Search code examples
phprestfirebasefirebase-cloud-messaging

Firebase Cloud Messaging HTTP V1 API: How to Get the Auth 2.0 Access Token with REST Calls?


In order to use the HTTP V1 API (not the legacy API) with PHP, the REST interface has to be used.

https://firebase.google.com/docs/cloud-messaging/send-message#top_of_page

I am wondering how to get the Auth 2.0 access token?

https://firebase.google.com/docs/cloud-messaging/auth-server

As there is no Google API Client Library for PHP (see examples in the link above), how can the Auth 2.0 token be received with REST calls (no need to show PHP code)?

The related question: once received this short living token, how to refresh this token? What is the workflow?

Thanks a lot!


Solution

  • There actually is a kind of "Google Api Client Library" for PHP, even two of them:

    https://github.com/google/google-api-php-client

    and

    https://github.com/GoogleCloudPlatform/google-cloud-php

    The one provides access to APIs that the other doesn't, so it's worth looking which one provides what - you will perhaps need to use both of them.

    In the README of the https://github.com/google/google-api-php-client repository, you can find a description on how to obtain the OAuth access and refresh tokens.

    Both libraries work with Guzzle underneath and provide a way to decorate your own Guzzle HTTP client with an authorization middleware so that you don't have to.

    So, if one of the libraries doesn't provide support for an API you want to access, you can apply the code from the following snippet and access the API in question yourself (from Google Api PHP Client - "Making HTTP requests directly"):

    // create the Google client
    $client = new Google_Client();
    
    /**
     * Set your method for authentication. Depending on the API, This could be
     * directly with an access token, API key, or (recommended) using
     * Application Default Credentials.
     */
    $client->useApplicationDefaultCredentials();
    
    // returns a Guzzle HTTP Client
    $httpClient = $client->authorize();
    

    Shameless plug: I am maintaining a separate Admin SDK for accessing Firebase related APIs at https://github.com/kreait/firebase-php , and it has a FCM component, which is documented here: https://firebase-php.readthedocs.io/en/stable/cloud-messaging.html