How to send push notifications using firebase cloud messaging with PHP?
In this tutorial, we will learn, How to send push notifications using firebase cloud messaging with PHP. You know, GCM(Google Cloud Messaging) for sending the push notification to Android devices, but Google has been launched FCM(Firebase Cloud Messaging), and the newer version of GCM with more features available. We will discuss the PHP developers who want to send Firebase Cloud Messaging notifications by using PHP.
When we send GCM messages, we required an Authorization key and Device Token. And we think how to get the Authorization key and device token, so we can get the Authorization key available in Firebase:
Console -> Project Settings -> CLOUD MESSAGING -> Server key
And then we get the device token at the time which user registering or logs by the android API.
How to send push notification using firebase cloud messaging with php
<?php
function push_notification_php($device_token, $message) {
/* API URL */
$url = 'https://fcm.googleapis.com/fcm/send';
/* authorization_key */
$authorization_key = 'AAAAKlspijkide:AKDMKsjkldf...FjkdldfKLUM-n';
$fields = array(
'registration_ids' => array($device_token),
'data' => array (
"message" => $message
)
);
$fields = json_encode($fields);
$headers = array (
'Authorization: key=' . $authorization_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, $fields);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
}