FCM from PHP always InvalidRegistration - php

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

Related

How can I send push notification to all users in an array in php?

I want to do it in such a way when I use {select token FROM riders} it selects all the tokens and send the push notifications to all of them but when i do that it does not send any notification.
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'android_api');
//connecting to database and getting the connection object
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$stmt = mysqli_query($conn,"SELECT token FROM riders");
$query = mysqli_fetch_array($stmt);
$token = $query['token'];
$apiKey = "AAAAKCR7bo4:APA91bHuIwpxHkR5VxODbqje6b518xbBLWUnVfucuUJNJzqzTYDyww- dwkPtgUj.........aDWTNyfARF0ru16"; //Server Key Legacy
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$notification = array('title' =>'iDELIVERY',
'body' => 'A Request Has Been Made');
$notifdata = array('title' =>'test title data',
'body' => 'hello',
'image' => 'path'
);
$fcmNotification = array (
'to' => $token,
'notification' => $notification,
'data' => $notifdata
);
$headers = array( 'Authorization: key='.$apiKey, 'Content-Type: application/json');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
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($fcmNotification));
$result = curl_exec($ch);
// curl_close($ch);
?>
I am sending a working code which I have used in one of my mobile app, You should fetch multiple tokens according to your dataset , Sample code is given below
$stmt = mysqli_query($conn,"SELECT token FROM riders where phone='026'");
//Itrate token and store it in an array based on your dataset
$allTokens = array();
foreach($tokens as $token){
$allTokens[] = $token['token'];
}
// This is a sample KEY
define( 'API_ACCESS_KEY', 'AIdsdyALOdsds7pR01rydsds0dsdqQndsdsOVpPpy4adsds');
// Build your message as an array
$msg = array(
'title' => "Payment Alert",
'message' => "You have received a test payment",
'bigText' => "You have received a test payment",
"subText" => "You have received a test payment",
'summaryText' => 'Alert for payment',
'click_action' => 'FCM_PLUGIN_ACTIVITY',
'vibrate' => 300,
'sound' => 1,
);
$fields = array(
'registration_ids' => $allTokens, // multiple tokens will be available in array
'data' => $msg
);
$headers = array(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
if(!empty($allTokens)){
$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 ) );
$result = curl_exec($ch );
curl_close( $ch );
}
Using PHP
function sendNotifiation(){
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'android_api');
//connecting to database and getting the connection object
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$stmt = mysqli_query($conn,"SELECT token FROM riders");
$query = mysqli_fetch_array($stmt);
$token = $query['token'];
$title = "Your notification title";
$body = "Your notification body";
$message = "Your notification message";
sendAndroidNotification($token, $message,$title,$body);
}
function sendAndroidNotification($device_token, $message = null,$title,$body) {
if (!empty($device_token) && $device_token != 'NULL') {
$device_token = json_decode(json_encode($device_token));
$FIREBASE_API_KEY = 'key';
$url = 'https://fcm.googleapis.com/fcm/send';
$notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1');
$fields = array('registration_ids' => $device_token, 'notification' => $notification,'priority'=>'high','data' => $message);
$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);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
}
}
You can use this method to send a notification to multiple users using this below code. Below code helps you to send Firebase push notification android
<?php
$target = ["TARGET_ID"];
$notificationBody['data'] = [
'type' => 1,
'url' => "https://trinitytuts.com/wp-content/uploads/2018/07/macaw.png",
'title' => "title",
"msg" => "Message"
];
$response = sendMessage($notificationBody, $target, $_POST['serverKey']);
function sendMessage($data, $target, $serverKey){
//FCM api URL
$rsp = [];
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = $serverKey;
$fields = array();
$fields['data'] = $data;
if(is_array($target)){
$fields['registration_ids'] = $target;
}else{
$fields['to'] = $target;
}
//header with content_type api 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, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
//die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
//print_r($result);
return $result;
}

FCM Push for iOS error InvalidRegistration

