Get FCM access token in PHP using Google library.

03-11-2024

Very often we need to send notifications from the PHP applications and in order to send the same we requires access token to be send with the body payload. 

Google provides the required library for several languages to get the access token.

Below is the sample function to get the access token using Google PHP library. It is using MySQL table to store the access token and refresh it when the stored access token expired. You may have other mechanism to store the access token.

$accessToken will hold the either stored or refreshed token.

settings.php -> will contains the value of $mysqlservername, $mysqlusername, $mysqlpassword, $mysqldatabase

service-account.json -> You need to download from Account section of FCM console,

google-api-php-client--PHP8.0 -> You need to download from Google API repository.


function send_to_fcm($title,$message,&$response){

    include "settings.php"; 

    $conn = mysqli_connect($mysqlservername, $mysqlusername, $mysqlpassword, $mysqldatabase);

    if (!$conn) {

        die("Connection failed: " . mysqli_connect_error());

    }

    $sql = "select access_token from fcmtoken where expires_in > " . time();

    $result = $conn->query($sql);

    if ($result->num_rows == 1) {

        $row = $result->fetch_array();

        $accessToken = $row["access_token"];

    }else{

        require_once '../google-api-php-client--PHP8.0/vendor/autoload.php';

        $credentialsFilePath = 'service-account.json';

        $client = new Google_Client();

        $client->setAuthConfig($credentialsFilePath);

        $client->addScope('https://www.googleapis.com/auth/firebase.messaging');

        $client->refreshTokenWithAssertion();

        $token = $client->getAccessToken();

        $accessToken = $token['access_token'];

        $created = $token['created'];

        $expires_in = $token['expires_in'] + $created;

        $sql = "delete from fcmtoken";

        $result = $conn->query($sql);

        $sql = "insert into fcmtoken(access_token,expires_in) values('" . $accessToken . "'," . $expires_in  . ")";

        $result = $conn->query($sql);

    }

   //  $accessToken will hold the access token value to use further

}


MySQL table create script.

CREATE TABLE `fcmtoken` (

  `id` bigint NOT NULL AUTO_INCREMENT,

  `access_token` text,

  `expires_in` int DEFAULT NULL,

  PRIMARY KEY (`id`)

);