FCM message not delivered to device when sent from php - php

I am trying to implement FCM in my app. Right now, I am able to receive messages when i send them from firebase app console. But when i try to send messages from my php code on the server, the message does not get delivered to the phone. However, I get the message_id with numbers whenever the call to FCM is completed and no indication of any errors. Any help would be appreciated.
PHP code:
public function send_fcm() {
$API_ACCESS_KEY = '*****************************';
$msg = array ('message' => 'here is a message. message',
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...',
'vibrate' => 1,
'sound' => 1
);
$fields = array('to' => '/topics/mytopic',
'priority' => 'high',
'data' => $msg);
$headers = array('Authorization: key=' . $API_ACCESS_KEY,
'Content-Type: application/json');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
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));
$pushResult = curl_exec($ch);
curl_close($ch);
}

you should provide notification with fields array , I use this method to send notification using PHP
public static function toDevice($token , $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'to' => $token,
'notification' => [
"body" => $message ,
...
] ,
"data" => [
...
]
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "XXXXXXXXXXXXXXXXXXX",
'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_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
curl_close ( $ch );
return $result;
}

Your correction code this..it is tested code.
or follow this link : https://inducesmile.com/android/android-firebase-cloud-messaging-push-notification-with-server-admin-in-php-and-mysql-database/
public function send_fcm($token) {
$url = "https://fcm.googleapis.com/fcm/send";
$msg = array('message' => 'here is a message. message',
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...',
'vibrate' => 1,
'sound' => 1
);
$fields = array('to' => $token,
'priority' => 'high',
'data' => array('message' => $msg)
);
$headers = array(
'Authorization:key=*****************************',
'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));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);
if ($result === FALSE) {
die('CURL FAILED ' . curl_error($ch));
}
$info = curl_getinfo($ch);
curl_close($ch);
return array('result' => $result, 'status' => $info['http_code']);
}

Related

Receive Push Notification Twice firebase PHP Script

I'm new to Firebase Send Push Notification. I'm working on Send Push notification To multiple Users Using PHP Script.
PHP SCRIPT
function sendPushNotification($fb_key_array, $title) {
$finalPostArray = array('registration_ids' => $fb_key_array,
'notification' => array(
'title' => $title,
'sound' => 'default',
'badge' => '1'
),
'priority' => 'high',
);
$server_key = env("SERVER_KEY");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($finalPostArray)); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: key=' . $server_key));
$server_output = curl_exec($ch);
print_r($server_output);
return $server_output;
curl_close($ch);
}
I'm send notification using Queue Jobs on Particular Time.
I have a problem when I send Three notification at same time than Notification receive Twice.
Response From This Curl
App\Jobs\PushNotification
<pre>{"multicast_id":4668247729883149905,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1616386021446151%e609af1cf9fd7ecd"}]}[2021-03-22 04:07:01][261] Processed: App\Jobs\PushNotification
[2021-03-22 04:07:01][262] Processing: App\Jobs\PushNotification
<pre>{"multicast_id":4539206321688711164,"success":2,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1616386022124068%e609af1cf9fd7ecd"},{"message_id":"0:1616386022123922%e609af1cf9fd7ecd"}]}[2021-03-22 04:07:01][262] Processed: App\Jobs\PushNotification
[2021-03-22 04:07:02][263] Processing: App\Jobs\PushNotification
<pre>{"multicast_id":1591082090876608595,"success":3,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1616386023195991%e609af1cf9fd7ecd"},{"message_id":"0:1616386023196003%e609af1cf9fd7ecd"},{"message_id":"0:1616386023195724%e609af1cf9fd7ecd"}]}[2021-03-22 04:07:02][263] Processed: App\Jobs\PushNotification
And Receive 6 Notification .but I send Only Three Notification. Where is my Fault ?
Help Thank You
I am not so sure about that there is nothing wrong with your func but you can try this it's the same but little different if not work so that mean you have a loop somewhere in your code ..
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => $target,
// fix new json format
'notification' => array(
'body' => 'this is firebase test mesging',
'title' => 'hello from firebase',
'badge' => 1,
'sound' => 'default',
'priority' => 'high',
)
);
$fields = json_encode($fields);
$server_key = 'ur_server_kay';
// inherited key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$server_key
);
$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, $fields);
$result = curl_exec($ch);
var_dump($result);
if ($result === FALSE) {
die('Oops! FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);

FCM from PHP always InvalidRegistration

i have problem send Push Notification from PHP, i alway getting error "InvalidRegistration", where device id and server key is correct.
But if i test send message from console firebase is success and i can see notif on my device.
this my code:
function sendNotification($dataArr)
{
define('API_ACCESS_KEY', 'AAAAL25_W68:APA91b............Bwp');
$url = 'https://fcm.googleapis.com/fcm/send';
$registrationIds = $dataArr['device_id'];
$message = $dataArr['message'];
$title = $dataArr['message'];
// prepare the bundle
$msg = array('message' => $message, 'title' => $title);
$fields = array('registration_ids' => $registrationIds, 'data' => $msg);
$headers = array(
'Authorization: key=' . API_ACCESS_KEY,
'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_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);
return $result;
}
and this error :
"fcm":"{\"multicast_id\":7294907474895567505,\"success\":0,\"failure\":1,\"canonical_ids\":0,\"results\":[{\"error\":\"InvalidRegistration\"}]}
So how to fix it, thanks
Try This.
<?php
function send_notification ($tokens, $message = "", $n)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
/*'to' => $tokens,*/
'registration_ids' => $tokens,
'priority' => "high",
'notification' => $n,
'data' => $message
);
//var_dump($fields);
$headers = array(
'Authorization:key = AAAAwLh71-s:APA91bHp4feyq76q7....RdhZrI',
'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);
return $result;
}
$conn = mysqli_connect("localhost","root","","mydb");
$sql = " Select Token From t_user_detail";
$result = mysqli_query($conn,$sql);
$tokens = array();
if(mysqli_num_rows($result) > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
$tokens[] = $row["Token"];
}
}
//mysql_close($conn);
$msg = array
(
'message' => 'here is a message. message',
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$n = array(
"body" => "great match!",
"title" => "NEW NOTIFICATION!",
"text" => "Click me to open an Activity!",
"sound" => "warning"
);
$message_status = send_notification($tokens, $msg, $n);
echo $message_status;
?>

PHP Firebase Clood Messaging (FCM) error missing registration

I am building a push notification from my server to FCM server. I getting following errors: Error=MissingRegistration
My PHP code is given below.
function send($id,$title,$text){
$msg = [
'title' => $title,
'body' => $text,
'icon' => 'myicon',
'sound' => 'mySound'
];
$fields = [
'to' => $id,
'notification' => $msg
];
$headers = [
'Authorization: key=' . $api_key,
'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_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
curl_close ( $ch );
echo $result;
}
I am calling function like this:
send($id,$title,$text);
For sending data to FCM you need to create json data. Please add this line after fields
$fields = json_encode($fields);

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;
?>`

Send GCM Notification from PHP

I am trying to send GCM notification using php. The script runs fine if I hard code the values and I do receive the notification as well. But when I try to pass the value as input, it fails with error:
{
"multicast_id":8013504586085987118,
"success":0,
"failure":1,
"canonical_ids":0,
"results":[
{
"error":"InvalidRegistration"
}
]
}
Working Code:
<?php
// Replace with the real server API key from Google APIs
$apiKey = "Google Api Key";
// Replace with the real client registration IDs
$registrationIDs = array("Registerationid");
// Message to be sent
//$message = "Your message e.g. the title of post";
$msg = array
(
'message' => 'TestMessage',
'title' => 'TestTitle',
'subtitle' => 'TestSubtitle',
'tickerText' => 'TestTicker',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $msg ),
);
$headers = array(
'Authorization: key=' . $apiKey,
'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));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_POST, true);
// 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);
echo $result;
//print_r($result);
//var_dump($result);
?>
code throwing error
<?php
$registrationIDs = array( $_GET['id'] );
// Replace with the real server API key from Google APIs
$apiKey = "API KEY";
// Replace with the real client registration IDs
//$registrationIDs = array( $_GET['id'] );
// Message to be sent
//$message = "Your message e.g. the title of post";
$msg = array
(
'message' => 'TestMessage',
'title' => 'TestTitle',
'subtitle' => 'TestSubtitle',
'tickerText' => 'TestTicker',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $msg ),
);
$headers = array(
'Authorization: key=' . $apiKey,
'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));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_POST, true);
// 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);
// print the result if you really need to print else neglate thi
echo $result;
//print_r($result);
//var_dump($result);
?>

Categories