Failed to send Push Notification - php

I try to send a message, but get nothing. Although no fails, when printing the variable:
$result
this returns "to" (I have no idea why).
The code I use is :
private function sendMessageGcm($registration_id,$message){
$this->key = "xxxxxxxxxxxxxxxxxxxxxx";
$data = array(
"registration_id" => $registration_id,
"data" => $message
);
$headers = array(
"Content-Type:application/json",
"Authorization:key=" . $this->key
);
$ch = curl_init();
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_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
if($result == false) {
echo('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
$rtn["code"] = "000";//means result OK
$rtn["msg"] = "OK";
$rtn["result"] = $result;
return($rtn);
}

$data and $registration_id must be an array to work with push notifications. so it should be like.
$data = array(
"registration_ids" => array($registration_id),
"data" => array(
"body" => $message,
),
);

Related

PHP CURL BadRequest

I am attempting to send a print job through PrintNode. I keep getting met with the same error message:
code: BadRequest
message: Incorrect request body: (request body).content must be present
I am relatively new to CURL, here is my code:
$pdf_path = plugin_dir_url( __FILE__ ) . 'pdfs/Order8221.pdf';
$url = 'https://api.printnode.com/printjobs';
$data_array = array(
'printerId' => 70029019,
'title' => 'My test print',
'contentType' => 'pdf_uri',
'content' => $pdf_path,
'source' => 'api doc'
);
$data = json_encode($data_array);
echo'<br/>';
print_r($data);
echo '<br/>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, 'API KEY*******' . ":" . '');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-Type: application/json');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
Any help would be greatly appreciated.
I replaced
$data = json_encode($data_array);
with :
$data = http_build_query($data_array);
and it worked.

Mailgun send mail with attachment

I am trying to send a mail with attachments with mailgun.
The mail itself is fine, but it is missing the attachment.
Also in the mailgun log it shows up fine, but the attachment array is empty.
I replaced my credentials with example.com.
The file is placed in a subdirectory and is readable.
$filename = 'directory/example.pdf';
$parameters = array('from' => 'Example <example#mail.example.com>',
'to' => 'example#example.com',
'subject' => 'Subject',
'text' => 'This is just a test.',
'attachment[1]' => '#' . $filename);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v3/mail.example.com/messages');
curl_setopt($ch, CURLOPT_USERPWD, 'api:key-ThisIsJustARandomString');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
I don't get an error, this is the $response:
string(103) "{
"id": "<20170514122638.8820.55203.4543B111#mail.example.com>",
"message": "Queued. Thank you."
}"
Within the mailgun logs no attachments are listed:
"message": {
"headers": {
"to": "example#example.com",
"message-id": "20170514122638.8820.55203.4543B111#mail.example.com",
"from": "Example <example#mail.example.com>",
"subject": "Subject"
},
"attachments": [],
"size": 349
},
According to all documentation I found this would be the correct solution, but it is not working.
Thanks in advance for all replies.
Change your first code to:
$filename = 'directory/example.pdf';
$parameters = array('from' => 'Example <example#mail.example.com>',
'to' => 'example#example.com',
'subject' => 'Subject',
'text' => 'This is just a test.',
'attachment[1]' => curl_file_create($filename, 'application/pdf', 'example.pdf'));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v3/mail.example.com/messages');
curl_setopt($ch, CURLOPT_USERPWD, 'api:key-ThisIsJustARandomString');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
I changed '#'.$filename to curl_file_create($filename, 'application/pdf', 'example.pdf').
See documentation curl_file_create and check the notes for PHP < 5.5.
or use the api https://documentation.mailgun.com/en/latest/api-sending.html#examples
once the domains and parameters are set you can then just use $result = $mgClient->messages()->send( $domain, $params );
This worked for me.
<?php
$path = $filename;
define('MAILGUN_URL', 'https://api.mailgun.net/v3/domainname');
define('MAILGUN_KEY', 'private api key from mail gun');
**function sendmailbymailgun**($to,$toname,$mailfromname,$mailfrom,$subject,
$html,$text,$tag,$replyto, $path){
$array_data = array(
'from'=> $mailfromname .'<'.$mailfrom.'>',
'to'=>$toname.'<'.$to.'>',
'subject'=>$subject,
'html'=>$html,
'text'=>$text,
'o:tracking'=>'yes',
'o:tracking-clicks'=>'yes',
'o:tracking-opens'=>'yes',
'o:tag'=>$tag,
'h:Reply-To'=>$replyto,
'attachment[0]' => curl_file_create(__dir__."\\".$path, 'application/pdf', $path),
'attachment[1]' => curl_file_create(__dir__."\\".$path, 'application/pdf', "example.pdf")
);
$session = curl_init(MAILGUN_URL.'/messages');
curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($session, CURLOPT_USERPWD, 'api:'.MAILGUN_KEY);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $array_data);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($session);
curl_close($session);
$results = json_decode($response, true);
return $results;
}
//: call the function
$res = sendmailbymailgun("example#yahoo.com","Recipeint Name", "Sender Name", "sender#example.com","Email subject","Email body. find two attachment","","tags", "no-reply#example.com", $path);
echo "<pre>".print_r($res, true)."</pre>";
?>
$dest = "filepath/test.pdf";
$result = $mgClient->messages()->send($domain,
array('from' => 'Tester <test#test.com>',
'to' => 'test#test02.com',
'subject' => 'Testing',
'html' => '<h1>Normal Testing</h1>',
'attachment' => array(
array(
'filePath' => $dest,
'filename' => 'test.pdf'
)
)
));
This code is worked properly for me.
This works for me. I have passed the attachment file URL in the attachment array. now I can send multiple attachments in email.
$attachment = [ 0 =>
'https://www.crm.truerater.com/public/assets/client_upload_images/1634327873.png',
1 => 'https://www.crm.truerater.com/public/assets/client_upload_images/1634327873.png'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v3/truerater.com/messages');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$post = array(
'from' => $mailfromname .'<'.$mailfrom.'>',
'to' => $toname.'<'.$to.'>',
'cc' => '',
'bcc' => '',
'subject' => $subject,
'html'=>$html,
'text'=>$text,
'o:tracking'=>'yes',
'o:tracking-clicks'=>'yes',
'o:tracking-opens'=>'yes',
'o:tag'=>$tag,
'h:Reply-To'=>$replyto,
);
if(sizeOf($attachment) > 0){
$i=0;
foreach ($attachment as $attach){
$attachPath = substr($attach, strrpos($attach, '/public/') + 1);
$post['attachment['.$i.']'] = curl_file_create($attach, '', substr($attachPath, strrpos($attachPath, '/') + 1));
$i=$i+1;
}
}
$headers_arr = array("Content-Type:multipart/form-data");
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_USERPWD, 'api' . ':' . $key);
curl_setopt($ch, CURLOPT_HEADER, $headers_arr);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if (curl_errno($ch)) {
$result = curl_error($ch);
\Log::info($result);
}
else{
$result = json_decode($result,true);
}
curl_close($ch);
\Log::info($result);
return $result;

