How to use FCM Http V1 Api with PHP : Firebase

How to use FCM Http V1 Api with PHP : Firebase

Firebase Cloud Messaging (FCM) has deprecated the legacy api or code we use to send notification in devices. This article will help you to send notifications with the new http v1 api in Php. I am using a codeigniter example.

Requirement:

1. JSON file : FIrst you have to get the Service Account JSON file of your Project.

2. Google Client Library : Install the google client Package in the project with Composer.

composer require google/apiclient

 

Legacy FCM api

Before we used to get an api key for the project and then we hit the 'https://fcm.googleapis.com/fcm/send' with title, body and data and it worked fine.

 

The New Http v1 FCM api

In the https v1 api what we have to do is to generate an access token with the json file and google api client package. Then we have to add that access token in the auth bearer token in the request. Here is how you can do it :

1. First Include the Package in the file. In my case this is my app Controller file

<?php

defined('BASEPATH') or exit('No direct script access allowed');

require 'vendor/autoload.php';

use Google\Client;

class App extends CI_Controller

{

 

}

?>

 

2. Authenticate and get Access Token

<?php

defined('BASEPATH') or exit('No direct script access allowed');

require 'vendor/autoload.php';

use Google\Client;

class App extends CI_Controller

{

 

function getAccessToken($jsonFilePath)

{

$client = new Client();

$client->setAuthConfig($jsonFilePath);

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

$client->useApplicationDefaultCredentials();

$token = $client->fetchAccessTokenWithAssertion();

return $token['access_token'];

}

 

}

?>

 

3.  Make a function to send Message notification

<?php

defined('BASEPATH') or exit('No direct script access allowed');

require 'vendor/autoload.php';

use Google\Client;

class App extends CI_Controller

{

 

function getAccessToken($jsonFilePath)

{

$client = new Client();

$client->setAuthConfig($jsonFilePath);

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

$client->useApplicationDefaultCredentials();

$token = $client->fetchAccessTokenWithAssertion();

return $token['access_token'];

}

 

function sendMessage($accessToken, $projectId, $message)

{

$url = 'https://fcm.googleapis.com/v1/projects/' . $projectId . '/messages:send';

$headers = [

'Authorization: Bearer ' . $accessToken,

'Content-Type: application/json',

];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['message' => $message]));

$response = curl_exec($ch);

if ($response === false) {

throw new Exception('Curl error: ' . curl_error($ch));

}

curl_close($ch);

return json_decode($response, true);

}

 

}

?>

 

4. Combine all the function in one function and hit the function in postman to test your notification.

<?php

defined('BASEPATH') or exit('No direct script access allowed');

require 'vendor/autoload.php';

use Google\Client;

class App extends CI_Controller

{

 

function getAccessToken($jsonFilePath)

{

$client = new Client();

$client->setAuthConfig($jsonFilePath);

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

$client->useApplicationDefaultCredentials();

$token = $client->fetchAccessTokenWithAssertion();

return $token['access_token'];

}

 

function sendMessage($accessToken, $projectId, $message)

{

$url = 'https://fcm.googleapis.com/v1/projects/' . $projectId . '/messages:send';

$headers = [

'Authorization: Bearer ' . $accessToken,

'Content-Type: application/json',

];

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['message' => $message]));

$response = curl_exec($ch);

if ($response === false) {

throw new Exception('Curl error: ' . curl_error($ch));

}

curl_close($ch);

return json_decode($response, true);

}

 

function sendNotification()

{

$jsonFilePath = APPPATH . 'libraries/ you-json-file';

              //Replace this path to your file path

            

 

$projectId = 'your-project-id';

             //Replace with your project id mention in your FCM dahsboard

 

// payload for Notification

$message = [

'token' => your-token,  //token of device where you want to send notifcation

'notification' => [

'title' => '',

'body' => '',

],             // title and body of notification

'data'=> ['key'=> 'value']  // data you want to send in notification

];

try {

$accessToken = $this->getAccessToken($jsonFilePath);

$response = $this->sendMessage($accessToken, $projectId, $message);

print_r($response, true);

} catch (Exception $e) {

echo 'Error: ' . $e->getMessage();

}

}

 

}

?>

 

By Following these steps you will now send the notification to devices. If you have any questions feel free to ask. If you want to know more about FCM Http v1 api you can head to Firebase Website .

Leave a comment