Flutter Firebase Messaging with PHP - 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");
}
);

Related

cURL PUT/PATCH request with Discord API resulting in error 400 (BAD REQUEST)

I am using php, oAuth2 (from Discord) and cURL to connect to the Discord API, where after the user authorizes the connection, he will automatically enter the server (guild) with a specific nickname and role, but if the user is already on the server, just changes the nickname and adds the role automatically.
I've had success with Auth2, so I'm looking at it. He returns everything I wanted, using identy, guilds.join and email scopes. However, in the process of adding the member to the server or editing the member, it returns error 400 (BAD REQUEST). And I really don't have a clue what it is, so what I'm seeing seems to be all right.
The strange thing is that yesterday, it was working only in the anonymous browser tab, but today, it even worked in my normal browser, but for other users, it does not work.
To tell you the truth, I've already got error 400 and 403, it's really very confusing.
My complete code:
class Discord extends CodonModule {
private static $OAUTH2_CLIENT_ID = 'CLIENT_ID';
private static $OAUTH2_CLIENT_SECRET = 'CLIENT_SECRET';
private static $BOT_TOKEN = 'CLIENT_TOKEN';
private static $guildID = 453922275248265175;
private static $roleID = 45129328442467690261;
public static $authorizeURL = 'https://discordapp.com/api/oauth2/authorize';
public static $tokenURL = 'https://discordapp.com/api/oauth2/token';
public static $apiURLBase = 'https://discordapp.com/api/users/#me';
public function login() {
$params = array(
'client_id' => Discord::$OAUTH2_CLIENT_ID,
'redirect_uri' => 'LINK/request',
'response_type' => 'code',
'scope' => 'identify guilds.join email'
);
// Redirect the user to Discord's authorization page
header('Location: https://discordapp.com/api/oauth2/authorize' . '?' . http_build_query($params));
die();
}
public function request() {
if($this->get('code')) {
// Exchange the auth code for a token
$token = $this->apiRequest(Discord::$tokenURL, array(
"grant_type" => "authorization_code",
'client_id' => Discord::$OAUTH2_CLIENT_ID,
'client_secret' => Discord::$OAUTH2_CLIENT_SECRET,
'redirect_uri' => 'LINK/request',
'code' => $this->get('code')
));
$logout_token = $token->access_token;
$_SESSION['access_token'] = $token->access_token;
header('Location: ' . $_SERVER['PHP_SELF']);
}
if($this->session('access_token')) {
$user = $this->apiRequest(Discord::$apiURLBase);
$userID = intval($user->id);
$userTAG = $user->username.'#'.$user->discriminator;
$newName = 'Teste';
$params = '{"access_token": "'.$_SESSION['access_token'].'", "nick": "'.$newName.'", "roles": ['.Discord::$roleID.']}';
$code = $this->membersRequest($userID, 'PUT', $params);
// The pilot is not on the guild
if($code == 201) {
$this->show('discord/discord_success.php');
return true;
} elseif($code == 204) {
// The pilot is already on the server
$params2 = '{"nick": "'.$newName.'", "roles": ['.Discord::$roleID.']}';
$http = $this->membersRequest($userID, 'PATCH', $params2);
if($http == 204) {
$this->show('discord/discord_success.php');
return true;
} else {
$this->show('discord/discord_error.php');
return false;
}
} else {
$this->show('discord/discord_error.php');
return false;
}
} else {
$this->index();
}
}
function apiRequest($url, $post=FALSE, $headers=array()) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
if($post)
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$headers[] = 'Accept: application/json';
if($this->session('access_token'))
$headers[] = 'Authorization: Bearer ' . $this->session('access_token');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return json_decode($response);
}
function membersRequest($userID, $post, $params) {
$membersURL = 'https://discordapp.com/api/guilds/'.Discord::$guildID.'/members/';
$url = $membersURL.$userID;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $post);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bot ' . Discord::$BOT_TOKEN,
'Content-Type: application/json'
));
curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return $http;
}
function get($key, $default=NULL) {
return array_key_exists($key, $_GET) ? $_GET[$key] : $default;
}
function session($key, $default=NULL) {
return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
}
}
Any help would be much appreciated. Thank you so much.

Set FCM channel ID in PHP for notifications

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

Push notification using FCM and php

