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 which has received support for FCM just today.

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 .


Answered By: jeromegamez

Method #2

To use the Firebase Cloud Messaging (FCM) HTTP v1 API with PHP, you can follow these steps:

  1. 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.

  2. Install the Guzzle HTTP client library for PHP. You can use Composer to install it by running the following command in your project directory:

    composer require guzzlehttp/guzzle
  3. Create a PHP script that sends an HTTP request to the FCM API endpoint. Here's an example:

    <?php use GuzzleHttp\Client; // Set the FCM API endpoint $url = '{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.

  4. Run the PHP script to send the FCM message.


Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755