Sharing how you can send notification to android device using php.
Before you send notification you need to have following things in place :
1) Registered with Firebase and setup project and application and get "Server Key" from "Cloud Messaging" Tab
2) Simple mobile application to receive push notification from server. Get the device token to send notification
Now you can use the below code to send a sample notification to android device using PHP:
function sendNotification($tokens,$body,$serverKey) {
$url = "https://fcm.googleapis.com/fcm/send";
$title = "Notification title";
$data = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1'); //if you want to send additional data along with notification.
$notification = array('title' =>"Notification title" , 'body' => "Notification Body");
if($tokens < 2 ) {
$arrayToSend = array('to' => $tokens, 'data' => $data,'priority'=>'high','notification' => $notification);
} else {
//if need to send more then one device use "registration_ids" instead "to"
$arrayToSend = array('registration_ids' => $tokens, 'data' => $data,'priority'=>'high','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);
}
$deviceID = 'Long long long ID from android device';
$serverKey = 'Server Key from firebase';
$message = 'Sample notification for testing';
echo sendNotification($deviceID,$message,$serverKey);
Thanks!!