Not able to send push notifications in android even after getting success1 through my PHP script

My PHP script looks like this:
<?php
$reg_id = "d8Sq53-gteU:APA91bGFcbSrcWY6J9fVBhUJVci4YHgktjoTOTbRjMXi7uY6ss-kLM39GpSt16cMmwsm2k4n9y3_YrcyBT7o9bpsN2QFS_bVceMcV-WThbThXMCWSiwaaP7p5LAJlb_01mzPbHb6xq1X1";
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'to' => $reg_id ,
'priority' => "high",
'data' => array(
"title" => "Android Learning",
"message" => "Test",
"image"=> "dsdsd",
"tag" => "dsdsd"
)
);
$headers = array(
'Authorization:key = AIzaSyC6ld4WBRmk8W6DZgMqevu1Na3dcQdQDBIA ',
'Content-Type: application/json'
);
$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('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
print_r($result);die;
?>
This is the response I am getting:
{"multicast_id":7558168491201020947,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1484883356821016%9bd11ceef9fd7ecd"}]}
But in Android I am unable to get the data that I am posting through the notification. Is there a problem with PHP script that I am using, Is the response that I am getting through PHP script correct. Or there is some problem with the android code. Can anyone help me please.
**Please check below .php file it will working fine for me.**
**You just need to pass firebase id "fcm_token" parameter to this php file**.
<?php
require_once __DIR__ . '/config.php';
// need to pass Firebase Register ID.
$registration_ids=$_POST["fcm_token"];
$title='hello';
$message='Please check the Details';
$is_background=FALSE;
$image='';
$payload='Its Payload';
$timestamp='10:15';
$arr = array('title' => $title, 'is_background' => $is_background, 'message' => $message, 'timestamp' => $timestamp, 'image' => $image,'payload'=> $payload);
$arr1 = array('data' => $arr);
$json = $arr1;
$fields = array('to' => $registration_ids,'data' => $json,);
//echo json_encode($fields);
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . FIREBASE_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));
echo 'its Not done bro';
}else{
echo 'its done bro';
}
// Close connection
curl_close($ch);
?>
Finally got the code which is working for me-
`
$filename = 'Fav_Icon.png';
$title = "thisis title";
$coupon_id = 1;
$url = 'https://fcm.googleapis.com/fcm/send';
$msg = array
(
'message' => 'We have added a new Coupon. Please have a look !!!',
'title' => $title,
'smallIcon' => base_url().'uploads/icons/'.$filename,
'type' => 'Coupon',
'coupon_id' => $coupon_id
);
$res = array();
$res['data']['title'] = "Coupon Name";
$res['data']['message'] = "We have added a new Coupon. Please have a look !!!";
$res['data']['image'] = base_url().'uploads/icons/'.$filename;
$res['data']['tag'] = "Coupon";
$res['data']['coupon_id'] = $coupon_id;
$fields = array(
'to' => $reg_id ,
'priority' => "high",
'data' => $res
);
$headers = array(
'Authorization:key = AIzaSyC6ld4WBRmk8W6DZgMqevu1Na3dcQdQDBIER ',
'Content-Type: application/json'
);
$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('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
print_r($result);
return $result;
?>`

