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"}
}
}}
Related
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
I am having trouble getting Google Cloud Messaging for Android working.
I have had it working before but it decides to stop working after the first couple of times.
In order to get it working again I have to delete my API key and recreate it.
I am using PHP with a SERVER API key with a IP whitelist of ::/0 (All IPv6 apparently)
Note: My android app requests a device message key each time the app is opened (Usually returns the same message key)
The Error I get is: Unauthorized Error 401
When I got to the following url to check my app message id i get 'invalid token'.
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=APA91bHuQEWGsvlRUhlSztNpqLVOZQGZPiGFHjQw2plcF-z8t29zvNNgNoDiRe-CbY9Fb-XcPQAFqJvy4HBfWTrTPPpzcY3pd5vX38WGalOsZ5iDiJeglpafLTC7eFkN4UA9JPKWZ4lqNiGLoH3w8W_GpFAFW5F-kLLzcbrPxwSFqyfUpmM8-14
The PHP code I am using is:
$data = array( 'message' => 'Hello World!222!' );
$ids = array('APA91bHuQEWGsvlRUhlSztNpqLVOZQGZPiGFHjQw2plcF-z8t29zvNNgNoDiRe-CbY9Fb-XcPQAFqJvy4HBfWTrTPPpzcY3pd5vX38WGalOsZ5iDiJeglpafLTC7eFkN4UA9JPKWZ4lqNiGLoH3w8W_GpFAFW5F-kLLzcbrPxwSFqyfUpmM8-14');
$apiKey = 'AIzaSyATkp_UTZh....'; //obviously the complete key is used...
$url = 'https://android.googleapis.com/gcm/send';
$post = array('registration_ids' => $ids, 'data' => $data);
$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;
Thanks for any help given.
EDIT: It seems to work since I unregistered my device and reregistered it with GCM. I am not sure if this is a permanent fix but it works for now.
I tried this code.
function sendNotification( $apiKey, $registrationIdsArray, $messageData )
{
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
$data = array(
'data' => $messageData,
'registration_ids' => $registrationIdsArray
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
And to call this function:
$message = "the test message";
$tickerText = "ticker text message";
$contentTitle = "content title";
$contentText = "content body";
$registrationId = 'APA91bEgsAG3vmliDnJE7jfLAOGSUv3K9p41MkNranPFV4EY0svABRax8NY5oulOHv7s3v2Ks_bQutsLLw8j4mHOr5LkrRlFfXxfs3hxxwAlxIOG7cXCB4YPhlLCDspVtImyWBL_znGgkZzEWCncV3tidHMV'; (Id is wrong here for security reasons)
$apiKey = "AIzaSyD6kZoY3Qb_1ut57IEmwdRg0JuxC42W1"; (Key is wrong here for security reasons)
$response = sendNotification(
$apiKey,
array($registrationId),
array('message' => $message, 'tickerText' => $tickerText, 'contentTitle' => $contentTitle, "contentText" => $contentText) );
echo $response;
And now i am stuck. I just create a PHP page with my own registration id of device and google API key.
But it shows me error of:
Unauthorized
Error 401
When i run this URL http://vbought.com/sendnotification.php
i even added my server IP and domain name in the GCM reference
.vbought.com/
*.vbought.com
50.87.3.82
is there something i did wrong? Or i need to know? I am just trying to send one message to my only device.
Thank you! (in advance)
i found the answer. And the answer is i dont need to define anything in GCM. Like i defined my domain name and IP address. So i dont need to do anything. Just leave it blank and it will work like charm...
have a nice day :)
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);
?>
I want to sent message from my server to phone, by PHP.
Here is my code:
$apiKey = "AIxxxxxxxxxxxxxxxxxxxx";
$registrationIDs = array( $c2dmId );
$url = "https://android.googleapis.com/gcm/send";
$headers = array(
'Authorization: key='.$apiKey,
'Content-Type: application/json'
);
$fields = array(
'collapse_key' => $collapseKey,
'data' => array(
"type" => $msgType,
"extra" => $msgExtra,
"uuid" => $uuid,
"user_id" => $userId),
'registration_ids' => $registrationIDs,
);
print (json_encode($fields));
echo "<br/>";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch);
$resultInfo = curl_getinfo($ch);
echo "resultinfo: $resultInfo <br>";
foreach ($resultInfo as $key => $value) {
echo "$key => $value <br>";
}
curl_close($ch);
die ("Result: $result");
Where $c2dmId is just registrationId which I send to server from phone. As a result I get (in $result variable):
<HTML>
<HEAD>
<TITLE>Not Found</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Not Found</H1>
<H2>Error 404</H2>
</BODY>
</HTML>
And I don't know why. Can anyone help? Documentation dosen't say anything about 404 code, so I really don't know what is going on.
Oh, I completely forgot about this question, sorry for that. I already find out what was the problem.
Earlier I used that code which I posted before to send messages via C2DM. I made only a few improvements to adjust it to GCM. And one of variables ($msgExtra) could equal null in some case. It was intended behaviour and with C2DM it worked just fine.
Unfortunately, when you try to pass null in JSON via GCM you get 404 error, although GCM documentation says nothing about that...
So code which I posted is good as far as you don't try to send null.
Solution of my problem is to replace null value with something like "".
And once again - sorry that I post it just now, I completely forgot about this question.
Generate a Browser API Key from the Google APIs Console, and use it instead of the server key in the "Authorization" header. Once you do that, this error will go away.
This is caused by a serious mistake in the GCM Documentation that states you should use a Server Key in the Authorization header (as written Over here).
may be its already resolved for you.But here is the working version of your code which i tested on device.
<?php
$apiKey = "AI.....";
$registrationIDs = array( "You registration key" );
$url = "https://android.googleapis.com/gcm/send";
$headers = array(
'Authorization: key='.$apiKey,
'Content-Type: application/json'
);
$msgType = "hello";
$msgExtra = "rock";
$uuid = '1234';
$userId = '5678';
/* data you need to define message you want to send in APP.For ex: here myssg in what i am fetching at client side, so in notification it will show hello. You can change accordingly. */
$fields = array(
'collapse_key' => $collapseKey,
'data' => array(
"mymsg" => $msgType,
"extra" => $msgExtra,
"uuid" => $uuid,
"user_id" => $userId),
'registration_ids' => $registrationIDs,
);
print (json_encode($fields));
echo "<br/>";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch);
$resultInfo = curl_getinfo($ch);
echo "resultinfo: $resultInfo <br>";
foreach ($resultInfo as $key => $value) {
echo "$key => $value <br>";
}
curl_close($ch);
die ("Result: $result");
?>
This will not give you 404 error.Hope this will help you or some looking for server side implementation in PHP .