I am using ngcordova push plugin for android with ionic framework.
My device is getting registered in GCM. I get the registration id as well. I am able to store the regid in users table. Everything works fine till now. But when I send the notification from my php server I cannot receive the notification in my mobile phone. The response of the gcm to php code I get is:
{"multicast_id":5214502018855543648,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1439022666580761%156ac804f9fd7ecd"}]}
My JavaScript code is.
.run(function($ionicPlatform,ngFB,$state,$cordovaPush,$rootScope) {
$ionicPlatform.ready(function() {
// ------------------------------ GCM NG-CORDOVA PUSH-----------------------------------
var androidConfig = {
"senderID": "XXXXXXXXXX"
};
$cordovaPush.register(androidConfig).then(function(result) {
// Success
alert(result);
}, function(err) {
// Error
alert(err);
});
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
switch(notification.event) {
case 'registered':
if (notification.regid.length > 0 ) {
alert('registration ID = ' + notification.regid);
$rootScope.reg_id = notification.regid;
}
break;
case 'message':
// this is the actual push notification. its format depends on the data model from the push server
alert('message = ' + notification.message + ' msgCount = ' + notification.msgcnt);
break;
case 'error':
alert('GCM error = ' + notification.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
});
// WARNING: dangerous to unregister (results in loss of tokenID)
// $cordovaPush.unregister(options).then(function(result) {
// Success!
//}, function(err) {
// Error
//})
});
})
My php code is:
<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );
$registrationIds = array( $_GET['id'] );
// prep the bundle
$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,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$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, '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 );
echo $result;
I don't understand where I am wrong. Please help me.
Thanks
I had the same problem one time back, I recommend making your first application with the link below and let second regid make sure the device is correct, that keep well and that the keys of the application are correct. Try the same browser send notifications, sometimes vary in time.
add android app
Make sure you wrap your $cordovaPush.register() and $rootScope.$on() functions inside document.addEventListener("deviceready", function() {}
like this
document.addEventListener("deviceready", function() {
console.log("insode ");
$cordovaPush.register(androidConfig).then(function(result) {
console.log(result);
// Success
}, function(err) {
console.log(err);
// Error
})
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
console.log(event);
console.log(notification);
switch (notification.event) {
case 'registered':
if (notification.regid.length > 0) {
//alert('registration ID = ' + notification.regid);
}
$http({
url: "http://192.168.1.101/saveregid.php",
method : "POST",
data : {
id : notification.regid
}
}).success(function(){
alert("Id is saved");
});
break;
case 'message':
// this is the actual push notification. its format depends on the data model from the push server
$scope.notification = notification;
//alert('message = ' + notification + ' msgCount = ' + notification.msgcnt);
break;
case 'error':
alert('GCM error = ' + notification.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
});
}, false);
To get a correct reg id I have made a simple script at http://192.168.1.101/saveregid.php which gets registration id in its post request and stores it on server file which I can access. Get exact reg id from server file and then try sending a notification.
Related
I make app with cordova and Google FMC notification plugin and everything work great until app is in foreground.
//MY index.php
<div id="load"></div>
<script>
FCMPlugin.onNotification(function(data){
alert( JSON.stringify(data) );
// I DONT UNDERSTAND THIS SECTION ???
// WHAT I SCHOULT DO HERE???
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
alert( JSON.stringify(data) );
// I RECIVED THE DATA ON "CLOSED" APP! GET VARS AND LOAD FILE INTO div id="load" WITH AJAX BASED ON KEY SENDTH FROM FIREBASE CONSOLE
// EXAMPLE KEY = MESSAGE = 10890
// $AJAX LOAD FILE MESSAGE ?ID=10890
// CLEAR NOTIFICATIONS
//example ajax
var message= 10890; // GET FROM CORDOVA NOTIFICATION
var dataString = '& message=' + message;
$.ajax({
type: "POST",
url: "https://mywebsite.com/LOAD.php",
data: dataString,
success: function(response) {
$('#info').html(response);
}
});
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
alert( JSON.stringify(data) );
// I RECIVED THE DATA ON OPEN APP! GET VARS AND LOAD FILE INTO div id="load" WITH AJAX BASED ON KEY SENDTH FROM FIREBASE CONSOLE
// EXAMPLE KEY = MESSAGE = 10890
// $AJAX LOAD FILE MESSAGE ?ID=10890
// CLEAR NOTIFICATIONS
// HOW TO GET VAR FROM alert( JSON.stringify(data) ); ??
//example ajax
var message= 10890; // GET FROM CORDOVA NOTIFICATION
var dataString = '& message=' + message;
$.ajax({
type: "POST",
url: "https://mywebsite.com/LOAD.php",
data: dataString,
success: function(response) {
$('#info').html(response);
}
});
}
});
</script>
Thnaks if sombody can help to solve this enigma. I hope its can help other people not expert like me.
I Use app as wrapper only and load external .php
App work great with all function that i need this ist only problem that i need to solve.
Thank You ,Sory for errors im newby
The Problem vas in sending notification
<?php
$url = "https://fcm.googleapis.com/fcm/send";
$token = "xxxx";
$serverKey = 'xxx';
$topic = 'mytopic';
$title = "title";
$body = "Message.";
$img = 'https://url.com/images/img.jpg';
$data = array('USR_id' => '1000',
'USR_name' => 'Name',
'MSG_id' => '1004',
'SEN_id' => '1001',
'USR_level' => 'user');
$android = array('senderID' => 'xxxxxxxxxxxx',
'sound' => true,
'vibrate' => true,
'clearNotifications' => true,
'forceShow' => true);
$notification = array('title' =>$title,
'body' => $body,
'image' => $img,
'sound' => 'audio.mp3',
'color' => '#F6C02B',
'click_action' => 'FCM_PLUGIN_ACTIVITY',
'badge' => '1');
$arrayToSend = array('to' => '/topics/' . $topic,
'notification' => $notification,
'data' => $data,
'android' => $android,
'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);
?>
After i send it with php that work Perfect
i am trying Edujugon Push Notification laravel; all configuration be correct.
my push notification code is
$push = new PushNotification('fcm');
$push->setMessage([
'notification' => [
'title'=>'This is the title',
'body'=>'This is the message',
'sound' => 'default'
],
'data' => [
'extraPayLoad1' => 'value1',
'extraPayLoad2' => 'value2'
]
])
->setApiKey('AAAAv7w78uY:APA91bF73GY1AcZvBh84K2matRxFwWB0VQysqlDzsLBtrmVRbRN0e6T2Lxasiv-sNfWaNQwqgltTaiaL0rZVC5TKzwfZRgrxb30B4jkl2bzJ9DViZsbGVdQMNOJ78FtOfwcUCgvUj_XC7jLdargjnfKQAD0ecbWMlA')
->setDevicesToken('fj6Sx3zYjhM:APA91bE3cas4LPX-T9jJ-7YgKrMIYOiD5Brjf9AgqvCUsSN7OygZEX3qhQ1F4RxCZfsvSCHNV9gq15NL26k62KBuWqpX4G9nrSQHT3ddabCTRwinqbmpt53gtdCgakaW5LvSxA1t1-iiZS8at8pW7W9o5Gyv2mBSEw');
$push = $push->send();
Please refer https://packagist.org/packages/edujugon/push-notification
$push->setMessage([
'notification' => [
'title'=>'This is the title',
'body'=>'This is the message',
'sound' => 'default'
],
'data' => [
'extraPayLoad1' => 'value1',
'extraPayLoad2' => 'value2'
]
])
->setApiKey('Server-API-Key')
->setDevicesToken(['deviceToken1','deviceToken2','deviceToken3'...]);
used this package LARAVEL-FCM EASY TO USED
I have also integrated push notification in laravel using below code, hope it helps you :
function sendPushNotification($fcm_token, $title, $message, $id="") {
$push_notification_key = Config::get('settings.PUSH_NOTIFICATION_KEY');
$url = "https://fcm.googleapis.com/fcm/send";
$header = array("authorization: key=" . $push_notification_key . "",
"content-type: application/json"
);
$postdata = '{
"to" : "' . $fcm_token . '",
"notification" : {
"title":"' . $title . '",
"text" : "' . $message . '"
},
"data" : {
"id" : "'.$id.'",
"title":"' . $title . '",
"description" : "' . $message . '",
"text" : "' . $message . '",
"is_read": 0
}
}';
$ch = curl_init();
$timeout = 120;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// Get URL content
$result = curl_exec($ch);
// close handle to release resources
curl_close($ch);
return $result;
}
I implemented Firebase Cloud Messaging in my application and while using the Firebase console my application in Android and iOS receives my notifications. But because I wanted to push notification daily I created a cron job to do that in my server side. I notice that every time i trigger my cron my application crashes
In my iOS client it doesn't receive any notification.
In my android client it displays an error:
java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getBody()' on a null object reference
Where it is in my FirebaseMessagingService here is my code
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
And in my server-side
function sendNotificationFCM($apiKey, $registrationIDs, $messageText,$id) {
$headers = array(
'Content-Type:application/json',
'Authorization:key=' . $apiKey
);
$message = array(
'registration_ids' => $registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($message)
));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
I'm wondering why am I having a NPE and how can I solve it?
Try to add a notification object on your $message. The body of your POST request must be something like:
{
"to" : "aUniqueKey",
"notification" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark"
},
"data" : {
"Nick" : "Mario",
"Room" : "PortugalVSDenmark"
}
}
Your remoteMessage.getNotification() returnsnull because the body of your POST request doesn't contain a notification object.
Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct FCM connection.
Check the Documentation for Advanced Messaging Options for your reference.
if (remoteMessage.getNotification() != null) {
sendNotification(remoteMessage.getNotification().getBody());
}
function sendNotificationFCM($apiKey, $registrationIDs, $messageText,$id) {
$headers = array(
'Content-Type:application/json',
'Authorization:key=' . $apiKey
);
$message = array(
'registration_ids' => $registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
'notification' => array(
"body" => "body of notification",
"title" => "title for notification",
)
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($message)
));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
I faced the same issue and found out the solution through few experiments.
I am using Node backend where my Sample Push (Taken from Google Firebase) looks like:
const message = {
data: {score: '850', time: '2:45'},
tokens: nTokenArray
}
admin.messaging().sendMulticast(message)
.then((response) => {
if (response.failureCount > 0) {
const failedTokens = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
console.log('resperrorresperrorresperrorresperror', resp.error);
failedTokens.push(registrationTokens[idx]);
}
});
console.log('List of tokens that caused failures: ' + failedTokens);
}
})
.catch(fcmError => {
console.log({'FCM Errors': fcmError});
})
At Android Side:
Log.d(TAG, "BodyScore: " + remoteMessage.getData().get("score"));
NullPointerException is due to when you use getNotification().getBody() instead of getData().get("score") when you are using Data Payload instead of Notification Payload at server side:
const message = {
data: {score: '850', time: '2:45'},
tokens: nTokenArray
}
I am really struggling with this. This piece of code wasn't created by me but I have changed it so it sort of works. My goal is for it to be able to send push notifications to all devices that use the app. I am an ios and andriod programmed so I will try my best. I have cleaned up and changed the code that was given to me so that it will now send a notification to just one device.
This is the code
<?php
include 'conn.php';
if ( $_REQUEST['key'] == 'notification' ) {
include 'notifications.php';
$message = $_REQUEST['text'];
$text = mysql_real_escape_string( $_REQUEST['text'] );
$start = $_REQUEST['start'];
$end = $_REQUEST['end'];
$date = date( "Ymd", strtotime( $_REQUEST['date'] ) );
$callus = $_REQUEST['callus'];
$in = "INSERT INTO `notifications` (`date`, `start_time`, `end_time`, `text`, `call_us`) VALUES ('$date', '$start', '$end', '$text', '$callus');";
mysql_query($in);
} else {
$message = mysql_real_escape_string( $_REQUEST['text'] );
$time = date( 'Y-m-d H:i:s' );
$in = "INSERT INTO `alerts` (`text`, `time`) VALUES ('$message', '$time');";
mysql_query( $in );
$sel="SELECT * FROM `users` GROUP by device_token";
$rs = mysql_query( $sel ) or die('');
if ( mysql_num_rows( $rs ) != 0 ) {
while( $row=mysql_fetch_array( $rs ) ) {
$regi = array();
$regi[] = $row['device_token'];
$dev = $row['device_token'];
if( strlen ( $dev ) > 65 ) {
$regis[] = $row['device_token'];
} else {
$ios[] = $dev;
}
}
}
$url = 'https://android.googleapis.com/gcm/send';
$fields = array( 'registration_ids' => $regis, 'data' => array( 'message'=>$message,'count'=>1 ) );
$headers = array(
'Authorization: key=AIzaSyCMysH7TySEgdbvRoCLoZk8uFF1x_A3uxg',
'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 ) );
$result = curl_exec( $ch );
curl_close ( $ch );
//Apple Push notification
// This this a fake device id:
$deviceToken = "5d8b3165fc03645d23c2651badd69f07d028aee801acf1d25a4d230882156755";
// fake password:
$passphrase = '123456789';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'badge' => '1'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
}
include 'index.php';
?>
I add the ios device token to the $deviceToken and the android device token to the $regi and it will send to the phones. The only part I have changed is the Apple push notification part which didn't work. Before I changed it the apple push notification was using the $dev variable and android was using $regi. Now I know that the device tokens are being sent to the server when the app is launched so my guess is that they are not being stored in the variables. Is there any problems you can see and how can I print them out to see if they are empty?
Thanks
I figured this out a while ago and though I would share for anyone else that is struggling.
<?php
include 'conn.php';
if ( $_REQUEST['key'] == 'notification' ) {
$message = $_REQUEST['text'];
$text = mysql_real_escape_string( $_REQUEST['text'] );
$start = $_REQUEST['start'];
$end = $_REQUEST['end'];
$date = date( "Ymd", strtotime( $_REQUEST['date'] ) );
$callus = $_REQUEST['callus'];
$in = "INSERT INTO `notifications` (`date`, `start_time`, `end_time`, `text`, `call_us`) VALUES ('$date', '$start', '$end', '$text', '$callus');";
mysql_query($in);
include 'notifications.php';
}
else {
$message = mysql_real_escape_string( $_REQUEST['text'] );
$time = date( 'Y-m-d H:i:s' );
$in = "INSERT INTO `alerts` (`text`, `time`) VALUES ('$message', '$time');";
mysql_query( $in );
$sel="SELECT * FROM `users` GROUP by device_token";
$rs = mysql_query( $sel ) or die('');
if ( mysql_num_rows( $rs ) != 0 ) {
while( $row=mysql_fetch_array( $rs ) ) {
$regi = array();
$regi[] = $row['device_token'];
$dev = $row['device_token'];
if( strlen ( $dev ) > 65 ) {
$regis[] = $row['device_token'];
}
else if ( strlen ($dev) > 25 ) {
$ios[] = $dev;
}
}
}
$deviceToken=$_REQUEST['device'];
$json=json_decode($deviceToken);
//google Push notification
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'AIzaSyCMysH7TySEgdbvRoCLoZk8uFF1x_A3uxg' );
//build the message
$fields = array
(
'registration_ids' => $regis,
'data' => array( 'message'=> $message,'count'=>1 )
);
$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 );
//Apple Push notification
// Certificate password:
$passphrase = '123456789';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ckStudioeast.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'badge' => '1'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Loop though device tokens
foreach($ios as $dev) {
if($dev!=''){
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $dev) . pack('n', strlen($payload)) . $payload;
//Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
}
}
if (!$result)
echo 'Message not delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
include 'index.php';
}
?>
The problem seemed to be that the app was sending the database a development device token so I updated my didRegisterForRemoteNotificationsWithDeviceToken function in xcode to this:
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
#ifdef DEBUG
// Update the database with our development device token
NSLog(#"IN DEVELOPMENT MODE!!!!!!!");
#else
// Update the database with our production device token
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#"<>"]];
token = [token stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"content---%#", token);
kSetValueForKey(#"device_token", token);
[self updateDeviceToken:token];
#endif
}
Also I found that if a user denies the request to allow push notifications that it send a device token of 0 to my database, which if used stops the notifications from being sent. So where I'm sorting my device tokens in my php file I added more logic to ignore all the tokens that where just 0.
I simply just checked that the length was more than 25 characters before I added it to my $ios array, where as before I wasn't
Old code:
if( strlen ( $dev ) > 65 ) {
$regis[] = $row['device_token'];
} else {
$ios[] = $dev;
}
New code:
if( strlen ( $dev ) > 65 ) {
$regis[] = $row['device_token'];
} else if ( strlen ($dev) > 25 ) {
$ios[] = $dev;
}
One of the main problems I found is if you send a device token to apples production push notification server that isn't a valid production device token, it just doesn't send the notification to any device. This is why I It wasn't working and I have added in the extra logic to my php code and Objective-c code to filter out all the invalid device tokens.
Hope this helps people.
while ($row = mysql_fetch_array($result1)) //fetch datafrom loop
{
$dev = $row["device_token"]; // your devide token
if( strlen ( $dev ) > 65 ) { // for android
$regis[] = $row['device_token'];
}
else
{
$ios[] = $row['device_token']; // for ios
}
}
foreach($regis as $dev1) {
$id=$dev1;
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'to' => $id,
'notification' => array (
"body" => $mess,
"icon" =>"icon",
"sound"=> ""
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "---your 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 );
}
foreach($ios as $dev) {
if($dev!='')
{
$deviceToken=$dev;
$passphrase = '';
// Put your alert message here:
$message = $mess;
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
// Create the payload body
$body['aps'] = array(
'alert' => array(
'body' => $message,
),
'badge' => +1,
'sound' => 'default',
'content-available' => '1',
);
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
}
}
if (!$result)
{
?>
<script>
alert("Push notification is successfully sent");
</script>
<?php
}
else
{
?>
<script>
alert("Mesaage is successfully sent");
</script>
<?php
}
curl_close ( $ch );
fclose($fp);
}
I am using PHP to build a App Engine application, but when I try to connect to the GCM server, it is returning the below error:
Parse error: syntax error, unexpected '$data' (T_VARIABLE), expecting ')' Line 6
I'm using this code...
$gcm_regid = "kjfadlfk;dkf;fpoekfldfk;";
$url = "https://android.googleapis.com/gcm/send";
$data = ['data' => 'this', 'registration_ids' => $gcm_regid];
$data = http_build_query($data);
$context = [
'https' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\n" .
"Authorization: key=" . GOOGLE_API_KEY . "\r\n",
'content' => $data
]
];
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);