How to use the FCM HTTP v1 API with php
✔ Recommended Answer
If you are willing to use an existing library instead of implementing it yourself, you might consider having a look at https://github.com/kreait/firebase-php/ which has received support for FCM just today.
https://firebase-php.readthedocs.io/en/latest/cloud-messaging.html
If it isn't for you, you will at least be able to extract the connections to the FCM REST API with PHP from the source code. In short, it's the implementation of https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages .
Source: stackoverflow.com
Answered By: jeromegamez
To use the Firebase Cloud Messaging (FCM) HTTP v1 API with PHP, you can follow these steps:
Obtain a Firebase Cloud Messaging server key. To do this, go to the Firebase Console and select your project. Then, go to the Project Settings > Cloud Messaging tab and copy the Server Key.
Install the Guzzle HTTP client library for PHP. You can use Composer to install it by running the following command in your project directory:
bashcomposer require guzzlehttp/guzzle
Create a PHP script that sends an HTTP request to the FCM API endpoint. Here's an example:
php<?php use GuzzleHttp\Client; // Set the FCM API endpoint $url = 'https://fcm.googleapis.com/v1/projects/{project_id}/messages:send'; // Set the request headers $headers = [ 'Authorization' => 'Bearer ' . $serverKey, 'Content-Type' => 'application/json', ]; // Set the message payload $message = [ 'message' => [ 'token' => $deviceToken, 'notification' => [ 'title' => $title, 'body' => $body, ], ], ]; // Send the HTTP request using Guzzle $client = new Client(); $response = $client->post($url, [ 'headers' => $headers, 'json' => $message, ]); // Check the response status code if ($response->getStatusCode() === 200) { echo 'Message sent successfully'; } else { echo 'Message could not be sent'; }
In this example, replace
{project_id}
with your Firebase project ID,$serverKey
with your Firebase Cloud Messaging server key,$deviceToken
with the device token of the device you want to send the message to,$title
with the title of the notification, and$body
with the body text of the notification.Run the PHP script to send the FCM message.
Comments
Post a Comment