send the PUSH notification to multiple users Through FCM - php

I want to send the PUSH notification to the Multiple USERS through PHP script. When I run my script it shows the result successful, but on my device I am not getting any Notification.
But when I use the FCM console, I got the Notifications on my Device.
PHP script:
<?php
function send_notification ($tokens, $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message,
'click_action' => ACTIVITY_CIRCULAR
);
$headers = array(
'Authorization:key = my 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);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$conn = mysqli_connect("connection set-up");
$sql = "Select FirebaseID From Coordinates";
$result = mysqli_query($conn,$sql);
$tokens = array();
//var_dump(result);
if(mysqli_num_rows($result) > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
$tokens[] = $row["FirebaseID"];
}
}
var_dump($tokens);
mysqli_close($conn);
$message = array("message" => "Hello World");
$message_status = send_notification($tokens, $message);
echo $message_status;
?>
My result:
{"multicast_id":6386552330832519***,"success":2,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1477******764957%e8a8d907f9fd7ecd"},{"message_id":"0:1477293027764959%e8a8d907f9f***cd"}]}
EDIT : Is there any way to check where the message is failing because it shows the Successful in Result...but it doesn't reach to device

If you user is more than 1k then you have to chunk you array because FCM registaion_ids not allowed more than 1k id at a time :
$value = array_chunk($userList,900);
foreach ($value as $val)
{
$db->sendPushCustomNew("test" . " Posted a Gallery", $createdDate, $val, "1", "Gotcha!", 0, 0, 0);
}
Then You have to configure you're notification send function like bellow :
function sendPushCustomNew($message, $currentDate, $tokens, $notificationType, $title, $latitude, $longitude, $memberID)
{
//error_log("IN_PUSH");
$curl = curl_init();
$fields = array(
'data' => array(
'notificationType' => $notificationType,
'title' => $title,
"message" => "" . $message,
"time" => "" . $currentDate,
'latitude' => $latitude,
'longitude' => $longitude
),
'registration_ids' => $tokens
);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://fcm.googleapis.com/fcm/send",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($fields),
CURLOPT_HTTPHEADER => array(
"authorization: ******",
"cache-control: no-cache",
"content-type: application/json",
"postman-token: ***"
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
}

please check that you have saved the device id properly or not ,and also check that you have used the same server key as per project android key ,check your google account

use this php code its works in your case
<?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://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;

inside your project you are adding registration id that you get when you create a google api console account from there you ll get server key and android key https://console.developers.google.com/apis/library?project=tabzen-1341,see the screenshot and read the google guidl

Related

Send GCM notifications to multiple devices using 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);

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

How to Send push notifications using One Signal + PHP + Server API?

I am using one signal to send push notification for android app. My question is
How Can I setup send push notifications using server rest api?
<?PHP
function sendMessage(){
$content = array(
"en" => 'Testing Message'
);
$fields = array(
'app_id' => "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx",
'included_segments' => array('All'),
'data' => array("foo" => "bar"),
'large_icon' =>"ic_launcher_round.png",
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
You can always refer to the official docs:
https://documentation.onesignal.com/reference#section-example-code-create-notification
'app_id' is currently known as (OneSignal App ID) in the OneSignal
Settings->Keys and IDs
in 'Authorization: Basic xxx...' past the "REST API Key" just below the App ID
I see you have set isAndroid=true, but OneSignal is returning an error that shows that the application with ID eec33e8e-5774-4b74-9aae-37370778c4b2 does not have Android notifications enabled.
Make sure your app ID is correct, and if it is, that Android notifications are enabled in your OneSignal settings.
$to - Device ID
$title - Notification Title
$message - Notification Message
$img - Full image link
Usage:
sendnotification($to, $title, $message, $img);
With Demo Values :
sendnotification("Device_ID","Test Notification","Test Message","https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png");
function sendnotification($to, $title, $message, $img)
{
$msg = $message;
$content = array(
"en" => $msg
);
$headings = array(
"en" => $title
);
if ($img == '') {
$fields = array(
'app_id' => 'YOUR_APP_ID',
"headings" => $headings,
'include_player_ids' => array($to),
'large_icon' => "https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png",
'content_available' => true,
'contents' => $content
);
} else {
$ios_img = array(
"id1" => $img
);
$fields = array(
'app_id' => 'YOUR_APP_ID',
"headings" => $headings,
'include_player_ids' => array($to),
'contents' => $content,
"big_picture" => $img,
'large_icon' => "https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png",
'content_available' => true,
"ios_attachments" => $ios_img
);
}
$headers = array(
'Authorization: key=**APP_KEY**',
'Content-Type: application/json; charset=utf-8'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://onesignal.com/api/v1/notifications');
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;
}

IOS GCM push notifications not received in background using PHP sender and Swift

I'm working on getting background notifications to work on IOS with GCM - non-background notifications are already working. Here are my steps to integrate background notifications:
Enable the remote-notifications tag in UIBackgroundmodes
Add the content-available key to my notification payload.
Write the application:didRecieveRemoteNotification:fetchCompletionHandler: in my delegate.
Here is the code for the delegate function:
func application( application: UIApplication,
didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
println("Notification received2: \(userInfo)")
GCMService.sharedInstance().appDidReceiveMessage(userInfo);
NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
userInfo: userInfo)
handler(UIBackgroundFetchResult.NoData);
}
This is the code for the on-server php script:
<?php
$regId = $_GET["regId"];
$message = $_GET["message"];
$data = array( 'price' => $message, 'sound' => 'default', 'body' => 'helloworld', 'title' => 'default', 'badge' => 12, 'content-available' => 1);
$ids = array( $regId);
sendGoogleCloudMessage( $data, $ids );
function sendGoogleCloudMessage( $data, $ids )
{
$apiKey = THE-API-KEY-THAT-I-AM-USING;
$url = 'https://android.googleapis.com/gcm/send';
$post = array(
'registration_ids' => $ids,
'data' => $data,
'content-available' => 1,
);
$headers = array(
'Authorization: key=' . $apiKey,
'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, json_encode( $post ) );
$result = curl_exec( $ch );
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
echo $result;
}
?>
I have tried sending the content-available flag through both the inner "data" array and the outer "post" array, which I have indicated by adding it to both.
The message is not received by the fetchCompletionHandler function, but rather waits until the app is active again and is received by the normal application:didRecieveRemoteNotification function. What could be the reason that my notification is not received via the background functionality?
You should provide content_available to GCM, not content-available (like in APNs) and you will be able to receive push notifications in background.
https://developers.google.com/cloud-messaging/server-ref#send-downstream
P.S. - Less then five minutes ago I had absolutely same problem. We should read docs more carefully...

PHP GCM appengine

I am trying to use gcm in appengine using PHP runtime. Following is the code, which uses URLFetch service
$context = array("https"=>
array( "method" => "post",
"content" => json_encode($fields),
"header" => "Content-Type: application/json\r\n" .
"Authorization: key=" . GOOGLE_API_KEY . "\r\n"
)
);
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);
Following is the Original code that uses PHP Curl:
$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);
PHP code that uses Curl works well, but the code that uses urlfetch service of appengine does't work. Can someone tell me where am I doing wrong.
This is tested code.
public function sendAndroidPushNotification($registration_ids, $message)
{
// Adding devicetoken in array
$registrationIds = array($registration_ids);
$msg = array(
'message' => $message,
'title' => 'notification center',
'tickerText' => $message,
'vibrate' => 1,
'sound' => 1,
);
$fields = array(
'registration_ids' => $registrationIds,
'data' => $msg
);
$fields = json_encode($fields);
$arrContextOptions=array(
"http" => array(
"method" => "POST",
"header" =>
'Authorization: key = '. "\r\n" .
'Content-Type: application/json'. "\r\n",
"content" => $fields,
),
"ssl"=>array(
"allow_self_signed"=>true,
"verify_peer"=>false,
),
);
$arrContextOptions = stream_context_create($arrContextOptions);
$result = file_get_contents('https://android.googleapis.com/gcm/send', false, $arrContextOptions);
return $result;
}

Categories