I am trying to send push notification from my react native app using fcm and php as server.Following is my code in react to receive notification from server.
pushNotification.js
import React, { Component } from "react";
import FCM from "react-native-fcm";
export default class PushNotification extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
// this method generate fcm token.
FCM.requestPermissions();
FCM.getFCMToken().then(token => {
console.log("TOKEN (getFCMToken)", token);
});
// This method get all notification from server side.
FCM.getInitialNotification().then(notif => {
console.log("INITIAL NOTIFICATION", notif)
});
// This method give received notifications to mobile to display.
this.notificationUnsubscribe = FCM.on("notification", notif => {
console.log("a", notif);
if (notif && notif.local_notification) {
return;
}
this.sendRemote(notif);
});
// this method call when FCM token is update(FCM token update any time so will get updated token from this method)
this.refreshUnsubscribe = FCM.on("refreshToken", token => {
console.log("TOKEN (refreshUnsubscribe)", token);
this.props.onChangeToken(token);
});
}
// This method display the notification on mobile screen.
sendRemote(notif) {
console.log('send');
FCM.presentLocalNotification({
title: notif.title,
body: notif.body,
priority: "high",
click_action: notif.click_action,
show_in_foreground: true,
local: true
});
}
componentWillUnmount() {
this.refreshUnsubscribe();
this.notificationUnsubscribe();
}
render() {
return null;
}
}
My php script is as follows.Here i am trying to send notification by taking the device token of each user.
notification.php
<?php
include 'db.php';
$check_json = file_get_contents('php://input');
$obj= json_decode($check_json);
$uid =$obj->{'uuid'};
$fcm =$obj->{'fcm'}
$to =$fcm;
$data = array(
'title'=>"Testmessage",
'message'=>"You have a new request");
function send_message($to,$data){
$server_key=
'*******';
$target= $to;
$headers = array(
'Content-Type:application/json',
'Authorization:key=' .$server_key
);
$ch = curl_init();
$message = array(
'fcm' => $to,
'priority' => 'high',
'data' => $data
);
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);
//echo $response;
return $response;
?>
I am testing this on a real device and an emulator.Trying to send push notification from a real device to an emulator (possible right?) .But not working.Can anybody please help me.I am new to react , so please..
It's possible to send Push notifications from physical device to Emulator but the Emulator should registered with the FCM
public function sendMessageThroughFCM($arr) {
//Google Firebase messaging FCM-API url
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = (array) $arr;
define("GOOGLE_API_KEY","XXXXXXXXXXXXXXXXXXXXX");
$headers = array(
'Authorization: key=' . GOOGLE_API_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;
}
Framing the array to send notification
$arr = array(
'registration_ids' => $androidTokens,
'notification' => array( 'title' => $notificationTitle, 'body' => $notificationBody),
'data' => array( 'title' => $notificationTitle, 'body' => $notificationBody)
);
Push the list of FCM tokens to which device you need to send the notification
array_push($androidTokens,$token['Fcm_registration_token']);
Refresh the FCM token if it's not generated
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Update the refreshedToken to server through an API call.

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.

Send multiple messages with GCM

I've been dealing with this issue since 2 days. What I want to do is, I've to send multiple messages to registered GCM device. Till now I can send single message to device. Below is the code to send message.
send_message.php
<?php
if (isset($_REQUEST["regId"]) && isset($_REQUEST["message"])) {
$regId = $_REQUEST["regId"];
$message = $_REQUEST["message"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $registatoin_ids; echo $message;
echo $result;
}
GCM.php
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
//Sending Push Notification
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'message' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
//print_r($headers); exit();
// 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);
echo $result;
}
}
?>
Here message is being received on receiver side..
// code for this is in GCM.php
$fields = array(
'registration_ids' => $registatoin_ids,
'message' => $message,
);
But I want to send multiple messages in single notification. for that what I did...
send_message.php
<?php
if (isset($_REQUEST["regId"]) && isset($_REQUEST["message"]) && isset($_REQUEST["data"])) {
$regId = $_REQUEST["regId"];
$message = $_REQUEST["message"];
$data = $_REQUEST["data"]; //added third parameter
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$data = array("extra" => $data);
$result = $gcm->send_notification($registatoin_ids, $message, $data);
echo $registatoin_ids; echo $message; echo $data;
echo $result;
}
GCM.php
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message, $data) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'message' => $message,
'data' => $data,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
//print_r($headers); exit();
// 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);
echo $result;
}
}
?>
And in android I wrote the function to receive message like this...
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getStringExtra("price");
String newmessage = intent.getStringExtra("extra");
displayMessage(context, message + newmessage);
generateNotification(context, message + newmessage);
}
But I'm getting null result for "price" and getting result for "extra".
How can I receive multiple message string in single notification?
In send_message.php
Put both messages in the same object. I don't know why you call it price, but try like this:
$message = array('message' => $message,
'extra' => $data
);
In GCM.php
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
In your Android Service
protected void onMessage(Context context, Intent intent) {
//log the message in JSON format
Log.i(TAG, "Received message >> " + intent.getExtras().toString());
//Retrieve message and extra
String message = intent.getExtras().getString("message");
String newmessage = intent.getExtras().getString("extra");
//Now display the message
displayMessage(context, message + newmessage);
generateNotification(context, message + newmessage);
}
All the payload parameters you pass in your JSON should be within the data element.
Your JSON should look like this :
{
"registration_ids":["xxx", "yyy"],
"data": {
"price": "price value",
"extra": "extra value"
}
}
And not like this :
{
"registration_ids":["xxx", "yyy"],
"message": {
"price": "price value"
},
"data": {
"extra": "extra value"
}
}
you can write a JSON response that contain a multiple messages
and the you get the JSON in android , parse it and get your multiple Messages .
send_message.php
<?php
if (isset($_REQUEST["regId"]) && isset($_REQUEST["message"]) && isset($_REQUEST["extra"])) {
$regId = $_REQUEST["regId"];
$message = $_REQUEST["message"];
$extra= $_REQUEST["extra"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("message" => $message, "extra" => $extra);
$result = $gcm->send_notification($registatoin_ids, $message);
}
GCM.php
<?php
class GCM {
function __construct() {
}
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// 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'
);
//print_r($headers); exit();
// 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);
echo 'result';
echo json_encode($fields);
echo $result;
}
}
Android side
/**
* Method called on Receiving a new message
* */
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("extra");
String newmessage = intent.getExtras().getString("message");
displayMessage(context, message + newmessage);
generateNotification(context, message + newmessage);
}

Categories