I have used FCM with the legacy protocol but cannot find any concrete documentation to use the new FCM HTTP v1 API with php.
I have managed to import the Google API Client Library into my project but cannot find any documentation or tutorials on how to obtain the access token for the required scopes for fcm messages.
Maybe a bit late, but this is how to retrieve an oath token to be used with the FCM HTTP v1 API.
public function configureClient()
{
$client = new Google_Client();
try {
$client->setAuthConfig("include_your_private_json_key_path_here");
$client->addScope(Google_Service_FirebaseCloudMessaging::CLOUD_PLATFORM);
// retrieve the saved oauth token if it exists, you can save it on your database or in a secure place on your server
$savedTokenJson = $this->readFile();
if ($savedTokenJson != null) {
// the token exists, set it to the client and check if it's still valid
$client->setAccessToken($savedTokenJson);
if ($client->isAccessTokenExpired()) {
// the token is expired, generate a new token and set it to the client
$accessToken = $this->generateToken($client);
$client->setAccessToken($accessToken);
}
} else {
// the token doesn't exist, generate a new token and set it to the client
$accessToken = $this->generateToken($client);
$client->setAccessToken($accessToken);
}
$oauthToken = $accessToken["access_token"];
// the client is configured, now you can send the push notification using the $oauthToken.
} catch (Google_Exception $e) {
// handle exception
}
}
private function generateToken($client)
{
$client->fetchAccessTokenWithAssertion();
$accessToken = $client->getAccessToken();
// save the oauth token json on your database or in a secure place on your server
$tokenJson = json_encode($accessToken);
$this->saveFile($tokenJson);
return $accessToken;
}
Please note that saveFile()
and readFile()
methods should be implemented as you prefer to store and retrieve the oath token json. Follow the migration guide for the payload structure.
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With