Set FCM channel ID in PHP for notifications - php

I'm trying to send FCM notification to Android device using PHP. My code is working for devices before Android O.
In Android O, we need to set channel ID in request as well to receive notifications, which I cannot figure out how to do.
I have done the necessary setup in the app and using Firebase Console I can receive a notification, but it fails when I try sending it through the PHP script.
I also looked into the link below but it doesn't work for me.
Android FCM define channel ID and send notification to this channel through PHP
My PHP code:
$notification = new Notification();
$notification->setTitle("startSession");
$notification->setBody($_POST['child_id']);
$notification->setNotificationChannel('my_channel_id');
$requestData = $notification->getNotification();
$firebase_token = $_POST['token'];
$firebase_api = 'my_value';
$fields = array(
'to' => $firebase_token,
'data' => $requestData,
);
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . $firebase_api,
'Content-Type: application/json'
);
$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);
if($result === FALSE){
die('Curl failed: ' . curl_error($ch));
$return_obj = array('responseCode'=>'0' , 'responseMsg'=> 'Error inserting, please try
again.', 'errorCode'=>'1');
}else{
$return_obj = array('responseCode'=>'1' , 'responseMsg'=> 'Successfully inserted.',
'errorCode'=>'0');
}
// Close connection
echo json_encode($return_obj);
curl_close($ch);
My notification class code is:
<?php
class Notification{
private $title;
private $body;
private $answer_value;
private $android_channel_id;
function __construct(){
}
public function setTitle($title){
$this->title = $title;
}
public function setBody($body){
$this->body = $body;
}
public function setAnswer($answer){
$this->answer_value = $answer;
}
public function setNotificationChannel($channel){
$this->android_channel_id = $channel;
}
public function getNotificatin(){
$notification = array();
$notification['title'] = $this->title;
$notification['body'] = $this->body;
$notification['answer'] = $this->answer_value;
$notification['android_channel_id'] = $this->android_channel_id;
return $notification;
}
}
?>
I'm sure the syntax is correct as the notification still works on devices with Android < 26.
Any help will be really appreciated. Thanks!

You can set your channel Id in server side PHP
PHP server side
<?php
function Notify($title,$body,$target,$chid)
{
define( 'API_ACCESS_KEY', 'enter here your API Key' );
$fcmMsg = array(
'title' => $title,
'body' => $body,
'channelId' => $chid,
);
$fcmFields = array(
'to' => $target, //tokens sending for notification
'notification' => $fcmMsg,
);
$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, true );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fcmFields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result . "\n\n";
}
?>
I define function Notify with 4 parameters title,body,target,chid to use it just call the function and define its parameters,
You must add your channelId in your client side (Android part), with
out channelId you can't get notifications in Android 8.0 and later

Related

Push notification not coming if App is closed Php Android

I am working on a push notification in android with PHP ( using fcm), Push notification is working fine but I am not getting any push notification whenever my App is "closed" (I am getting notification only whenever my app is "open")
Here is my code, where I am wrong?
function testingPush(){
define("FCM_URL", "https://fcm.googleapis.com/fcm/send");
define( "FCM_KEY","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$devicetype1 = "ios";
$devicetype2 = "android";
$deviceType = $rows['device_type']; // coming from database
$deviceToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$titleMessage="Push Notification Testing";
$message="Lorem Ipsum";
$msgs = array();
if (strcasecmp($devicetype1, $deviceType) == 0)
{
/* sending push to IOS */
$notification = array('body'=>$message,
'sound'=>"default",
'title'=>$titleMessage,
'badge'=>1);
$data = array('notificationType'=>1,
'displayURL'=>"https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG");
$msgs = array('to'=>$deviceToken,
'content_available'=>true,
'mutable_content'=>true,
'notification'=>$notification,
'priority'=>'high',
'data'=>$data);
}
else{
/* sening push to android */
$notification = array('contentTitle'=>$titleMessage,
'message'=>$message);
$msgs = array('to'=>$deviceToken,
'priority'=>'high',
'data'=>$notification);
}
$this->sendPushNotification_With($msgs);
}
private function sendPushNotification_With($json) {
$headers = array('Authorization: key=' . FCM_KEY,'Content-Type: application/json');
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, FCM_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($json) );
$result = curl_exec($ch );
curl_close( $ch );
}
Well I think the problem is contentTitle in $notification , replace it to title and it should work and also in your ios notification you are using notification as seperate variable, I would rather suggest you to pass the notification paramter in data , as notification don't work in background.If above don't work recheck your key

