Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Google API PHP Client - Firebase Cloud Messaging Service v1 example
<?php
/**
* This serves as an example of how to use the Google API PHP Client
* with Firebase Cloud Messaging Service.
*
* The client can be found here:
* https://github.com/google/google-api-php-client
*
* At the time of writing this, there's no Service object for the correct
* scope for Firebase Messaging, so here's an example of how this can be
* done with provididing the scope manually.
*
* Info regarding authorization and requests can be found here:
* https://firebase.google.com/docs/cloud-messaging/server
*/
require 'vendor/autoload.php';
$client = new Google_Client();
// Authentication with the GOOGLE_APPLICATION_CREDENTIALS environment variable
$client->useApplicationDefaultCredentials();
// Alternatively, provide the JSON authentication file directly.
$client->setAuthConfig(__DIR__.'/auth.json');
// Add the scope as a string (multiple scopes can be provided as an array)
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
// Returns an instance of GuzzleHttp\Client that authenticates with the Google API.
$httpClient = $client->authorize();
// Your Firebase project ID
$project = "myproject-4e6ed";
// Creates a notification for subscribers to the debug topic
$message = [
"message" => [
"topic" => "debug",
"notification" => [
"body" => "This is an FCM notification message!",
"title" => "FCM Message",
]
]
];
// Send the Push Notification - use $response to inspect success or errors
$response = $httpClient->post("https://fcm.googleapis.com/v1/projects/{$project}/messages:send", ['json' => $message]);
@tmacedo29

This comment has been minimized.

Copy link

@tmacedo29 tmacedo29 commented May 3, 2018

Thank you.. it help me a lot. =)

@srgkas

This comment has been minimized.

Copy link

@srgkas srgkas commented May 10, 2018

Great, thank you!

@nayzawoo

This comment has been minimized.

Copy link

@nayzawoo nayzawoo commented May 16, 2018

Thanks

@mgerasimchuk

This comment has been minimized.

Copy link

@mgerasimchuk mgerasimchuk commented Aug 28, 2018

Thank you..!!! it help me a lot to!!!

@Instrye

This comment has been minimized.

Copy link

@Instrye Instrye commented Sep 19, 2018

Thanks.

@3ffusi0on

This comment has been minimized.

Copy link

@3ffusi0on 3ffusi0on commented Nov 14, 2018

The $project variable used in the url https://fcm.googleapis.com/v1/projects/{$project}/messages:send should be the one defined in the .json f file for project_id key. I had trouble using the project_id defined on firebase page.

@jsancheztak

This comment has been minimized.

Copy link

@jsancheztak jsancheztak commented Nov 27, 2018

I have been trying to send push notifications. Your code works, but I having problems sending notification to one device.

My code

    $token = "fFIF0lT6mEs:APA91bGpCdSXzjX....h3JDyDp"; //Token generated in app
    $title = "FCM Message";
    $body = "This is an FCM notification message!";

    $client = new Google_Client();

    // Set auth config file
    $client->setAuthConfig($json_file_path);
    $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
    // Returns an instance of GuzzleHttp\Client that authenticates with the Google API.
    $httpClient = $client->authorize();

    // Your Firebase project ID
    $project = 'my_project_id';

    // Creates a notification for subscribers to the debug topic
    $message = [
        "message" => [
            // Send with token is not working, but works without it
            "token" => $token,
            "topic" => "debug",
            "notification" => [
                "body" => $body,
                "title" => $title,
            ]
        ]
    ];

    // Send the Push Notification - use $response to inspect success or errors
    $response = $httpClient->post("https://fcm.googleapis.com/v1/projects/$project/messages:send", ['json' => $message]);
    dump($response);

This code always returns reasonPhrase: "Bad Request" with statusCode: 400

Am i missing something? Thanks!

@jsancheztak

This comment has been minimized.

Copy link

@jsancheztak jsancheztak commented Nov 27, 2018

Sorry, after lots of tests I have change the message al follows:

    // Creates a notification for subscribers to the debug topic
    $message = [
        "message" => [
            //"topic" => "debug", // Send to topic or token are incompatibles
            "notification" => [
                "body" => $body,
                "title" => $title,
            ],
            // Send with token is not working
            "token" => $token,
        ]
    ];

Thanks a lot!

@KiyokGU

This comment has been minimized.

Copy link

@KiyokGU KiyokGU commented Jan 31, 2019

Hi everybody, I'm trying this code but I get 403 Forbidden as response!
Could you help me to understand what I'm doing wrong!

Thanks, Martin

@sakilimran

This comment has been minimized.

Copy link

@sakilimran sakilimran commented Apr 9, 2019

Getting the following error response. Is there any permission issue for service account? @Repox

{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}
@kbsali

This comment has been minimized.

Copy link

@kbsali kbsali commented Apr 11, 2019

thanks for the good hint!

@hristo-atanasov

This comment has been minimized.

Copy link

@hristo-atanasov hristo-atanasov commented Apr 19, 2019

Is this code still working? I don't know why but I constantly get error 401 Unautorized .. :|

@deepakyadav23

This comment has been minimized.

Copy link

@deepakyadav23 deepakyadav23 commented Jun 19, 2019

This was helpful.
Download and install composer then use windows powershell to use composer.
composer require google/apiclient:"^2.0"

Make sure to use your service account json file which contains the private key.
From your filebase console->settings->service account

There is an issue with the guzzle
ErrorException/app/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php

The solution:
#replace this
if (count($this->handles) >= $this->maxHandles)
#with this
if ( $this->handles != null && count($this->handles) >= $this->maxHandles )

in the file on line 67, and everything works like a charm.

@su1736

This comment has been minimized.

Copy link

@su1736 su1736 commented Aug 17, 2019

Thanks a lot!
I was trying to do it with GoogleApi docs but google documentation sometimes so quirky.. )

@ekohadim

This comment has been minimized.

Copy link

@ekohadim ekohadim commented Nov 8, 2019

Thanks! It works. But i have issues to send message to web app running on Firefox and Edge. Send to chrome is fine. Any one have any clue?

@davists

This comment has been minimized.

Copy link

@davists davists commented Nov 13, 2019

Thank you.. it help me a lot. =)

@akshaywo

This comment has been minimized.

Copy link

@akshaywo akshaywo commented Aug 28, 2020

How to use multiple device tokens here?

@Repox

This comment has been minimized.

Copy link
Owner Author

@Repox Repox commented Sep 3, 2020

How to use multiple device tokens here?

Hey @akshaywo

The solution proposed in this Gist is a couple of years old, I wouldn't recommend this approach anymore.

The package from krait called firebase-php is what I would recommend these days as this package easily solves what you need, also sending to multiple device tokens.

Quick and easy implementation too:

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;

$factory = (new Factory)->withServiceAccount(base_path('service_account_credentials.json')); // or use auto-loading of credentials

$messaging = $factory->createMessaging();

$message = CloudMessage::withTarget('topic', 'debug')
                ->withNotification(Notification::create('Notification title', 'This is an FCM notification message!'));

$messaging->send($message);
@akshaywo

This comment has been minimized.

Copy link

@akshaywo akshaywo commented Sep 4, 2020

Thank you so much for your reply! It helps a lot.

@Jean-Kenned

This comment has been minimized.

Copy link

@Jean-Kenned Jean-Kenned commented Feb 5, 2021

Thanks a lot! Very helpful !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment