Good evening good people. I have run across an issue that I am trying to resolve. Here is the context:
In an email template (using the email service provider Mad Mimi) I have a placeholder {name}
In my implementation of calling their API to send a transactional email, I am posting data using a cURL request. This data includes my api key and username, so I can't give that part of the code but here is a link to the documentation that I am using to try to get this done. (https://madmimi.com/developer/mailer/methods)
Here is the sample from the link above:
promotion_name=Welcome to Acme Widgets
recipient=Dave Hoover <dave#example.com>
body=--- \nname: Some YAML data\n
My PHP Code is this: (there are 2 other variables before these)
$myvars .= '&recipient='.$email;
$myvars .= '&promotion_name=Welcome';
$myvars .= '&body= name: Some YAML data';
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
return (curl_exec( $ch ));
The result that I get from the send is:
Email Result:Your body parameter was unable to be parsed, due to: (): mapping values are not allowed in this context at line 1 column 9. Please ensure the body parameter is valid YAML: --- name: Some YAML data...
Can anyone help out?
Thanks!!
Edit: I changed my code to be like this:
$url = 'https://api.madmimi.com/mailer';
$myvars = [
"username" => "xxxxxxxxxx",
"api_key" => "xxxxxxxxxx",
"recipient" => "xxxxx#gmail.com",
"promotion_name" => "Welcome",
"body" => "--- \n firstname:John\n"
];
error_log('Mailer API Variables: ' . $myvars);
//TODO: Put the email transaction ID into the database FUTURE PHASE
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
error_log (curl_exec( $ch ));
I tried the body variable two ways. One urlencoded, one not. Here are the responses from both tries.
[05-Dec-2020 10:20:55 America/Boise] Mailer API Variables: Array
[05-Dec-2020 10:20:56 America/Boise] Your email has {placeholders} in it, but you have not specified their replacements in the body parameter, which was: ---+%0A+firstname%3AJohn%0A
[05-Dec-2020 10:22:10 America/Boise] Mailer API Variables: Array
[05-Dec-2020 10:22:10 America/Boise] Your email has {placeholders} in it, but you have not specified their replacements in the body parameter, which was: ---
firstname:John
According to the docs, CURLOPT_POSTFIELDS takes either an urlencoded string or an array. Yours is neither, since the string you give contains spaces.
An array seems easier:
$myvars = [
"recipient" => $email,
"promotion_name" => "Welcome",
"body" => "--- \nname: Some YAML data\n"
];
By the way, you seem to not show your actual code. The error message you give says your YAML starts with --- but it doesn't in your code. The error implies that you simply forgot to include the linebreak after --- in your string.
Related
I would like to get the instance metadata (like AZ) for the current EC2, using AWS SDK.
I was able to find an alternative solution, but it is not using the SDK just a file_get_contents
How is it possible with the SDK?
The solution proposed by JasonQ-AWS is useful to get information about all instances and applications in your account. However, it does not tell you what information describes the instance that is really executed by the current process.
For that you have to use IMDSv2 which requires two CURL commands, the first one to get a TOKEN and the second one to get the actual metadata of the current instance.
In PHP the code can therefore be :
$ch = curl_init();
// get a valid TOKEN
$headers = array (
'X-aws-ec2-metadata-token-ttl-seconds: 10' );
$url = "http://169.254.169.254/latest/api/token";
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "PUT" );
curl_setopt( $ch, CURLOPT_URL, $url );
$token = curl_exec( $ch );
echo "<p> TOKEN :" . $token;
// then get metadata of the current instance
$headers = array (
'X-aws-ec2-metadata-token: '.$token );
$url = "http://169.254.169.254/latest/dynamic/instance-identity/document";
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "GET" );
$result = curl_exec( $ch );
echo "<p> RESULT :" . $result;
All you have to do is to extract the desired information. You can also ask for a unique information, such as the instance id with a more specific url like :
$url = "http://169.254.169.254/latest/meta-data/instance-id";
By current EC2 instance, are you referring to PHP code running on an EC2, and you would like to inject that metadata into some variables for use?
Or do you mean you have an object created with the PHP SDK such as with something like:
$ec2Client = new Aws\Ec2\Ec2Client([
'region' => 'us-east-1',
'version' => 'latest'
]);
If you mean the second way, you can access that data through describeInstances like this:
$result = $ec2Client->describeInstances();
echo "Instances: \n";
foreach ($result['Reservations'] as $reservation) {
foreach ($reservation['Instances'] as $instance) {
echo "InstanceId: {$instance['InstanceId']} - {$instance['State']['Name']} \n";
echo "Availability Zone: {$instance['Placement']['AvailabilityZone']} \n";
}
echo "\n";
}
You can also filter by adding parameters to the method call such as by type or instanceId.
If you're just running PHP code on the EC2 instance and you want that info, you can check out this page for some options: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
I don't think this is possible at all. IMDSv2 info like AZ, instance-id, instance-type, etc is readable via https://169.254.169.254 and if you look into the source code for the SDK, it only pulls temporary credentials via IMDSv2 (https://github.com/aws/aws-sdk-php/search?q=169.254)
and does not allow arbitrary IMDSv2 queries.
Unless I'm missing something, you need to pull this data yourself or use some 3rd-party library which does that for you in PHP.
I have php script hosted in ftp server.
Its accessed from android app.
I did enabled Google Cloud Messaging in android and also php script.
So I want to send message every one hour.
So I need php schedule for trigger every one hour.
Message is constant.
My php code is:
<?php
define( "API_ACCESS_KEY", "***********************");
// Message to be sent
$message = "welcome to android app";
//RegistrationIds
$registrationid = "******************";
//call to gcm notification
send_push_notification($registrationid,$message);
//gcm push notification function
function send_push_notification($registrationids,$messages){
//GCM Implementation Code
// Set POST variables
$url = "https://android.googleapis.com/gcm/send";
$fields = array(
'registration_ids' => array($registrationids),
'data' => array( "message" => $messages ),
);
$headers = array(
'Authorization: key=' . API_ACCESS_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 );
cur_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
}
?>
I want to call send push notification method every one hour.
You can use cron job for this. You dont have to add anything to the PHP script. Just running it every hour will solve the issue. Below is how you can add a cronjob. I believe you are on a Linux server.
0 * * * * /usr/bin/php /path/to/your/php/script.php
See this link to see how you can add/edit/delete cron tab - http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/
I have to send Push Notifications with different messages for large number of devices(More than 10k devices per day).But sometimes its not receiving all of the devices.I set up a function pushNotificationToUsers($heading,$message,$registraionids) to send the push notification and I am not sure about my method is correct ,if i am wrong please correct me.
function pushNotificationToUsers($heading,$message,$registraionids){
//array of registration ids in $registraionids
$key="xxxxxxxxxxx";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' =>,$registraionids,
'data' => array( "message" => $message,"title"=>$heading,"soundname"=>"beep.wav" ),
);
$headers = array(
'Authorization: key=' . $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 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
}
I'm using php in my serverside
For Android,
The message size limit in GCM is 4 kbytes.
https://developer.android.com/google/gcm/server.html#params
The message size limit in C2DM is 1024 bytes. (DEPRECATED)
https://developers.google.com/android/c2dm/#limitations
For iOS,
in iOS the size limit is 256 bytes, but since the introduction of iOS 8 has changed to 2kb!
https://forums.aws.amazon.com/ann.jspa?annID=2626
Also, see below stuffs
After Google replaced C2DM with GCM, they took off all limits.
http://developer.android.com/google/gcm/c2dm.html#history
The only limits you run into the GCM documentation is this:
http://developer.android.com/google/gcm/adv.html#lifetime
I think this answer is enough clear for your question.
I tried this code.
function sendNotification( $apiKey, $registrationIdsArray, $messageData )
{
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
$data = array(
'data' => $messageData,
'registration_ids' => $registrationIdsArray
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
And to call this function:
$message = "the test message";
$tickerText = "ticker text message";
$contentTitle = "content title";
$contentText = "content body";
$registrationId = 'APA91bEgsAG3vmliDnJE7jfLAOGSUv3K9p41MkNranPFV4EY0svABRax8NY5oulOHv7s3v2Ks_bQutsLLw8j4mHOr5LkrRlFfXxfs3hxxwAlxIOG7cXCB4YPhlLCDspVtImyWBL_znGgkZzEWCncV3tidHMV'; (Id is wrong here for security reasons)
$apiKey = "AIzaSyD6kZoY3Qb_1ut57IEmwdRg0JuxC42W1"; (Key is wrong here for security reasons)
$response = sendNotification(
$apiKey,
array($registrationId),
array('message' => $message, 'tickerText' => $tickerText, 'contentTitle' => $contentTitle, "contentText" => $contentText) );
echo $response;
And now i am stuck. I just create a PHP page with my own registration id of device and google API key.
But it shows me error of:
Unauthorized
Error 401
When i run this URL http://vbought.com/sendnotification.php
i even added my server IP and domain name in the GCM reference
.vbought.com/
*.vbought.com
50.87.3.82
is there something i did wrong? Or i need to know? I am just trying to send one message to my only device.
Thank you! (in advance)
i found the answer. And the answer is i dont need to define anything in GCM. Like i defined my domain name and IP address. So i dont need to do anything. Just leave it blank and it will work like charm...
have a nice day :)
I'm trying to set up a server status for the MMORPG Champions Online. I got some basic information from the web master and this is all he told me:
XML-RPC call to server: http://www.champions-online.com/xmlrpc.php
function name: wgsLauncher.getServerStatus
Parameter (language): en-US
Now, I found a nice example to start with here, and I ended up with this code:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
# Using the XML-RPC extension to format the XML package
$request = xmlrpc_encode_request("wgsLauncher.getServerStatus", "<param><value><string>en-US</string></value></param>", null );
# Using the cURL extension to send it off,
# first creating a custom header block
$header[] = "Host: http://www.champions-online.com:80/";
$header[] = "Content-type: text/xml";
$header[] = "Content-length: ".strlen($request) . "\r\n";
$header[] = $request;
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "http://www.champions-online.com/xmlrpc.php"); # URL to post to
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header ); # custom headers, see above
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' ); # This POST is special, and uses its specified Content-type
$result = curl_exec( $ch ); # run!
curl_close($ch);
echo $result;
?>
But I'm getting a "400 Bad Request" error. I'm new to XML RPC and I barely know php, so I'm at a loss. The examples from the php site show how to use an array as a parameter, but nothing else.
I obtained the parameter string <param><value><string>en-US</string></value></param> from this XMLRPC Debugger (very nice btw). I entered the parameter I needed in the "payload" box and this was the output.
So, I would appreciate any help on how to pass this parameter to the header.
Note: My host supports xmlrpc but it seems the function "xmlrpc_client" doesn't exist.
Update: The web master replied with this information, but it's still not working... it's getting to the point I may just scrape the status off the page.
$request = xmlrpc_encode_request("wgsLauncher.getServerStatus", "en-US" );
Ok, I finally figured out my answer... It seemed to be a problem in the header, because it worked when I changed the cURL code to match the code I found it on this site. The post is about how to remotely post to wordpress using XMLRPC in php.
This is the code I ended up with:
<?php
// ini_set('display_errors', 1);
// error_reporting(E_ALL);
# Using the XML-RPC extension to format the XML package
$request = xmlrpc_encode_request( "wgsLauncher.getServerStatus", "en-US" );
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, "http://www.champions-online.com/xmlrpc.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$result = curl_exec($ch);
curl_close($ch);
$method = null;
$params = xmlrpc_decode_request($result, &$method);
# server status result = true (up) or false (down)
$status = ($params['status']) ? 'up' : 'down';
$notice = ($params['notice'] == "") ? "" : "Notice: " + $params['notice'];
echo "Server Status: " . $status . "<br>";
echo $notice;
?>