Skip to content

Instantly share code, notes, and snippets.

@benixal
Created September 22, 2023 10:10
Show Gist options
  • Save benixal/59c5be11d1f67502698decf0c80e2cf2 to your computer and use it in GitHub Desktop.
Save benixal/59c5be11d1f67502698decf0c80e2cf2 to your computer and use it in GitHub Desktop.
PHP code snippet for sending a Firebase Cloud Messaging (FCM) notification
<?php
$authorizationHeader = "Authorization: Bearer <YOUR_ACCESS_TOKEN>";
/*
Steps to get Authentication Bearer :
1.Got to Google OAuth Playground: https://developers.google.com/oauthplayground
2.In the "Input your own scopes" for FCM use this url: https://www.googleapis.com/auth/firebase.messaging
3.Tap Authorize API.
4.Pick correct user for authorisation and allow access.
5.In the Step 2: Exchange authorization code for tokens tap Exchange authorisation code for tokens.
6.Access token is your Bearer.
SOURCE: https://stackoverflow.com/a/62670409
*/
$data = [
"message" => [
"notification" => [
"title" => "Hello from PHP",
"body" => "Hi this is body"
],
"token" => "<CLIENT_REGISTRATION_TOKEN>"
]
];
$jsonData = json_encode($data);
$ch = curl_init("https://fcm.googleapis.com/v1/projects/<PROJECT_ID>/messages:send");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, [$authorizationHeader, "Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment