how to send the JSON also from the PHP API - php

I'm sending a text push from the php API code successfully, but I wonder how to send the JSON also from the PHP API
My problem is that when I send JSON from the PHP API code it received like like a "message" type.
When i send the same JSON code from the parse control panel it works fine
I so some hint to send "uri" key in the data, but it didn't help.
What am I missing?
Thanks.
this is the PHP code that i'm using
<?php
$APPLICATION_ID = "gggggggggggggggg";
$REST_API_KEY = "xxxxxxxxxxxxxxxxxxx";
//$MESSAGE = "your-alert-message";
if (!empty($_POST)) {
$errors = array();
foreach (array('app' => 'APPLICATION_ID', 'api' => 'REST_API_KEY', 'body' => 'MESSAGE') as $key => $var) {
if (empty($_POST[$key])) {
$errors[$var] = true;
} else {
$$var = $_POST[$key];
}
}
if (!$errors) {
$url = 'https://api.parse.com/1/push';
if(strstr($MESSAGE,"{")){ //json
$data['data_type']='json';
//$MESSAGE = json_decode($MESSAGE);
}
//, 'uri' => $MESSAGE
$data = array(
'channel' => 'test1',
'type' => 'android',
'expiry' => 1451606400,
'data_type' => 'json',
'data' =>array(
'alert'=> "the link2",
'uri' => $MESSAGE
),
'uri' => $MESSAGE
);
//var_dump( $data );die;
//if(strstr($MESSAGE,"{")) //json
//$data['data_type']='json';
$_data = json_encode($data);
//var_dump( $_data );die;
$headers = array(
'X-Parse-Application-Id: ' . $APPLICATION_ID,
'X-Parse-REST-API-Key: ' . $REST_API_KEY,
'Content-Type: application/json',
'Content-Length: ' . strlen($_data)
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
}
}
?>
In the parse.com website there is a tool that you can send PUSH and in this tool you can send push with 2 types: plain text, or JSON.
it's look like that
When I try to send push with this parse.com tool in both types it works fine and I get the push properly
But, when I try to send to push from my PHP API code as a "JSON" I always got it as a "plain text"
What am I'm doing wrong ?

It depends on your JSON structure for example i want to send this:
{
"data": {
"date": "2015-12-09",
"message": "and when you open this we will show you a message.",
"title": "6 Notice Click On It :)))",
"url": ""
},
"is_background": false
}
and in your php you should send like this:
$data = array(
'where' => '{}', // send to all users
// 'channels' => '{my_channel_name}',
'data' => array(
'is_background'=>false,
'data'=>array(
'date'=>'2015-12-09',
'message'=>'and when you open this we will show you a message',
'title'=>' Notice Click On It',
'url'=>''
),
),
);

Related

How to add image to android push notification from firebase. developed using ionic 3

I want to add an image to push notification. am using firebase and app is developed using ionic 3 frameworks. I have a web app to push the notification. this is the PHP code. Please help me to add an image to push notification.
public function pushNotification($title, $body, $image) {
//FCM API end-point
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = 'xxxx';
$target = [];
$targets = $this->db->get('device_ids')->result();
foreach($targets as $val) {
array_push($target, $val->device_id);
}
$fields = array();
$fields['notification'] = array(
'title' => $title,
'body' => $body
);
if(is_array($target)){
$fields['registration_ids'] = $target;
}else{
$fields['to'] = 'news';
}
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$server_key
);
//CURL request to route notification to FCM connection server (provided by Google)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Oops! FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
print_r(json_encode($fields));
}
$tokenListAndroid = "YOUR_TOKEN";
define( 'API_ACCESS_KEY', 'YOUR_KEY');
$Message='YOUR_MESSAGE';
$offerId=$_POST['offerId'];
$iOSids = explode(",",$tokenListiOS);
$androidIds = explode(",",$tokenListAndroid);
$msg = array
(
'title' => 'TEXT',
'message' => 'TEXT',
'summaryText' => 'TEXT',
'orderId' => 'TEXT',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'image' => 'YOUR_ICON_PATH ex. https://carboncostume.com/wordpress/wp-content/uploads/2016/08/blackpanther.jpg',
'style' => 'picture',
'picture' => 'YOUR_IMAGE_PATH ex. https://carboncostume.com/wordpress/wp-content/uploads/2016/08/blackpanther.jpg',
//'ongoing' => true,
'vibrate' => 1,
'sound' => 1
);
$fields = array
(
'registration_ids' => $androidIds,
'data' => $msg
);
//echo json_encode( $fields ); die;
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
Thats all XD
This is for IONIC 3
notification with Image and Text from firebase
Implement Phonegap Push Plugin and create your firebase project
ionic cordova plugin add phonegap-plugin-push
//Now we send the Notification
Post service
URL=https://fcm.googleapis.com/fcm/send
Header: Authorization: key={Your Firebase Key}
Content-Type: application/json
then send Body
Body:
***
{
"to": "/topics/college",
"data": {
"title": "Notification With Image",
"message": "This is my Notification with Image",
"style": "picture",
"picture": https://appsolzone.com/wp-content/uploads/2018/07/Scholar-Wings-2-480x336.jpg",
"summaryText": "This is image notification with Firebase in IONIC"
}
}

