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');
defined('BASEPATH') or exit('No direct script access allowed');
require 'vendor/autoload.php';
require 'vendor/autoload.php';
use Google\Client;
use Google\Client;
class App extends CI_Controller
class App extends CI_Controller
{
{
}
}
?>
?>
2. Authenticate and get Access Token
defined('BASEPATH') or exit('No direct script access allowed');
defined('BASEPATH') or exit('No direct script access allowed');
require 'vendor/autoload.php';
require 'vendor/autoload.php';
use Google\Client;
use Google\Client;
class App extends CI_Controller
class App extends CI_Controller
{
{
function getAccessToken($jsonFilePath)
function getAccessToken($jsonFilePath)
{
{
$client = new Client();
$client = new Client();
$client->setAuthConfig($jsonFilePath);
$client->setAuthConfig($jsonFilePath);
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$client->useApplicationDefaultCredentials();
$client->useApplicationDefaultCredentials();
$token = $client->fetchAccessTokenWithAssertion();
$token = $client->fetchAccessTokenWithAssertion();
return $token['access_token'];
return $token['access_token'];
}
}
}
}
?>
?>
3. Make a function to send Message notification
defined('BASEPATH') or exit('No direct script access allowed');
defined('BASEPATH') or exit('No direct script access allowed');
require 'vendor/autoload.php';
require 'vendor/autoload.php';
use Google\Client;
use Google\Client;
class App extends CI_Controller
class App extends CI_Controller
{
{
function getAccessToken($jsonFilePath)
function getAccessToken($jsonFilePath)
{
{
$client = new Client();
$client = new Client();
$client->setAuthConfig($jsonFilePath);
$client->setAuthConfig($jsonFilePath);
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$client->useApplicationDefaultCredentials();
$client->useApplicationDefaultCredentials();
$token = $client->fetchAccessTokenWithAssertion();
$token = $client->fetchAccessTokenWithAssertion();
return $token['access_token'];
return $token['access_token'];
}
}
function sendMessage($accessToken, $projectId, $message)
function sendMessage($accessToken, $projectId, $message)
{
{
$url = 'https://fcm.googleapis.com/v1/projects/' . $projectId . '/messages:send';
$url = 'https://fcm.googleapis.com/v1/projects/' . $projectId . '/messages:send';
$headers = [
$headers = [
'Authorization: Bearer ' . $accessToken,
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json',
'Content-Type: application/json',
];
];
$ch = curl_init();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['message' => $message]));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['message' => $message]));
$response = curl_exec($ch);
$response = curl_exec($ch);
if ($response === false) {
if ($response === false) {
throw new Exception('Curl error: ' . curl_error($ch));
throw new Exception('Curl error: ' . curl_error($ch));
}
}
curl_close($ch);
curl_close($ch);
return json_decode($response, true);
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');
defined('BASEPATH') or exit('No direct script access allowed');
require 'vendor/autoload.php';
require 'vendor/autoload.php';
use Google\Client;
use Google\Client;
class App extends CI_Controller
class App extends CI_Controller
{
{
function getAccessToken($jsonFilePath)
function getAccessToken($jsonFilePath)
{
{
$client = new Client();
$client = new Client();
$client->setAuthConfig($jsonFilePath);
$client->setAuthConfig($jsonFilePath);
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$client->useApplicationDefaultCredentials();
$client->useApplicationDefaultCredentials();
$token = $client->fetchAccessTokenWithAssertion();
$token = $client->fetchAccessTokenWithAssertion();
return $token['access_token'];
return $token['access_token'];
}
}
function sendMessage($accessToken, $projectId, $message)
function sendMessage($accessToken, $projectId, $message)
{
{
$url = 'https://fcm.googleapis.com/v1/projects/' . $projectId . '/messages:send';
$url = 'https://fcm.googleapis.com/v1/projects/' . $projectId . '/messages:send';
$headers = [
$headers = [
'Authorization: Bearer ' . $accessToken,
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json',
'Content-Type: application/json',
];
];
$ch = curl_init();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['message' => $message]));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['message' => $message]));
$response = curl_exec($ch);
$response = curl_exec($ch);
if ($response === false) {
if ($response === false) {
throw new Exception('Curl error: ' . curl_error($ch));
throw new Exception('Curl error: ' . curl_error($ch));
}
}
curl_close($ch);
curl_close($ch);
return json_decode($response, true);
return json_decode($response, true);
}
}
function sendNotification()
function sendNotification()
{
{
$jsonFilePath = APPPATH . 'libraries/ you-json-file';
$jsonFilePath = APPPATH . 'libraries/ you-json-file';
//Replace this path to your file path
//Replace this path to your file path
$projectId = 'your-project-id';
$projectId = 'your-project-id';
//Replace with your project id mention in your FCM dahsboard
//Replace with your project id mention in your FCM dahsboard
// payload for Notification
// payload for Notification
$message = [
$message = [
'token' => your-token, //token of device where you want to send notifcation
'token' => your-token, //token of device where you want to send notifcation
'notification' => [
'notification' => [
'title' => '',
'title' => '',
'body' => '',
'body' => '',
], // title and body of notification
], // title and body of notification
'data'=> ['key'=> 'value'] // data you want to send in notification
'data'=> ['key'=> 'value'] // data you want to send in notification
];
];
try {
try {
$accessToken = $this->getAccessToken($jsonFilePath);
$accessToken = $this->getAccessToken($jsonFilePath);
$response = $this->sendMessage($accessToken, $projectId, $message);
$response = $this->sendMessage($accessToken, $projectId, $message);
print_r($response, true);
print_r($response, true);
} catch (Exception $e) {
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
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 .