APNS PHP JSON Payload structure - php

I am sending push notifications via a PHP script to connect to APNS server. Everything is working fine when I use the below payload structure.
$body['aps'] = array(
'alert' => $message,
'badge' => $badge,
'sound' => 'default'
);
$payload = json_encode($body);
However, I need to add more parameters to the 'alert' element as well as want to add some more custom parameters. The way I do is is as follows, but APNS is not accepting the JSON. Is it a problem with my JSON creation method in PHP?
$payload='{
"aps": {
"alert":{
"title": "'.$message.'",
"body":"'.$notif_desc.'"
},
"badge":"'.$badge.'",
"sound": "default"
},
"type": "notification",
"id":"'.$lastid.'",
"date:"'.$date1.'"
}';
So basically, I have two queries. IS the second method wrong? If so, please show me a valid method to create nested JSON Payload for APNS server. Second question, I need to add custom PHP variables to the Payload, I want to know whether the way I have added it in the second method is right or wrong.
basically, I need to create a JSON object as below in PHP
{
"aps" : {
"alert" : {
"title" : "Game Request",
"body" : "Bob wants to play poker",
"action-loc-key" : "PLAY"
},
"badge" : 5,
},
"acme1" : "bar",
"acme2" : [ "bang", "whiz" ]
}

You're missing a double quote after the "date" property:
"date:"'.$date1.'"
... should be...
"date":"'.$date1.'"
I'd recommend putting the payload together as a PHP object/array first (like your original example) as it is much easier to see the structure in that format rather than a giant concatenated string. E.g.
$payload['aps'] = array(
'alert' => array(
'title' => $title,
'body' => $body,
'action-loc-key' => 'PLAY'
),
'badge' => $badge,
'sound' => 'default'
);
$payload['acme1'] = 'bar';
$payload['acme2'] = array(
'bang',
'whiz'
);
$payload = json_encode($body);

$send_data =
array(
'aps' =>
array
(
'status_code'=>200,
'alert'=>$message,
'sound' => 'default',
'notification_type'=>'DoctorPendingRequest',
'request_id'=>$request_id
)
);
Passs $send_data to payload.

Related

Guzzle: Sending POST with Nested JSON to an API

I am trying to hit a POST API Endpoint with Guzzle in PHP (Wordpress CLI) to calculate shipping cost. The route expects a RAW JSON data in the following format:
{
"startCountryCode": "CH"
"endCountryCode": "US",
"products": {
"quantity": 1,
"vid": x //Variable ID
}
}
Link to the API I am consuming: https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate
$body = [
"endCountryCode" => "US",
"startCountryCode" => "CN",
"products" => [
'vid' => $vid,
'quantity' => 1
],
];
$request = $this->client->request(
'POST', 'https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate',
[
'headers' => [
'CJ-Access-Token' => $this->auth_via_cj(), // unnecessary, no auth required. Ignore this header
],
'body' => json_encode( $body )
],
);
I've also tried using 'json' => $body instead of the 'body' parameter.
I am getting 400 Bad Request error.
Any ideas?
Try to give body like this.
"json" => json_encode($body)
I spent so many hours on this to just realise that products is actually expecting array of objects. I've been sending just a one-dimensional array and that was causing the 'Bad Request' error.
In order to fix this, just encapsulate 'vid' and 'quantity' into an array and voila!
You don't need to convert data in json format, Guzzle take care of that.
Also you can use post() method of Guzzle library to achieve same result of request. Here is exaple...
$client = new Client();
$params['headers'] = ['Content-Type' => 'application/json'];
$params['json'] = array("endCountryCode" => "US", "startCountryCode" => "CN", "products" => array("vid" => $vid, "quantity" => 1));
$response = $client->post('https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate', $params);

Inserting record in zoho api v2 in PHP

I want to insert data in zoho crm using api v2. first make an array then i encoded json .Request url https://www.zohoapis.com/crm/v2/Contacts.
But i got this error.
Code:
$authtoken = ***********;
$fields={"data":["{\"Last_Name\":\"Test John insert\",\"Email\":\"testjhon#jhon.com\"}"]};
$zoho_url = "https://www.zohoapis.com/crm/v2/Contacts";
Error:
{"data":[{"code":"INVALID_DATA","details":{"expected_data_type":"jsonobject","index":0},"message":"invalid data","status":"error"}]}
Working example:
$fields = json_encode(
array(
"data" => array([
"Company" => "abc",
"Last_Name" => "Tom",
"City" => "Egham"
],
[
"Company" => "abc",
"Last_Name" => "Jerry",
"City" => "Egham"
])
)
);
Send headers this way :
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($fields),
sprintf('Authorization: Zoho-oauthtoken %s', $oauth)
);
Use this json array:
$fields = "{\"data\":[{\"Last_Name\": \"Test\",\"First_Name\": \"TESTING\",\"Email\": \"demo#w3scloud.com\"}],\"trigger\":[\"approval\",\"workflow\"]}";
send this way :
[{ "data": \[ { "Company":"company name", "Last_Name":"your last name", "Phone":"123456789", "First_Name": "your first name", "Email":"first#gmail.com" } \], “triggger”:\[“workflow”,”approval”,”blueprint”\] }]
click here to view image (request and response via postman)
hope this will help you.
I've noticed that Zoho seems to want an extra pair of brackets around the data. And you might try encoding the data array to a JSON-string before sending it to cURL.
$fields = json_encode([
["data" => ["Last_Name" => "Test John insert","Email" => "testjhon#jhon.com"]],
]);
As #Ghost mentioned, you may also need to change the content-type. According to the PHP docs, passing an array to CURLOPT_POSTFIELDS will set the content-type to multipart/form-data; what you probably want is application/json.
CURLOPT_HTTPHEADER => array(
"Authorization: ".$authtoken,
"Content-Type: application/json"
),
You must send the json file to zoho api, and all be works.:
$fields=["data"=> ['Last_Name'=>'Test John insert','Email'=>'testjhon#jhon.com']];
$fields = json_encode($fields);

