Send GCM notifications to multiple devices using PHP - php

I need to send GCM notifications to multiple devices. Here i made PHP code to get the array of Registration ID from MySql and tried to send notification to multiple devices but there is some problem here.
My PHP Code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$tags = $_GET['tags'];
$api_key = 'My OWN API KEY';
//Getting registration token we have to make it as array
//Getting the message
$message = Testing GCM';
$title= 'Cuboid';
$vibrate= '1';
$sound= '1';
require_once('dbConnect.php');
$user_ids = array();
foreach ($_REQUEST['tags'] as $key => $val) {
$user_ids[$key] = filter_var($val, FILTER_SANITIZE_STRING);
}
$tagss = "'" . implode("','", $user_ids) . "'";
$sql = "SELECT user_tags.user_id AS userID , gcm_token.regtoken AS regToken
FROM user_tags,gcm_token
WHERE tags IN ({$tagss}) AND user_tags.user_id=gcm_token.user_id";
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
$reg_token = array();
//looping through all the records fetched
while ($row = mysqli_fetch_array($r)) {
$result['regToken'][] = $row['regToken'];
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
$reg_token = (json_encode(array('result'=>$result)));
//$reg_token = array('result'=>$result);
$msg = array
(
'message' => $message,
'title' => $title,
'subtitle' => 'Android Push Notification using GCM Demo',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => $vibrate,
'sound' => $sound,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
//Creating a new array fileds and adding the msg array and registration token array here
$fields = array
(
'registration_ids' => $reg_token,
'data' => $msg
);
//Adding the api key in one more array header
$headers = array
(
'Authorization: key=' . $api_key,
'Content-Type: application/json'
);
//Using curl to perform http request
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/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 ) );
//Getting the result
$results = curl_exec($ch );
curl_close( $ch );
//Decoding json from results
$res = json_decode($results);
mysqli_close($con);
}

You must get result in JSON Array. Try the following code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$tags = $_GET['tags'];
// Replace with the real server API key from Google APIs
$apiKey = "YOUR_API_CODE";
$message = "Hello Raja";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
require_once('dbConnect.php');
$user_ids = array();
foreach ($_REQUEST['tags'] as $key => $val) {
$user_ids[$key] = filter_var($val, FILTER_SANITIZE_STRING);
}
$tagss = "'" . implode("','", $user_ids) . "'";
$sql = "SELECT user_tags.user_id AS userID , gcm_token.regtoken AS regToken
FROM user_tags,gcm_token
WHERE tags IN ({$tagss}) AND user_tags.user_id=gcm_token.user_id";
$r = mysqli_query($con,$sql);
$result = array();
//looping through all the records fetched
while ($row = mysqli_fetch_array($r)) {
$result[] = $row['regToken'];
}
//Displaying the array in json format
//echo json_encode(array('result'=>$result));
echo json_encode(($result));
$registrationIDs = ($result);
//echo json_encode(array('result'=>$result));
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
$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);
}
?>

