How to use FCM Http V1 Api with PHP : Firebase

How to use FCM Http V1 Api with PHP : Firebase

Introduction

So, you are finishing up your application design and need a push notification feature to make it complete. However, you just can’t figure out the coding for integrating this concluding element to finalize your project. Our comprehensive guide to “How to use FCM Http V1 Api with PHP: Firebase” will help you enhance the functionality of your app and offer actionable insights on how to apply Firebase Cloud Messaging to your program design. 

Herein, you will find clear instructions with code snippets that show you how to set up and utilize FCP HTTP V1 API using PHP. Whether you are a learner building an app from scratch or a seasoned developer needing some help with using the latest FCM HTTP V1 API, this instructive manual has you covered.

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

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

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

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.

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();

}

}

 

}

?>

Conclusion

You have mastered the basics of FCM and are ready to utilize it. Learn to integrate FCM HTTP V1 API into your software using PHP to unlock its full potential. Implement your new found knowledge and build interactive and immersive applications everyone loves to use.

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

Leave a comment