Field "to" must be a JSON string [Firebase]

I'm trying to send notification using a cron job. I migrated from GCM to FCM. In my server side, I changed https://android.googleapis.com/gcm/send to https://fcm.googleapis.com/fcm/send and also updated on how to request the data changing registration_ids to to. Checking the json passed it is a valid json but I'm having an error Field "to" must be a JSON string. Is there anyway to solve this?
Here is my code
function sendNotificationFCM($apiKey, $registrationIDs, $messageText,$id) {
$headers = array(
'Content-Type:application/json',
'Authorization:key=' . $apiKey
);
$message = array(
'to' => $registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($message)
));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Try explicitly converting $registrationIDs to string.
$message = array(
'to' => (string)$registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
);
Edited Answer
The 'to' parameter requires a string - which is the recipient of the message.
The $registrationIDs could be passed a separate parameter (as string array) to 'registration_ids'
Edit your code to something like this:
$recipient = "YOUR_MESSAGE_RECIPIENT";
$message = array(
'to' => $recipient,
'registration_ids' => $registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
);
Where $recipient is
a registration token, notification key, or topic.
Refer this:
Firebase Cloud Messaging HTTP Protocol
Try making to as a string:
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
...
},
}
// if you are using an array like
$fcm_ids = array();
$fcm_ids[] = "id_1";
$fcm_ids[] = "id_2";
$fcm_ids[] = "id_3";
//.
//.
//.
$fcm_ids[] = "id_n";
// note: limit is 1000 to send notifications to multiple ids at once.
// in your messsage send notification function use ids like this
$json_data = [
"to" => implode($fcm_ids),
"notification" => [
"title" => $title,
"body" => $body,
],
"data" => [
"str_1" => "something",
"str_2" => "something",
.
.
.
"str_n" => "something"
]
];
I had a similar problem. It turns out when I retrieved the Registration Token from my Firebase database (using this Firebase PHP Client), it was returned with double quotes at the beginning and at the end of the token. So I had to remove the first and last characters from the token before I could use it. The code below solved my problem
substr($registrationToken, 1, -1)

How can I change my JSON object with PHP?

I don't know any PHP but i need to get my JSON object to look a certain way
$body['aps'] = array(
'alert' => "look at this stuff",
'sound' => 'default'
);
$payload = json_encode($body);
How can I make the JSON object look like
{
"aps":
{
"alert": "look at this stuff",
"sound": 'default'
},
"view": "wc1"
}
Are you trying to insert another value into $body?
$body['aps'] = array(
'alert' => "look at this stuff",
'sound' => 'default'
);
$body['view'] = 'wc1';
$payload = json_encode($body);

PHP how to create JSON with localization arguments for APNS

I want to send JSON in an APNS with the following:
{
"aps" : {
"alert" : {
"loc-key" : "GAME_PLAY_REQUEST_FORMAT",
"loc-args" : [ "Jenna", "Frank"]
},
"sound" : "default"
},
}
Can anyone explaine how I can create this in PHP?
I have the following for JSON without the key/args:
$body['aps'] = array(
'alert ' => 'This is my messsage',
'sound' => 'default'
);
$payload = json_encode($body);
I have tried to replace the 'This is my message' with an array for loc-key and loc-args but that does not work. Also jus putting in the data as string does not work..
Hope someone can help me. I have tried multiple options and variations but nothing works..
$body = array(
"aps" => array(
"alert" => array(
"loc-key" => "GAME_PLAY_REQUEST_FORMAT",
"loc-args" => array( "Jenna", "Frank" )
),
"sound" => "default",
),
);
echo json_encode($body);
$body['aps']['alert'] = array(
"loc-key" => "GAME_PLAY_REQUEST_FORMAT",
"loc-args" => array("Jenna", "Frank")
);
just replace the content

Categories