Update:
As per the updated documentation the API endpoint to send push notification is changed from
https://android.googleapis.com/gcm/send
to https://fcm.googleapis.com/fcm/send
The older endpoint is still working but I'll recommend to use the latest one.
This code remains the same for both the endpoints.
Try this,
Declare a function to send notifications:
function sendfcmMessage($registrationIds, $msg)
{
if (!defined('API_ACCESS_KEY')) define('API_ACCESS_KEY', '<PUT_YOUR_KEY_HERE>');
$fields = array('registration_ids' => $registrationIds, 'data' => $msg, 'content-available' => 1, 'priority' => 'high'); //set priority as required
$headers = array('Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/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);
return $result;
}
The use it like this,
$msg = array('message' => $message,
'title' => $title,
'body' => $body,
'subtitle' => $subtitle,
'tickerText' => $ticker_text,
'vibrate' => $vibrate,
'sound' => $sound,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon');
$registrationIds = array();
while ($row = mysqli_fetch_array($r)) {
array_push($registrationIdsIOS, $row['regToken'];);
}
sendfcmMessage($registrationIds, $msg);
You can also debug by printing the result of this function to know if notification was sent or not, it also lets you know why notification was not sent.
echo sendfcmMessage($registrationIds, $msg);

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

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

Firebase how to send Topic Notification

I am using below script to send notification to particular users:
<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'My_API_KEY' );
$registrationIds = array( TOKENS );
// prep the bundle
$msg = array
(
'body' => "abc",
'title' => "Hello from Api",
'vibrate' => 1,
'sound' => 1,
);
$fields = array
(
'registration_ids' => $registrationIds,
'notification' => $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 ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
?>
Script is working fine but how can i send notification to all user who installed my app. I created a topic in my app (alerts), and i can send notification to all users via firebase console. Can anyone guide me to update above script for topic.
I fixed by replacing
$fields = array
(
'registration_ids' => $registrationIds,
'notification' => $msg
);
To
$fields = array
(
'to' => '/topics/alerts',
'notification' => $msg
);
You can send the notifications without curl (which was not available on my server).
I prepared a function which can send a notification to a specified topic:
sendNotification("New post!", "How to send a simple FCM notification in php", ["new_post_id" => "605"], "new_post", "YOUR_SERVER_KEY");
function sendNotification($title = "", $body = "", $customData = [], $topic = "", $serverKey = ""){
if($serverKey != ""){
ini_set("allow_url_fopen", "On");
$data =
[
"to" => '/topics/'.$topic,
"notification" => [
"body" => $body,
"title" => $title,
],
"data" => $customData
];
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n" .
"Authorization:key=".$serverKey
)
);
$context = stream_context_create( $options );
$result = file_get_contents( "https://fcm.googleapis.com/fcm/send", false, $context );
return json_decode( $result );
}
return false;
}
i am work with google firebase many time and i suggest my simple code for send notification on topic.
public function test()
{
// Method - 1
// $fcmUrl = 'https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1';
// $notification = [
// "message" => [
// "topic" => "foo-bar",
// "notification" => [
// "body" : "This is a Firebase Cloud Messaging Topic Message!",
// "title" : "FCM Message",
// ]
// ]
// ];
// Method - 2
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$notification = [
"to" => '/topics/cbtf',
"data" => [
"message" : "Messaging Topic Message!",
]
]
];
$headers = [
'Authorization: key=AIza...............klQ5SSgJc',
'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($notification));
$result = curl_exec($ch);
curl_close($ch);
return true;
}
You can send notification to any of a topic in firebase. And you can do it from any language it's just a http request but Always you have to maintain the JSON format so that you can catch notification from your android part from
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Timber.d("Data Payload: " + remoteMessage.getData());
}
So You need to send below JSON format
{
"to": "\/topics\/general",
"data": {
"data": {
"title": "Database Notification",
"message": "New Data Added"
}
}
}
So that you can get this data set from remoteMessage.getData()
With particular Topic
<?php
print "testing";
function sendPushnotification($data = array()) {
$apiKey = '';
$fields = array('to' => '/topics/EWAP' , 'notification' => $data);
$headers = array('Authorization: key=' .$apiKey, 'Content-Type: application/json', 'priority' => 10);
$url = 'https://fcm.googleapis.com/fcm/send';
// var_dump($fields);
$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);
curl_close($ch);
return json_encode($result, true);
}
$data = array(
'title' => 'Today topic',
'body' => 'done buddy'
);
var_dump(sendPushnotification($data));
?>
With device token.
<?php
print "testing";
function sendPushnotification($to = '',$data = array()) {
$apiKey = '';
$fields = array('to' => $to , 'notification' => $data);
$headers = array('Authorization: key=' .$apiKey, 'Content-Type: application/json');
$url = 'https://fcm.googleapis.com/fcm/send';
// var_dump($fields);
$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);
curl_close($ch);
return json_encode($result, true);
}
$to = "add device here token ";
$data = array(
'title' => 'Today topic',
'body' => 'done buddy'
);
var_dump(sendPushnotification($to, $data));
?>

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

error in Android: GCM using PHP

I used following code in PHP to send GCM message to Android:
<?php
$apiKey = "xxxxx"; //my api key
$registrationIDs = array("APA91bGGN7o7AwVNnv35lwP5Jw8OTJQL331XcxPfEIu4xt-ZKLe6R0aSSbAve99uKSDXhzE9L2PVLihpqFt0DEawhymUs9h5ICbTMweMAEJypg6ZLFqmf6SOGlyULQzudw9MM1DjbPaaKbo--wxWoHGkjyec2H_63e7mesYjaRf4_rgxBe655M0");
// Message to be sent
$message = "Message Text";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
$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 ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
It's working fine. Here I added my device tokens manually(hardcoded).
But when i tried getting device tokens from the database, I am getting below mentioned error.
Code:
<?php
include 'config.php';
if($_REQUEST['msg']!='')
{
echo $message = $_REQUEST['msg'];
// Replace with real BROWSER API key from Google APIs
$apiKey ="xxxxxx"; //my api key
// Replace with real client registration IDs
$sql = mysql_query("SELECT `device_token` FROM `users`");
$result = mysql_fetch_array($sql);
$registrationIDs = $result;
// Message to be sent
$message = $_REQUEST['msg'];
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
$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 ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
}
I also tried using json_encode($registration_ids) with no use.
"registration_ids" field is not a JSON array
I finally got a solution. I used a for loop to get all the results into an array and converted array into JSON array using json_encode();
I was getting the same error because my array indexes are not properly sorted I fix it by using PHP's sort() function.
Before Sort
$registration_ids = Array
(
[1] => "xxx"
[6] => "xxx"
[8] => "xxx"
)
Sort
sort($registration_ids);
After Sort
$registration_ids = Array
(
[0] => "xxx"
[1] => "xxx"
[2] => "xxx"
)
Pass to PHP's cURL
$fields = array(
'registration_ids' => $ids,
'data' => array('message' => $data)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

Categories