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);
Related
I am getting the JSON output below:
{
"clientCorrelator": "58a1acaf3ebf0",
"referenceCode": "REF-12345",
"endUserId": "263774705932",
"transactionOperationStatus": "Charged",
"paymentAmount": {
"0": {
"amount": 34,
"currency": "USD",
"description": "Ecofarmer Bulk Sms Online payment"
}
},
"chargeMetaData": {
"channel": "WEB",
"purchaseCategoryCode": "Online Payment",
"onBeHalfOf": "Paynow Topup"
},
"merchantCode": "42467",
"merchantPin": "1357",
"merchantNumber": "771999313"
}
I want to get the output below but somehow my php to JSON object conversion is turning the "charginginformation" key to "0".
$payment_amount = array(
$charginginformation = array(
'amount' => 34,
'currency' => 'USD',
'description' => 'Ecofarmer Bulk Sms Online payment'
)
);
$charge_data = array(
'channel' => 'WEB',
'purchaseCategoryCode' => 'Online Payment',
'onBeHalfOf' => 'Paynow Topup'
);
//API Url
$url = '';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'clientCorrelator' => $u_id,
'referenceCode' => 'REF-12345',
'endUserId' => '263774705932',
'transactionOperationStatus' => 'Charged',
'paymentAmount' => $payment_amount,
'chargeMetaData' => $charge_data,
'merchantCode' => '42467',
'merchantPin' => '1357',
'merchantNumber' => '771999313'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData, JSON_FORCE_OBJECT);
How can I stop the json_encode from changing the key?
Your issue is here:
$payment_amount = array(
//this is essentially array("cat", "dog", "etc");
$charginginformation = array(
'amount' => 34,
'currency' => 'USD',
'description' => 'Ecofarmer Bulk Sms Online payment'
)
);
You are adding an element to an array with a numeric index
To get this to work do
$payment_amount = array(
"charginginformation" => array(
//array data
)
);
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)
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.
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
What is the easiest way to send an email via Mailchimp's Mandrill service (using the API).
Here's the send method: https://mandrillapp.com/api/docs/messages.html#method=send
Here's the API wrapper: https://bitbucket.org/mailchimp/mandrill-api-php/src/fe07e22a703314a51f1ab0804018ed32286a9504/src?at=master
But I can't figure out how to make an PHP function that will send and email via Mandrill.
Can anyone help?
We also have an official API wrapper for PHP, which is available on Bitbucket or via Packagist, which wraps the Mandrill API for you.
If your Mandrill API key is stored as an environment variable, here's a simple example of sending using a template, with some merge variables and metadata:
<?php
require 'Mandrill.php';
$mandrill = new Mandrill();
// If are not using environment variables to specific your API key, use:
// $mandrill = new Mandrill("YOUR_API_KEY")
$message = array(
'subject' => 'Test message',
'from_email' => 'you#yourdomain.example',
'html' => '<p>this is a test message with Mandrill\'s PHP wrapper!.</p>',
'to' => array(array('email' => 'recipient1#domain.example', 'name' => 'Recipient 1')),
'merge_vars' => array(array(
'rcpt' => 'recipient1#domain.example',
'vars' =>
array(
array(
'name' => 'FIRSTNAME',
'content' => 'Recipient 1 first name'),
array(
'name' => 'LASTNAME',
'content' => 'Last name')
))));
$template_name = 'Stationary';
$template_content = array(
array(
'name' => 'main',
'content' => 'Hi *|FIRSTNAME|* *|LASTNAME|*, thanks for signing up.'),
array(
'name' => 'footer',
'content' => 'Copyright 2012.')
);
print_r($mandrill->messages->sendTemplate($template_name, $template_content, $message));
?>
Mandrill take HTTP POST requests for all of their API methods, and they take your input as a JSON string. Here's a basic example of sending an email. It uses cURL to do the HTTP request:
$uri = 'https://mandrillapp.com/api/1.0/messages/send.json';
$postString = '{
"key": "YOUR KEY HERE",
"message": {
"html": "this is the emails html content",
"text": "this is the emails text content",
"subject": "this is the subject",
"from_email": "someone#example.com",
"from_name": "John",
"to": [
{
"email": "blah#example.com",
"name": "Bob"
}
],
"headers": {
},
"track_opens": true,
"track_clicks": true,
"auto_text": true,
"url_strip_qs": true,
"preserve_recipients": true,
"merge": true,
"global_merge_vars": [
],
"merge_vars": [
],
"tags": [
],
"google_analytics_domains": [
],
"google_analytics_campaign": "...",
"metadata": [
],
"recipient_metadata": [
],
"attachments": [
]
},
"async": false
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
$result = curl_exec($ch);
echo $result;
// Simply Send Email Via Mandrill...
require_once 'Mandrill.php';
$mandrill = new Mandrill($apikey);
$message = new stdClass();
$message->html = "html message";
$message->text = "text body";
$message->subject = "email subject";
$message->from_email = "address#example.com";
$message->from_name = "From Name";
$message->to = array(array("email" => "recipient#example.com"));
$message->track_opens = true;
$response = $mandrill->messages->send($message);
This is the most basic piece of code I could give you, I just craft it seconds ago for a client and it's working smooth.
require_once 'path/to/your/mandrill/file/Mandrill.php';
try {
$mandrill = new Mandrill('your-API-key');
$message = array(
'html' => $htmlMessage,
'subject' => $subject,
'from_email' => $fromEmail,
'from_name' => $fromName,
'to' => array(
array(
'email' => $toEmail,
'name' => $toName,
'type' => 'to'
)
)
);
$result = $mandrill->messages->send($message);
print_r($result);
} catch(Mandrill_Error $e) {
echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
throw $e;
}
Also check their send method for more options like headers, meta-data, attachments etc. https://mandrillapp.com/api/docs/messages.php.html#method-send
Include the PHP API: https://bitbucket.org/mailchimp/mandrill-api-php
Code: https://mandrillapp.com/api/docs/messages.php.html#method-send
You can use ZF's autoloading for including the wrapper class or Composer: https://mandrillapp.com/api/docs/index.php.html