error in Android: GCM using PHP - 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));

Related

Push notification from PHP to an android app with FCM

I am a beginner in PHP and I would like to make a program to send a simple notification (a title and a little message) from a localhost (in PHP) to an android app. For this, I use Firebase. For the moment, I can send a notification from FCM to android but I cannot do it from the PHP program to the android app. I tried a lot of different way and program to send this notification and it's always a failure.
This is the program I use :
<html>
<?php
$read = shell_exec ('gpio read 0');
$status = intval($read);
if ($status == 1) {
function sendFCM($mess,$id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'AAAAS4YkIPw:A.........rLQjQ' => $id,
'notification' => array (
"body" => $mess,
"Doorbell" => "Title",
// "icon" => "myicon"
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "AIzaSy.....J_Hy0",
'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 );
}
print ("oui");
sleep(30);
header("Refresh:0");
}
else {
print ("non");
sleep(2);
header("Refresh:0");
}
?>
</html>
In each program I used, maybe I made the same mistake every time but I don't manage to find it. Just to explain, this program read a GPIO and as function of the result, he tell "oui" or "non" and send a notification wend it's "oui". The program I took on a website is between the line 6 and the line 30. All the rest work. My problem is must I don't receive notifications.
I change my program after I saw one error so this is the new one.
<html>
<head>
</head>
<?php
function sendFCM($mess,$id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'AAAAS4Yk.........KirLQjQ' => $id,
'notification' => array (
"body" => $mess,
"Doorbell" => "Title",
// "icon" => "myicon"
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=>' . "$ip",
'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 );
}
$read = shell_exec ('gpio read 0');
$status = intval($read);
if ($status == 1) {
sendFCM('Yolo','AIzaSy......xdJ_Hy0');
print ("oui");
sleep(30);
header("Refresh:0");
}
else {
print ("non");
sleep(2);
header("Refresh:0");
}
?>
</html>

Firebase PHP don't work for IOS

I have a small problem
I use FireBase for push notification on iOS and Android.
On Android it work, on iOS it work only when i send message by the console when i send message with PHP it's not good
My php code
function sendGCM($message, $id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => array (
$id
),
'data' => array (
"message" => $message
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "*****",
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
curl_close ( $ch );
}
Do you know why ?
Thanks :)

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

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

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...

Categories