I am trying to send push notifications through PHP script via Firebase Cloud Messaging to iOS App.
Currently I'm using following test PHP script.
$url = "https://fcm.googleapis.com/fcm/send";
$token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$serverKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$title = "Title";
$body = "Body of the message";
$notification = array('title' =>$title , 'text' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
However, I am receiving following error message when I try to run script via browser.
{"multicast_id":5417898622260949101,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
But when I use the same device token from FCM console, it is working without any issues.
I have tried many PHP scripts on the internet, but end up with the same results, what would be the issue here ?
Any help would be highly appreciate.
The token you are using does not seem to be a valid registration token for FCM, hence the InvalidRegistration error.
$apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$title = 'Title';
$message = 'hello message';
$notification =[
"text" => "Test",
'badge' => "1",
'sound' => 'shutter.mp3',
"android_channel_id"=>"test01",
'body'=>$message,
'icon'=>'notif_icn',
'title'=>$title,
'priority'=>'high',
'vibrate'=> 1,
'alert'=> $message
];
$msg = [
'message'=> $message,
'title'=> $title
];
$fields =[
"content_available" => true,
"priority" => "high",
'registration_ids'=> $deviceToken,
'data'=> $msg
];
$headers = array('Authorization: key=' . $apiKey,'Content-Type: application/json');
if ($headers){
$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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$response = curl_exec($ch);
if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
}

FCM message not delivered to device when sent from 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']);
}

Sending Firebase notification with PHP

everyone! I am having a problem using PHP to send FIrebase notification. When I send it from Firebase console, I get the notification, but when I send it from PHP, I don't receive any notification.
DO you have any idea what is the problem?
Here is my PHP code:
<?php
$message = 'ojlaasdasdasd';
$title = 'ojla';
$path_to_fcm = 'https://fcm.googleapis.com/fcm/send'; $server_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5LnDZO2BpC2aoPMshfKwRbJAJfZL8C33qRxxxxxxxxxxxxL6';
$key = 'eqnlxIQ1SWA:APA91bGf1COAZamVzT4onl66_lEdE1nWfY7rIADcnt9gtNYnw7iWTwa7AYPYTHESFholkZ89ydCQS3QeL-lCIuiWTXiqoDREO0xhNdEYboPvqg8QsBYkrQVRlrCLewC4N-hHUja1NG4f';
$headers = array(
'Authorization:key=' .$server_key,
'Content-Type: application/json');
$fields = array
(
'to' => $key,
'notification' => array('title' => $title,'body' => $message)
);
$payload = json_encode($fields);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, '$path_to_fcm' );
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_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt( $ch,CURLOPT_POSTFIELDS, $payload);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
?>
I don't get any echo from the server
try this code.Its working fine for me.just change key and token
<?php
define('API_ACCESS_KEY','Api key from Fcm add here');
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$token='235zgagasd634sdgds46436';
$notification = [
'title' =>'title',
'body' => 'body of message.',
'icon' =>'myIcon',
'sound' => 'mySound'
];
$extraNotificationData = ["message" => $notification,"moredata" =>'dd'];
$fcmNotification = [
//'registration_ids' => $tokenList, //multple token array
'to' => $token, //single token
'notification' => $notification,
'data' => $extraNotificationData
];
$headers = [
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$fcmUrl);
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($fcmNotification));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
I use the following function to send a HTTP Request to Firebase:
function request($url, $body, $method = "POST", $header = "Content-type: application/x-www-form-urlencoded\r\n")
{
switch ($method) {
case 'POST':
case 'GET':
case 'PUT':
case 'DELETE':
break;
default:
$method = 'POST';
break;
}
$options = array(
'http' => array(
'header' => "$header",
'method' => "$method",
'content' => $body
)
);
$context = stream_context_create($options);
$data = file_get_contents($url, false, $context);
$data = json_decode($data, true);
return $data;
}
To execute the function I use the following code:
$fcm_key = "";
$body = array("data" => $data, "to" => "$fcm_token");
$body = json_encode($body);
$json = request("https://fcm.googleapis.com/fcm/send", $body, "POST", "Authorization: key=$fcm_key\r\nContent-Type:application/json");
For me, this code works without any problems. Be sure that you use the right FCM device token ($fcm_token) and set the right FCM key ($fcm_key).
$tokenID = $valueTwo["TokenID"];
$cmMessage = array();
$cmMessage["type"] = 3;
$cmMessage["receiverMail"] = $receiverMail;
$cmMessage["ownerMail"] = $ownerMail;
$cmMessage["jsonData"] = $jsonData;
$url = "https://fcm.googleapis.com/fcm/send";
$title = "";
$body = "";
//$notification = array('title' => $title, 'body' => null, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $tokenID, 'priority' => 'high', 'data' => $cmMessage);
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key=' . $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
Get your server key and token id to send write them... Dont use notification tag...Like I did in code... Cuz if you write notification tag, Application in background is not got receive msg Cuz notification tag executes on foreground and in background automatic notification is displayed..
Send firebase push notification via php to android, ios
function sendPushNotification($to = '', $data = array()){
$api_key = '';
$fields = array('to' => $to, 'notification' => $data);
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$api_key
);
$url = 'https://fcm.googleapis.com/fcm/send';
$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));
$result = curl_exec($ch);
if ($result === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$to = ''; //Device token
// You can get it from FirebaseInstanceId.getInstance().getToken();
$message = array(
'title' => 'Hai',
'body' => 'New Message');
echo sendPushNotification($to, $message);

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

Categories