Payload was not valid JSON Slack Webhooks PHP

Slack Incoming Webhooks returns Payload was not valid JSON and the documentation doesn't seem to make a whole lot of sense.
public function index() {
$message = [
"pretext" => "There's been a sale on Example Cart",
"title" => "Sales Order #123456 on Example Cart",
"title_link" => "http://www.example.com/admin/index.php?route=sale/order/info&order_id=123456",
"text" => "There's been a new sale on the Example website. Click the order above to check it out.",
];
$send = self::slack($message);
dd($send); // die and dump curl result
}
public static function slack($message, $room = "test-messages", $color = "#ED7100", $icon = ":mailbox:") {
foreach ($message as $key => $value):
$message[$key] = str_replace(["<", ">", "&"], ["<", ">", "&"], $value);
endforeach;
$fallback = $message["pretext"] . " - " . $message["title"] . " - " . $message["title_link"];
$attachments = [
"fallback" => $fallback,
"pretext" => $message["pretext"],
"title" => $message["title"],
"title_link" => $message["title_link"],
"text" => $message["text"],
"color" => $color,
];
$payload = [
"channel" => "#{$room}",
"channel" => "#bossman",
"icon_emoji" => $icon,
"username" => "webhook-tests",
"attachments" => [$attachments]
];
$data = "payload=" . json_encode($payload);
$ch = curl_init("https://hooks.slack.com/services/endpoint");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
When I lint the JSON in any of the online linters it returns as valid JSON.
What is Slack looking for that's not in the documentation?
It looks like your POST data is being sent with payload= at the front instead of as the key.
This gist sends the data like so:
$data = json_encode($payload);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('payload' => $data));

Python to PHP - Azure Machine Learning

