This is my first time using FCM, and I had a lot of trouble finding up to date examples on how to send notifications using Firebase Cloud Messaging Notifications via FCM HTTP v1 API with PHP. I'd appreciate any feedback; if none, I hope that others might find this useful.
require 'vendor/autoload.php';
use \Firebase\JWT\JWT;
function get_access_token($service_account_key_file) {
$service_account = json_decode(file_get_contents($service_account_key_file), true);
$now = time();
$token = [
'iss' => $service_account['client_email'],
'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
'aud' => 'https://oauth2.googleapis.com/token',
'iat' => $now,
'exp' => $now + 3600,
];
$jwt = JWT::encode($token, $service_account['private_key'], 'RS256');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt,
]));
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
return $data['access_token'];
}
function send_fcm_notification($server_key, $fcm_token, $title, $body) {
// FCM API URL
$fcm_url = 'https://fcm.googleapis.com/v1/projects/PROJECT-ID/messages:send';
// The payload to send to FCM
$payload = [
'message' => [
'token' => $fcm_token,
'notification' => [
'title' => $title,
'body' => $body
]
]
];
// Encode the payload as JSON
$json_payload = json_encode($payload);
// Prepare headers
$headers = [
'Authorization: Bearer ' . $server_key,
'Content-Type: application/json'
];
// Initialize cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $fcm_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_payload);
// Execute cURL request
$response = curl_exec($ch);
// Check for errors
if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
// Close cURL
curl_close($ch);
// Return response
return $response;
}
// Example usage
$title = 'Test Notification';
$body = 'This is a test notification sent using FCM HTTP v1';
$service_account_key_file = 'firebase-admin.json';
$access_token = get_access_token($service_account_key_file);
// Example usage
$fcm_token = 'DEVICE-TOKEN';
$response = send_fcm_notification($access_token, $fcm_token, $title, $body);
echo $response;