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"}
}
}}