Firebase FCM server php-android - php

I created a simple php code to send a notification to my android devices which have google log in method from firebase implementation. Their tokens are already stored in my database. When I execute my php, it doesn't send the notification. Whoever , if i send a notification trough firebase notification console it works. This is my php code .
function sendGCM($message, $registration_ids) {
//FCM URL
$url = "https://fcm.googleapis.com/fcm/send";
//prepare data
$fields = array (
'registration_ids' => array ($registration_ids),
'data' => array ("message" => $message)
);
$fields = json_encode ( $fields );
//header data
$headers = array ('Authorization: key=<YOUR_API_KEY>', 'Content-Type: application/json');
//initiate curl request
$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 );
// execute curl request
$result = curl_exec ( $ch );
//close curl request
curl_close ( $ch );
//return output
return $result;
}
Error:
when I execute this php file, throw this error:
{
"multicast_id": 5359746182596118281,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "InvalidRegistration"
}
]
}

Try this:-
<?php
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'your_key' );
$registrationIds = array($id); //$id is string not array
// prep the bundle
$notification = array
(
'title' => 'title',
'body' => 'body',
'icon' => 'logo',
'sound' => 'default',
'tag' => 'tag',
'color' => '#ffffff'
);
$data = array
(
'message' => 'message body',
'click_action' => "PUSH_INTENT"
);
$fields = array
(
'registration_ids' => $registrationIds,
'notification' => $notification,
'data' => $data,
'priority' => 'normal'
);
$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 );
echo $result;
?>

Related

I have implemented an FCM server side, Server side not delivering

I am trying to implement a php curl fcm topic broadcasting and it just displays {"message_id":4731721763997571462} and does not deliver.
I have gone through a lot of search and to no end, I can't seem to find the problem.
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'Legacy_server_key' );
// prep the bundle
$msg = array
(
'message' => 'here is a message. message',
'title' => 'This is a title. title',
);
$fields = array
(
'to' => "/topics/hello",
'notification' => $msg
);
$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 );
echo $result;
I just expect to get a notification on the device and maybe there is a way I can trace successful notifications on the google console?
You need to add registration ids with field parameter
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'Legacy_server_key' );
$registrationIds = array( "/topics/obajemusagmailcom" );
// prep the bundle
$msg = array
(
'message' => 'here is a message. message',
'title' => 'This is a title. title',
);
$fields = array
(
//'to' => "/topics/hello",
'registration_ids' => $registrationIds,
'notification' => $msg
);
$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 );
echo $result;
and $registrationIds = array( "/topics/obajemusagmailcom" ); is not registration id of any app, please correct it.
Finally after much horror and tries, turned out the array fields were incorrect and were meant to be
$msg = array
(
'body' => $body,
'title'=>$title
);
$data = array
(
'to' => "/topics/".$topic,
'notification' => $msg
);

How to open an url on webview on click firebase notification?

I'm using php for to send notification. When I add click_action as a parameter, there is nothing on click notification. App doesn't open. But if I don't send click_action everything is okay, app is opening. But of course main page. I just want to specific url on webview on click to notification. How can I do that? Thanks.
$msg = array
(
'body' => 'Test Test',
'title' => 'Test',
'click_action' => 'https://google.com/',
'icon' => 'smallicon',/*Default Icon*/
'sound' => 'mySound'/*Default sound*/
);
$fields = array
(
'to' => 'token',
'notification' => $msg
);
$headers = array
(
'Authorization: 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 );

Sending POST REQUEST Firebase Cloud Messaging

EDITED. Solved at the end of the post.
I´m trying to update GCM to FCM and everything works perfect but the connection with the Firebase API.
In GCM I sent had this code from my PHP script:
define( 'API_ACCESS_KEY', 'myapikeynumber');
$registrationIds = array($registrationID);
$msg = array
(
'message' => $message,
'title' => 'You have new notification(s)',
'subtitle' => 'Please click to view your notification(s)',
'user_id' => $user_id,
'user_type' => $user_type,
'notification_id' => $notification_id
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg,
'time_to_live' => 3
);
$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;
But now don´t know which fields or values I need send to the https://fcm.googleapis.com/fcm/send.
Any help?
SOLUTION
The problem was here:
$registrationIds = array($registrationID);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg,
'time_to_live' => 3
);
Because $registrationsIds had not JSON structure.
So the code is nearly the same, just change that and the URL of the API to https://fcm.googleapis.com/fcm/send.

