Migrate from legacy FCM APIs to HTTP v1 in Laravel and Send Push Notification (Topic)
Share this:
Google recently updated their Firebase Cloud messaging API. Even they dont have proper guideline on how to upgrade to their new API for PHP or Laravel Application. In this article i am going to describe how you can migrate to latest Firebase Cloud messaging API.
1. Create a firebase project and go to the Project Settings then generate a new Private key and download it
After downloading the file move it to the laravel /storage/app directory rename it to service-account.json
2. Install the google api client package in your laraval project running the following command
composer require google/apiclient
3. Now we can dive into the coding section. The first step in coding is to get the firebase access token. Then we can send firebase push notification using the access token. The senPushNotification() function sends push notification to the specific topic.
Replace the Project ID with your firebase project ID and your topic name with your topic.
<?php
namespace App\Http\Controllers;
use Google\Client as GoogleClient;
use Illuminate\Support\Facades\Http;
class FcmController extends Controller
{
public function getToken(){
$service_file = storage_path("storage/app/service-account.json");
$client = new GoogleClient();
$client->setAuthConfig($service_file);
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
$client->refreshTokenWithAssertion();
$response = $client->getAccessToken();
$token = $response['access_token'];
return $token;
}
public function sendPushNotification(){
$projectID = "YOUR_FIREBASE_PROJECT_ID";
$topicName = "YOUR_TOPIC_NAME";
$notificationTitle = "YOUR_NOTIFICATION_TITLE";
$notificationBody = "YOUR_NOTIFICATION_DESCRIPTION";
$token = $this->getToken();
$response = Http::withHeaders([
"Content-Type" => "application/json",
"Authorization" => "Bearer $token"
])->post("https://fcm.googleapis.com/v1/projects/$projectID/messages:send", [
"message" => [
"topic"=> "$topicName",
"notification"=> [
"title"=> "$notificationTitle",
"body"=> "$notificationBody",
],
"data"=> [
"id" => ""
// Pass Notification Data Here
]
]
]);
return $response->ok();
}
}