Hi im trying to translate this python script to php. I don't have much knowledge of Python and limited for PHP.
The python script is:
import urllib2
import json
data = {
"Inputs": {
"input1": {
"ColumnNames": ["Client_ID"],
"Values": [ [ "0" ], [ "0" ], ]
},
},
"GlobalParameters": {}
}
body = str.encode(json.dumps(data))
url = 'https://ussouthcentral.services.azureml.net/workspaces/3e1515433b9d477f8bd02b659428cddc/services/cb1b14b17422435984943d51b5957ec7/execute?api-version=2.0&details=true'
api_key = 'abc123'
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib2.Request(url, body, headers)
try:
response = urllib2.urlopen(req)
result = response.read()
print(result)
except urllib2.HTTPError, error:
print("The request failed with status code: " + str(error.code))
print(error.info())
print(json.loads(error.read()))
In a bid to try and convert it myself, here is what I have done so far:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$data = array(
'Inputs'=> array(
'input1'=> array(
'ColumnNames' => ["Client_ID"],
'Values' => [ [ "0" ], [ "0" ], ]
),
),
'GlobalParameters'=> array()
);
$body = json_encode($data);
$url = 'https://ussouthcentral.services.azureml.net/workspaces/3e1515433b9d477f8bd02b659428cddc/services/cb1b14d17425435984943d41a5957ec7/execute?api-version=2.0&details=true';
$api_key = 'abc123';
$headers = array('Content-Type'=>'application/json', 'Authorization'=>('Bearer '+ $api_key));
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($curl);
var_dump($result);
im sure I have got lots wrong but would appreciate the help.
thanks
I just had to do this myself and though I'd provide an answer for you. If you're going to talk to Azure's ML platform using php, you need to build your CURL call like this:
$data = array(
'Inputs'=> array(
'input1'=> array(
'ColumnNames' => array("header1", "header2", "header3"),
'Values' => array( array("value1" , "value2" , "value3"))
),
),
'GlobalParameters'=> null
);
$body = json_encode($data);
$url = 'your-endpoint-url';
$api_key = 'your-api-key';
$headers = array('Content-Type: application/json', 'Authorization:Bearer ' . $api_key, 'Content-Length: ' . strlen($body));
$this->responseArray['body'] = $body;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
Of all the places to get hung up, it was on the GlobalParameters for me, and is for you, too. You need this instead:
GlobalParameters => null
This generates the following JSON
GlobalParameters: {}
whereas
GlobalParameters => array()
gives
GlobalParameters: []
it's a subtle distinction, but enough to make Azure throw a hissy fit.
I didn't test using your curl_setopt functions and instead used what I've included in my example. I'm assuming it will work using the curl_setopts you have, but I don't know for sure.
I had some trouble adapting this perfectly, and I wanted to be able to easily work with JSON & Guzzle. Below is the solution that I built.
First is the function for making the actual call to Azure. Note that Guzzle wants your URL to be split into the domain and URI pieces.
This should all be in your .env file (if you're using Laravel at least).
AZURE_BASE=https://ussouthcentral.services.azureml.net
AZURE_URL=/workspaces/[[YOUR_STUFF_HERE]]/services/[[YOUR_STUFF_HERE]]/execute?api-version=2.0&format=swagger
AZURE_PRIMARY_KEY=[[YOUR_KEY]]
use GuzzleHttp\Client;
public function learn () {
$client = new Client([
'base_uri' => env('AZURE_BASE'),
'timeout' => 2.0,
]);
$headers = [
'Authorization' => 'Bearer ' .env('AZURE_PRIMARY_KEY'),
'Accept' => 'application/json',
'Content-Type' => 'application/json'
];
$data = $this->test_data();
$body = json_encode($data);
$response = $client->request('POST', env('AZURE_URL'), [
'headers' => $headers,
'body' => $body
]);
return $response;
}
As other answers have noted, the data setup is very touchy. new \stdClass is the key here, as we need to end up with a JSON Object ({}) not an array ([]). stdClass creates that empty object for us.
function test_data () {
return array(
'Inputs'=> array(
'input1'=> array(
[
'DESC' => "",
'2-week-total'=> "1",
'last-week'=> "1",
'this-week'=> "1",
'delta'=> "1",
'normalized delta'=> "1",
'delta-percent'=> "1",
'high-total-delta'=> "1",
'high-total-amt'=> "1",
'role'=> ""
]
),
),
'GlobalParameters'=> new \stdClass,
);
}
Now when you call ->learn(), you'll get back some nice JSON to do what you need.

Use collapse key for 2 type ofmessages gcm

In my gcm android app I am sending 2 types of messages from application server.I got the idea about what is collapse key, but Idont know how to use.These are the two types of messages.
1.
$message = array(
"price" => "signal",
"type" => $user_type,
"date" => $date1,
"name" => $signal_name,
"buy" => $price,
"stop" => $stop,
"tv" => $trig_value,
"tp" => $profit,
"res" => $result,
);
second one
$message = array(
"price" => "instru",
"price1" => $trade1,
"price2" => "$trade2",
"price3" => "$trade3",
"price4" => "$trade4",
"price5" => "$date"
);
What I need is the last messages send for both of the message types persist in gcm server.How can I do that.I am giving the gcm class also .Please help.
GCM.php
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key='.GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
You should add the collapse_key parameter to your JSON.
The JSON should look like this :
For example, for the first type :
{
"registration_ids":["...", "..."],
"collapse_key": "type1",
"data": {
"price" => "...",
"type" => "...",
...
},
}
For the second type, give a different value to collapse_key.
Based on your code and my limited knowledge of PHP, you need something like this :
$fields = array(
'collapse_key' => $collapse_key,
'registration_ids' => $registatoin_ids,
'data' => $message,
);
And the $collapse_key should be initialized based on the type of data you have in $message.

POST request with JSON body

I would like to add a post to a Blogger blog via PHP.
Google provided the example below. How to use that with PHP?
You can add a post for a blog by sending a POST request to the post
collection URI with a post JSON body:
POST https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/
Authorization: /* OAuth 2.0 token here */
Content-Type: application/json
{
"kind": "blogger#post",
"blog": {
"id": "8070105920543249955"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}
You need to use the cURL library to send this request.
<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';
// The data to send to the API
$postData = array(
'kind' => 'blogger#post',
'blog' => array('id' => $blogID),
'title' => 'A new post',
'content' => 'With <b>exciting</b> content...'
);
// Setup cURL
$ch = curl_init('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Authorization: '.$authToken,
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Close the cURL handler
curl_close($ch);
// Print the date from the response
echo $responseData['published'];
If, for some reason, you can't/don't want to use cURL, you can do this:
<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';
// The data to send to the API
$postData = array(
'kind' => 'blogger#post',
'blog' => array('id' => $blogID),
'title' => 'A new post',
'content' => 'With <b>exciting</b> content...'
);
// Create the context for the request
$context = stream_context_create(array(
'http' => array(
// http://www.php.net/manual/en/context.http.php
'method' => 'POST',
'header' => "Authorization: {$authToken}\r\n".
"Content-Type: application/json\r\n",
'content' => json_encode($postData)
)
));
// Send the request
$response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);
// Check for errors
if($response === FALSE){
die('Error');
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData['published'];
I think cURL would be a good solution. This is not tested, but you can try something like this:
$body = '{
"kind": "blogger#post",
"blog": {
"id": "8070105920543249955"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: OAuth 2.0 token here"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);
If you do not want to use CURL, you could find some examples on stackoverflow, just like this one here: How do I send a POST request with PHP?. I would recommend you watch a few tutorials on how to use GET and POST methods within PHP or just take a look at the php.net manual here: httprequest::send. You can find a lot of tutorials: HTTP POST from PHP, without cURL and so on...
I made API sending data via form on website to prosperworks based on #Rocket Hazmat, #dbau and #maraca code.
I hope, it will help somebody:
<?php
if(isset($_POST['submit'])) {
//form's fields name:
$name = $_POST['nameField'];
$email = $_POST['emailField'];
//API url:
$url = 'https://api.prosperworks.com/developer_api/v1/leads';
//JSON data(not exact, but will be compiled to JSON) file:
//add as many data as you need (according to prosperworks doc):
$data = array(
'name' => $name,
'email' => array('email' => $email)
);
//sending request (according to prosperworks documentation):
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-Type: application/json\r\n".
"X-PW-AccessToken: YOUR_TOKEN_HERE\r\n".
"X-PW-Application:developer_api\r\n".
"X-PW-UserEmail: YOUR_EMAIL_HERE\r\n",
'method' => 'POST',
'content' => json_encode($data)
)
);
//engine:
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
//compiling to JSON (as wrote above):
$resultData = json_decode($result, TRUE);
//display what was sent:
echo '<h2>Sent: </h2>';
echo $resultData['published'];
//dump var:
var_dump($result);
}
?>
<html>
<head>
</head>
<body>
<form action="" method="POST">
<h1><?php echo $msg; ?></h1>
Name: <input type="text" name="nameField"/>
<br>
Email: <input type="text" name="emailField"/>
<input type="submit" name="submit" value="Send"/>
</form>
</body>
</html>
<?php
// Example API call
$data = array(array (
"REGION" => "MUMBAI",
"LOCATION" => "NA",
"STORE" => "AMAZON"));
// json encode data
$authToken = "xxxxxxxxxx";
$data_string = json_encode($data);
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://domainyouhaveapi.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Content-Length: ' . strlen($data_string) ,
'API-TOKEN-KEY:'.$authToken )); // API-TOKEN-KEY is keyword so change according to ur key word. like authorization
// execute the request
$output = curl_exec($ch);
//echo $output;
// Check for errors
if($output === FALSE){
die(curl_error($ch));
}
echo($output) . PHP_EOL;
// close curl resource to free up system resources
curl_close($ch);

Categories