Google Cloud Messaging returns Invalid Registration

When I am trying to send a gcm message through the below php, I get this error:
{"multicast_id":8958574426215974401,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
However, the server API key is exactly what Google gave me to use, and the gcm_token is accurately being stored to my database. I do not know where the issue lies.
Here is my server side php:
<?php
require 'db_connect.php';
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'AIzaSyREST OF MY KEY' );
//insert the message into a database
$sql = "SELECT gcm_token FROM users WHERE user_id='1' LIMIT 1;";
// preform
if (!mysqli_query($Thesisdb, $sql)) {
printf("Errormessage: ", mysqli_error($Thesisdb));
mysqli_close($Thesisdb);
} else{
$results = mysqli_query($Thesisdb, $sql);
$registrationIds = array($results);
// prep the bundle
$msg = array
(
'message' => '$user',
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
);
$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;
}
?>
mysqli_query returns Boolen value (true or false) so this will not going to works directly.
we have to convert mysqli_query return values to array using fetch array, fetch assoc.
$results = mysqli_query($Thesisdb, $sql);
$registrationIds = array($results);
Code to combile all GCM Tokens.
registrationIds=array();
$sql="SELECT `user_id`,`push_notification_registration_id` FROM `tbl1` WHERE `user_status`='Active' AND `push_notification_registration_id`!=''";
$fire=mysqli_query($this->conn,$sql);
$users=array();
if( (isset($fire))&&(!empty($fire)) ){
while($result=mysqli_fetch_assoc($fire)){
array_push($users,$result);
}
}
foreach($users as $single_user){
$register_id=$single_user['push_notification_registration_id'];
array_push($registrationIds,$register_id);
}
$msg = array
(
'title' => $news_title,
'subtitle' => $news_description,
'tickerText' => 'Ticker Text',
'vibrate' => 1,
'sound' => 1,
'news_id' => $news_id,
'notification_type' => 'news'
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . YOUR_GOOGLE_API_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,true ) );
$result = curl_exec($ch );
curl_close( $ch );

GCM PHP : Field "data" must be a JSON array

I do know there are several posts here which talks about my issue but none works for me.Its either incomplete solution mentioned or left as is.
My query:
I am getting
Field "data" must be a JSON array: [{"sound":1,"vibrate":1,"message":"Push Notification Message","title":"Push Notification Title"}]
error when trying to use GCM. My regID, Sender ID, and server key looks fine.
May know how to resolve this.
PHP Code:
<?php
$to="";
if($_GET['id']){
$to = $_GET['id'];
}
$title="Push Notification Title";
$message="Push Notification Message";
sendPush($to,$title,$message);
function sendPush($to,$title,$message)
{
// API access key from Google API's Console
// replace API
define( 'API_ACCESS_KEY', 'API_HIDDEN');
$registrationIds = array($to);
$msg = array
(
'message' => $message,
'title' => $title,
'vibrate' => 1,
'sound' => 1
// you can also add images, additionalData
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => array($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;
}
?>
Replace the line
$message="Push Notification Message";
by
$message=array( 'response' => json_encode("Push Notification Message"));
GCM requires the response data in JSONArray format.
OR Use below method
function sendGoogleCloudMessage( $data, $ids ) {
$apiKey = 'YOUR_KEY';
$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_IPRESOLVE, CURL_IPRESOLVE_V4 );
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 ) ) {
$result = $result . 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
return $result;
}
and call it using
$response = array();
$response["title"] = "title";
$response["message"] = "Notification message.";
$data = array( 'response' => json_encode($response));
$result = sendGoogleCloudMessage($data, $ids);
It is working in my application.
Hope it'll help.

Categories