Flutter Firebase Messaging with PHP

I have successfully sent push notification from Firebase console using FCM registration token. This is my dart file:
class PushNotificationsManager {
PushNotificationsManager._();
factory PushNotificationsManager() => _instance;
static final PushNotificationsManager _instance = PushNotificationsManager._();
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
bool _initialized = false;
Future<void> init() async {
if (!_initialized) {
// For iOS request permission first.
_firebaseMessaging.requestNotificationPermissions();
_firebaseMessaging.configure();
// For testing purposes print the Firebase Messaging token
String token = await _firebaseMessaging.getToken();
print("FirebaseMessaging token: $token");
_initialized = true;
}
}
}
Now I would like to send the push notification using PHP. I found this tutorial. The PHP code is as below:
push.php
<?php
/**
* #author Ravi Tamada
* #link URL Tutorial link
*/
class Push {
// push message title
private $title;
private $message;
private $image;
// push message payload
private $data;
// flag indicating whether to show the push
// notification or not
// this flag will be useful when perform some opertation
// in background when push is recevied
private $is_background;
function __construct() {
}
public function setTitle($title) {
$this->title = $title;
}
public function setMessage($message) {
$this->message = $message;
}
public function setImage($imageUrl) {
$this->image = $imageUrl;
}
public function setPayload($data) {
$this->data = $data;
}
public function setIsBackground($is_background) {
$this->is_background = $is_background;
}
public function getPush() {
$res = array();
$res['data']['title'] = $this->title;
$res['data']['is_background'] = $this->is_background;
$res['data']['message'] = $this->message;
$res['data']['image'] = $this->image;
$res['data']['payload'] = $this->data;
$res['data']['timestamp'] = date('Y-m-d G:i:s');
return $res;
}
}
firebase.php
<?php
/**
* #author Ravi Tamada
* #link URL Tutorial link
*/
class Firebase {
// sending push message to single user by firebase reg id
public function send($to, $message) {
$fields = array(
'to' => $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// Sending message to a topic by topic name
public function sendToTopic($to, $message) {
$fields = array(
'to' => '/topics/' . $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// sending push message to multiple users by firebase registration ids
public function sendMultiple($registration_ids, $message) {
$fields = array(
'to' => $registration_ids,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// function makes curl request to firebase servers
private function sendPushNotification($fields) {
require_once __DIR__ . '/config.php';
// Set POST variables
$url = 'https://fcm.googleapis.com/fcm/send';
$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);
// 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);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
return $result;
}
}
?>
The web console show returned success message, but my device didn't get the notification. What went wrong?
Problem solved by using this PHP code
<?php
$url = "https://fcm.googleapis.com/fcm/send";
$token = "firebase token";
$serverKey = 'Server key';
$title = "Title";
$body = "Body";
$notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification,'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);
?>
try to configure your code as
protected function sendPushNotification($fields = array())
{
define( 'API_ACCESS_KEY', 'AAAA4-.....' );
$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 );
return $result;
}
and use it like:
$msg = array
(
'body' => 'your message',
'title' => "your app name",
'vibrate' => 1,
'sound' => 1,
);
$fields = array
(
'to' => '/topics/your topic name', // or 'to'=> 'phone token'
'notification'=> $msg
);
$this->sendPushNotification($fields);
If this helps,
You need to add the handlers for the notification under _firebaseMessaging.configure();
Have you done this anywhere -
_firebaseMessaging.configure
(
onMessage: (Map<String, dynamic> message) async
{
print("onMessage: $message");
},
onLaunch: (Map<String, dynamic> message) async // Called when app is terminated
{
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async
{
print("onResume: $message");
}
);

How to send FCM notification using PHP?

I tried to send FCM using PHP code/web browser.
But the problem is when I send it using PHP web browser:
FCM notification only appear on virtual devices.
FCM notification does not appear on real phone devices.
And I can only send FCM notifications to real phone devices using Firebase Console.
Can somebody help? The code is below.
<?php
require "init.php";
global $con;
if(isset($_POST['Submit'])){
$message = $_POST['message'];
$title = $_POST['title'];
$path_to_fcm = 'https://fcm.googleapis.com/fcm/send';
$server_key = "AAAA2gV_U_I:APA91bHA28EUGmA3BrDXFInGy-snx8wW6eZ_RUE7EtOyM99pbfrVZU_ME-FU0O9_dUxYpM30OYF8KWYlixod_PfwbgLNoovzdkdJ4F-30vY8X_tBz0CMrajCIAgbNVRfw203YdRGli";
$sql = "SELECT fcm_token FROM fcm_table";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_row($result);
$key = $row[0];
$headers = array('Authorization:key=' .$server_key, 'Content-Type:application/json');
$fields = array('to' => $key, 'notification' => array('title' => $title, 'body'=> $message));
$payload = json_encode($fields);
$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);
$result = curl_exec($curl_session);
curl_close($curl_session);
mysqli_close($con);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>FCM Notification</title>
</head>
<body>
<form action='fcm_notification.php' method="POST">
<table>
<tr>
<td>Title : </td>
<td><input type="text" name="title" required="required" /></td>
</tr>
<tr>
<td>Message : </td>
<td><input type="text" name="message" required="required" /></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Send notification"></td>
</tr>
</table>
</form>
</body>
</html>
Thanks.
By the following way you can send push notification to mobile using google FCM. For me its works as expected. Add the key 'priority' => 'high'
function sendPushNotification($fields = array())
{
$API_ACCESS_KEY = 'YOUR KEY';
$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 );
return $result;
}
$title = 'Whatever';
$message = 'Lorem ipsum';
$fields = array
(
'registration_ids' => ['deviceID'],
'data' => '',
'priority' => 'high',
'notification' => array(
'body' => $message,
'title' => $title,
'sound' => 'default',
'icon' => 'icon'
)
);
sendPushNotification($fields);
you can create function which send push notification for devices .
// firebase access key
define( 'API_ACCESS_KEY', 'AAAAAG78XmM:APA91bFRHpzuEIgiQRmPUm4uRy8bygNGr1h2Oq3ydc5WtKbrfJA8NVAaGIAxbQELfcOWwN2OR4pf5NzSRuuWOYj_P-XXXXXXXX');
// target device 'fcm' id
$device[0]='JI8YHo7GEo:APA9-aGWOU3U3CXXXXXXXXXXX';
$device[1]='JI8YHo7GEo:APA9-aGWOU3U3CXXXXXXXXXXX';
$url = 'https://fcm.googleapis.com/fcm/send';
// "to": "e1w6hEbZn-8:APA91bEUIb2JewYCIiApsMu5JfI5Ak...", // for single device (insted of "registration_ids"=>"$device" )
$data = array("registration_ids" => $device, // for multiple devices
"notification" => array(
"title" => "Party Night",
"body" => "Invitation for pool party!",
"message"=>"Come at evening...",
'icon'=>'https://www.example.com/images/icon.png'
),
"data"=>array(
"name"=>"xyz",
'image'=>'https://www.example.com/images/minion.jpg'
)
);
$data_string = json_encode($data);
$headers = array ( 'Authorization: key=' . API_ACCESS_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, $data_string);
$result = curl_exec($ch);
for more details refer this
to – Type String – (Optional) [Recipient of a message]
The value must be a single registration token, notification key, or topic. Do not set this field when sending to multiple topics
registration_ids – Type String array – (Optional) [Recipients of a message]
Multiple registration tokens, min 1 max 1000.
priority– Type String – (Optional) [ default normal]
Allowed values normal and high.
delay_while_idle – Type boolean – (Optional) [default value false]
true indicates that the message should not be sent until the device becomes active.
time_to_live – Type JSON number – (Optional) [default value 4 week maximum 4 week]
This parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline
data – Type JSON Object
Specifies the custom key-value pairs of the message’s payload.
eg. {“post_id”:”1234″,”post_title”:”A Blog Post Title”}
In Android you can receive it in onMessageReceived() as Map data…
When in the background – Apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
When in the foreground – App receives a message object with both payloads available.
public class FcmMessageService extends FirebaseMessagingService{
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//onMessageReceived will be called when ever you receive new message from server.. (app in background and foreground )
Log.d("FCM", "From: " + remoteMessage.getFrom());
if(remoteMessage.getNotification()!=null){
Log.d("FCM", "Notification Message Body: " + remoteMessage.getNotification().getBody());
}
if(remoteMessage.getData().containsKey("post_id") && remoteMessage.getData().containsKey("post_title")){
Log.d("Post ID",remoteMessage.getData().get("id").toString());
Log.d("Post Title",remoteMessage.getData().get("post_title").toString());
// eg. Server Send Structure data:{"post_id":"12345","post_title":"A Blog Post"}
}
}}

GCM return null message

I am trying to get the message from server as a push notification in android. but I got null message from server when I change language to Thai but English working.
PHP File
class GCMPushMessage {
var $url = 'https://android.googleapis.com/gcm/send';
var $serverApiKey = "";
var $devices = array();
/*
Constructor
#param $apiKeyIn the server API key
*/
function GCMPushMessage($apiKeyIn){
$this->serverApiKey = $apiKeyIn;
}
/*
Set the devices to send to
#param $deviceIds array of device tokens to send to
*/
function setDevices($deviceIds){
if(is_array($deviceIds)){
$this->devices = $deviceIds;
} else {
$this->devices = array($deviceIds);
}
}
/*
Send the message to the device
#param $message The message to send
#param $data Array of data to accompany the message
*/
function send($message, $data = false){
if(!is_array($this->devices) || count($this->devices) == 0){
$this->error("No devices set");
}
if(strlen($this->serverApiKey) < 8){
$this->error("Server API Key not set");
}
$fields = array(
'registration_ids' => $this->devices,
'data' => array( "message" => $message ),
);
if(is_array($data)){
foreach ($data as $key => $value) {
$fields['data'][$key] = $value;
}
}
$headers = array(
'Authorization: key=' . $this->serverApiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $this->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 ) );
// Avoids problem with https certificate
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
return $result;
}
function error($msg){
echo "Android send notification failed with error:";
echo "\t" . $msg;
exit(1);
}
onMessageReceived
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
String title = data.getString("title");
/*Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);*/
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
help me please.

Android phonegap send push notification using Google Cloud Messaging using php

I have developed the android application in cordova 3.4 now I want to get the automatic notification to their mobile. For this I refer websites as below
http://devgirl.org/2013/07/17/tutorial-implement-push-notifications-in-your-phonegap-application/
http://devgirl.org/2012/10/25/tutorial-android-push-notifications-with-phonegap/
https://github.com/hollyschinsky/PushNotificationSample30/tree/master/platforms/android
I read all above links then did all stuff they told like create project on google cloud messaging , get the project id , create server key (In textbox I given my private server IP) then API Key, I also have registration id device and I wrote code in php for sending push notification to my device but it is giving me "unauthorised Error 404"
my code is as below
define( 'API_ACCESS_KEY', 'my api key' );
//$registrationIds = array( $_GET['id'] );
$registrationIds = array($id);
//var_dump($registrationIds);die;
//prep the bundle
$msg = array
(
'message' => 'New Jobs is updated',
'title' => 'get the job in cad',
'subtitle' => 'get the job in cad',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'sound' => 1
);
$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 just hit url and send the registration id of device to the my php page but this page give me the error unauthorised Error 401.
Que.1. Is this possible to send the push notification from php which is hosted on private server?
Que.2 Is device registration id compulsory for sending push notification to those user they installed the apps?
Please anybody help me how to solve this above error and if anybody have another solution then tell me. I tried from yesterday but not achieve my goal so please help me.
Here is the GCM code and its working properly with my device though its in CI framework but hope you can use it. It is compulsory to add device_id for the push and also the passphrase you'll get for the site. just try it.
function sendNotification($device_id,$message) {
/*echo $device_id;
echo "<br>";
echo $message;*/
// note: you have to specify API key in config before
$this->load->library('gcm');
// simple adding message. You can also add message in the data,
// but if you specified it with setMesage() already
// then setMessage's messages will have bigger priority
$msg = $this->gcm->setMessage($message);
//var_dump($message);
// add recepient or few
$this->gcm->addRecepient($device_id);
//var_dump($device_id);
// set additional data
//$this->gcm->setData($params);
// also you can add time to live
$this->gcm->setTtl(500);
// and unset in further
//$this->gcm->setTtl(false);
// set group for messages if needed
//$this->gcm->setGroup('Test');
// or set to default
//$this->gcm->setGroup(false);
// send
return $this->gcm->send();
}
Hope it'll solve your problem.
<?php
$register_keys = array("YOUR_REGISTRY_KEYS")
$google_api_key = "YOUR_API_KEY";
$registatoin_ids = $register_keys;
$message = array("price" => $message);
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' .$google_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);
// 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);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
//print_r($result);
// Close connection
curl_close($ch);
?>

Categories