I have an application that uses FCM for sending push notification for multiple devices.
When I send notification I'm getting error:
{"multicast_id":7972874062893873258,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
I've tried with both sever key and legacy server key, but getting the same error.
Used googleservice.json and uninstall the app after integrating the json.
I have researched a lot and made sure I have added all prerequisites that FCM needs.
Any suggestions?
function sendPushNotificationToFCMSever($token,$title, $desc, $API_SERVER_KEY) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => $token,
'notification' => array (
"body" => $title,
"title" => "Title",
"icon" => "myicon"
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . $API_SERVER_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 );
return $result;
}
Related
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 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 following this tutorial for GCM notification.I am able register the device but unable to send notifications.
I have also used couple of online services to send notification, they are sending message but with "null" message.
Please help me, what can be wrong
Note: I am in my college network which use proxy to connect.
Try to create some_name.php file with the code below and upload it to server and then open it. It should send the notification.
Don't forget to change: "add_your_server_key_here", "register_id_of_your_device".
<?php
define( 'API_ACCESS_KEY', 'add_your_server_key_here' );
$registrationIds = array("register_id_of_your_device" );
$msg = array
(
'message' => 'your_message',
'title' => 'title_of_message',
);
$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 have read few threads here about this issue but doesn't seem to solve it, not sure what I am missing, here is my code that's supposed to send notifications to all devices, but it seems to miss some out, any help is appreciated:
foreach ($devices as $deviceArray) {
$regIds[] = $deviceArray['device_id'];
}
$pusher->notify($regIds, $msg);
the notify function:
public function notify($regIds, $data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::GOOGLE_GCM_URL);
if (!is_null($this->proxy)) {
curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->getPostFields($regIds, $data));
$result = curl_exec($ch);
if ($result === false) {
throw new \Exception(curl_error($ch));
}
curl_close($ch);
$this->output = $result;
}
private function getHeaders()
{
$tempArray[0] = 'Authorization: key=' . $this->apiKey;
$tempArray[1] = 'Content-Type: application/json';
return $tempArray;
}
private function getPostFields($regIds, $data)
{
$fields = array(
'registration_ids' => is_string($regIds) ? array($regIds) : $regIds,
'data' => is_string($data) ? array( 'message' => $data) : $data,
);
return json_encode($fields, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
}
i try to send message from my server to google cloud server, but i have problem with it...
i get server key(Key for server applications), set it to this code:
$headers = array(
'Authorization: key=' .My server 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));
$result = curl_exec($ch);
after sending message i have such result:
Unauthorized
Error 401
I use such ip:78.47.150.20
but when i use test ip 0.0.0.0/0 i haven't any problems....
function sendNotification($registrationIdsArray, $messageData) {
$apiKey = "YOUR_API_KEY";
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
$data = array(
'data' => $messageData,
'registration_ids' => $registrationIdsArray
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );
$response = curl_exec($ch);
curl_close($ch);
return $response;
}