Warning on GCM with PHP

I'm using GCM in php. Everything is fine. But im getting response as
"Field \"data\" must be a JSON array: example\n"
My code for GCM is
function sendNotification($registrationIdsArray, $messageData) {
$data = array(
'data' => $messageData,
'registration_ids' => $registrationIdsArray
);
var_dump($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->header);
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 my $data object is
{"data":"example","registration_ids":["apikey1", "apikey2"]}
What is the missing code for GCM here.
the data which you are passing should be an array not a string like this
$messageData = array(
'success' => 1,
'title' => $data['title'],
'desc' => $data['message']
);

Add more variables in the URL via GET

I want to do have the possibility to pass parameters through the URL example.
www.example.com/index.php?msg=textOne&var2=textTwo&var3=textThree.
what do I need to change the code to make it work?
<?php
define("GOOGLE_API_KEY", ...);
define("GOOGLE_GCM_URL", "https://android.googleapis.com/gcm/send");
function send_gcm_notify($reg_id, $message, $text) {
$fields = array(
'registration_ids' => array( $reg_id ),
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, GOOGLE_GCM_URL);
curl_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));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Problem occurred: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
}
$reg_id = "APA91bHuSGES.....nn5pWrrSz0dV63pg";
$msg = filter_input (INPUT_GET, 'msg', FILTER_SANITIZE_STRING);
send_gcm_notify($reg_id, $msg,put);
If you want to use the array style:
....
$getParams = array(
'param1' => 'value',
'param2' => 'value2',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, GOOGLE_GCM_URL . '?' . implode('&', array_map('urlencode', $getParams)));
curl_setopt($ch, CURLOPT_POST, true);
....
Notice the usage of urlencode to insure your parameters are URL safe.

Categories