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.
Related
I'm send push notifications using php, what I've realise is the push notification comes to the phone, but fails to send the additional data I add to the script for example page etc.
<?php
$url = "https://fcm.googleapis.com/fcm/send";
$token = 'device_id here';
$serverKey = 'AIzaSxxxbAGLyxxxx';
$title = "New Message";
$body = 'Hello there';
$notification = array('title' =>$title , 'message' => $body,'priority'=>'high','badge'=>'1','notId'=>''.time(), 'id' => '33','page' => 'news');
$arrayToSend = array('to' => $token, 'notification' => $notification);
$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);
?>
You are attempting to add custom data fields to a Notification message. Notification messages only allow certain fields. If you want to send custom data then you need to make your message a Data message or a Notification message with data payload.
From the FCM docs a combination Notification message with data payload for android could look like this:
{
"to":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"New Message",
"body":"Hello there"
},
"data" : {
"notId" : 201801,
"id" : 33,
"page" : "news",
}
}
Make these changes to the message structure:
$notification = array('title' =>$title , 'message' => $body);
$data = array('notId'=>''.time(), 'id' => '33','page' => 'news');
$arrayToSend = array('to' => $token, 'notification' => $notification, 'data' => $data);
You will need to change your android code to accommodate the data field and parse the data accordingly.
Please read the FCM documentation carefully is see which ramifications this change can have on your project. Most importantly, how data messages are handled when you app is in the background!
I am using FCM to send push notification to IOS app, IOS dev provide me device token and SERVER_KEY, I search on google and tried different solutions but nothing worked for me , So let me know what is wrong with my code, Getting error {
"multicast_id": 8569689262516537799,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "InvalidRegistration"
}
]
}
Thanks in advance
$ch = curl_init("https://fcm.googleapis.com/fcm/send");
//The device token.
$token = "c2420d68a0838d8fb6b26ef06278e899de73a149e93c9fe13df11f70f3dd5cc1"; //token here
//Title of the Notification.
$title = "Carbon";
//Body of the Notification.
$body = "Bear island knows no king but the king in the north, whose name is stark.";
//Creating the notification array.
$notification = array('title' => $title, 'text' => $body);
//This array contains, the token and the notification. The 'to' attribute stores the token.
$arrayToSend = array('to' => $token, 'notification' => $notification, 'priority' => 'high');
//Generating JSON encoded string form the above array.
$json = json_encode($arrayToSend);
//print_r($json); die();
//Setup headers:
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key=AAAAx6P1Nz0:APA91bEqkVCA9YRw9gpUvmF8UOVrYJ5T8672wfS_I7UAT3dA0g1QS7z-Z4fpn8JMiJ5kFRz9ZGc2K64hKZG-4__PAUqm733hqNDuFCDv9'; // key here
//Setup curl, add headers and post parameters.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//Send the request
$response = curl_exec($ch);
//Close request
print_r($response);
curl_close($ch);
//return $response;
token number ur sending is most probably wrong. try "/topics/all" this will send notification to all the users registered.
The notification work just fine when sent from the firebase console, but don't work when sent from the API. Even when the result displays a success:
{"multicast_id":5946406103096345260,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1480093752122166%13791f60f9fd7ecd"}]}
Anyway heres the code:
<?php
// Payload data you want to send to Android device(s)
// (it will be accessible via intent extras)
$data = array('title' => 'Notification Title' ,'message' => 'Hello World!');
// The recipient registration tokens for this notification
$ids = array('TOKEN');
// Send push notification via Google Cloud Messaging
sendPushNotification($data, $ids);
function sendPushNotification($data, $ids)
{
// Insert real GCM API key from the Google APIs Console
$apiKey = 'API_KEY';
// Set POST request body
$post = array(
'registration_ids' => $ids,
'data' => $data,
);
// Set CURL request headers
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Initialize curl handle
$ch = curl_init();
// Set URL to GCM push endpoint
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
// Set request method to POST
curl_setopt($ch, CURLOPT_POST, true);
// Set custom request headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Get the response back as string instead of printing it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set JSON post data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
// Actually send the request
$result = curl_exec($ch);
// Handle errors
if (curl_errno($ch))
{
echo 'GCM error: ' . curl_error($ch);
}
// Close curl handle
curl_close($ch);
// Debug GCM response
echo $result;
}
?>
FCM only sends push notifications when using the notification payload, e.g.:
{
"to: "registration token",
"priority": "high",
"notification": {
"title": "Title",
"text": "Text"
},
...
}
}
See also Firebase Docs
For those unfamiliar with php (as me) #Simon Heinzle answer might be a bit cryptic. It just means that in the original code these changes should be made:
$data = array('title' => 'Notification Title' ,'text' => 'Hello World!');
...
$post = array(
'registration_ids' => $ids,
'priority' => 'high',
'notification' => $data,
);
Note that you could change registration_ids (which is an array of tokens) by to (a single token) if you just need to send the notification to a single device.
More options for the notifications can be found in the FCM docs.
To send push-notification from server to android app I am using the following script.
<?php
$message = "hi there";
$apiKey = "xxxxxxxxxxxx";
$registrationIDs = array("xxxxxxx");
$url = 'https://android.googleapis.com/gcm/send';
// Set POST variables
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message,
)
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
$ch = curl_init(); // Open connection
curl_setopt($ch, CURLOPT_URL, $url );
// Set the url, number of POST vars, POST data
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); // Execute post
if($result === false)
die('Curl failed ' . curl_error());
curl_close($ch);
//return $result;
// curl_close($ch); // Close connection
$response = json_decode($result);
print_r($response);
?>
This code works fine for native android app, but the app developed in titanium when i send push-notification with above script, device receives notification but with "NULL" payload.
I want to know, why? What is wrong with my PHP Script.
UPDATE
This is my code to receive notification
// These events monitor incoming push notifications
CloudPush.addEventListener('callback', function (evt) {
//Ti.API.info('This is the payload data i got'+JSON.parse(evt.payload));
Ti.API.log("This is the GCM response "+JSON.stringify(evt));
alert(evt.payload);
//var payload = JSON.parse(evt.payload);
//Ti.API.info('This is the message data i got'+payload.message);
});
CloudPush.addEventListener('trayClickLaunchedApp', function (evt) {
Ti.API.info('Tray Click Launched App (app was not running)');
});
CloudPush.addEventListener('trayClickFocusedApp', function (evt) {
Ti.API.info('Tray Click Focused App (app was already running)');
});
and this is the response
[INFO] : APSCloudPush: receivePayload: null
[INFO] : APSCloudPush: background: true
[INFO] : APSCloudPush: queuePayload: null
[INFO] : APSCloudPush: showTrayNotification
[ERROR] : APSCloudPush: Payload is null!
The code above given is absolutely correct. I guess the problem is only the keyword payload. Just replace the word "message" to "payload" at server side script as below.
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "payload" => $message,
)
);
Because in Titanium ti.cloudePush module internally search for word payload
I kinda stuck on a problem. I need to send message notification and alert notification to the device. Message notification is sent when a user send message to other and alert notification is generated to alert user from server. That mean I need multiple notification types. I am using this on my server to push notification to my device.
// This is code from the class that take user input
$notify = "This is message"
$msg = array("Message" => $notify);
$sense = $gcm->send_notification($registatoin_ids, $msg);
//This is the send notification in GCM class
public function send_notification($registatoin_ids, $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));
}
// Close connection
curl_close($ch);
echo $result;
}
How can I adjust the above code to meet my requirement. I tried by sending
$fields = array(
"registration_ids" : registatoin_ids,
"data" : {
"type" : "Message",
"Message" : $message,
}
);
But I got error as
E/JSON(3444): <b>Parse error</b>: syntax error, unexpected ':', expecting ')' in <b>/home/a8709494/public_html/mobile/GCM.php</b> on line <b>25</b><br />
You need to use the => operator for this:
$fields = array(
"registration_ids" => "registatoin_ids",
"data" => array(
"type" => "Message",
"Message" => $message,
)
);