Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel API -Send Notifications to android and iOS client apps with Firebase FCM

I am working on a project which uses android and iOS as front and Backend as Laravel APIs. So I want to send notifications to all users (include android/iOS) when some event happen like New Offer Created/New Stock available.. So to do this is have gone through some google searches and finally knew that the curl approach seems to be deprecated.. so Is there any better Way to integrate firebase FCM into my Laravel project.. if it so How? I hope someone can answer this.. Thanks in Advance

like image 482
JEJ Avatar asked Nov 01 '25 21:11

JEJ


2 Answers

Fcm for core already answered here How to send Notification to Android from php? so in laravel you can

create a config file in config folder and name it as firebase.php

 <?php

        return [
            'fcm_url'=>env('FCM_URL'),
            'fcm_api_key'=>env('FCM_API_KEY'),
        ];

and in env file

FCM_URL=https://fcm.googleapis.com/fcm/send
FCM_API_KEY=

and in code you can create Trait class

<?php


namespace App\Traits;

use Illuminate\Support\Facades\Http;

trait Firebase
{

    public  function firebaseNotification($fcmNotification){

        $fcmUrl =config('firebase.fcm_url');

        $apiKey=config('firebase.fcm_api_key');

        $http=Http::withHeaders([
            'Authorization:key'=>$apiKey,
            'Content-Type'=>'application/json'
        ])  ->post($fcmUrl,$fcmNotification);

        return  $http->json();
    }
}

Then you can include this trait any class where you want to call

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Traits\Firebase;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use Firebase,AuthenticatesUsers;

    
    public function sendNotification(){
        $token="";
        $notification = [
            'title' =>'title',
            'body' => 'body of message.',
            'icon' =>'myIcon',
            'sound' => 'mySound'
        ];
        $extraNotificationData = ["message" => $notification,"moredata" =>'dd'];

        $fcmNotification = [
            //'registration_ids' => $tokenList, //multple token array
            'to'        => $token, //single token
            'notification' => $notification,
            'data' => $extraNotificationData
        ];
        
        return $this->firebaseNotification($fcmNotification); 

    }
}

Also i suggest to create events based to better code optimization

Also read

https://firebase.google.com/docs/cloud-messaging/http-server-ref

registration_ids for multiple users

This parameter specifies the recipient of a multicast message, a message sent to more than one registration token.

The value should be an array of registration tokens to which to send the multicast message. The array must contain at least 1 and at most 1000 registration tokens. To send a message to a single device, use the to parameter.

Multicast messages are only allowed using the HTTP JSON format.

For new Version as mentioned in comment by @JEJ

https://firebase.google.com/docs/cloud-messaging/migrate-v1#python_1

So it will be

  $http=Http::withHeaders([
                'Authorization'=>'Bearer '.$apiKey,
                'Content-Type'=>'application/json; UTF-8'
            ])  ->post($fcmUrl,$fcmNotification);
    
            return  $http->json();

and simple notification message for $fcmNotification

{
  "message": {
    "topic": "news",
    "notification": {
      "title": "Breaking News",
      "body": "New news story available."
    },
    "data": {
      "story_id": "story_12345"
    }
  }
}

for targeting multiple platforms

{
  "message": {
    "topic": "news",
    "notification": {
      "title": "Breaking News",
      "body": "New news story available."
    },
    "data": {
      "story_id": "story_12345"
    },
    "android": {
      "notification": {
        "click_action": "TOP_STORY_ACTIVITY"
      }
    },
    "apns": {
      "payload": {
        "aps": {
          "category" : "NEW_MESSAGE_CATEGORY"
        }
      }
    }
  }
}
like image 121
John Lobo Avatar answered Nov 03 '25 10:11

John Lobo


Try Laravel FCM package

For your ease, writing steps here...

SETUP

  1. Installation (terminal)

    composer require brozot/laravel-fcm
    
  2. config/app.php

    • providers

      'providers' => [
          // ...
      
          LaravelFCM\FCMServiceProvider::class,
      ]
      
    • aliases

      'aliases' => [
          ...
      
          'FCM'      => LaravelFCM\Facades\FCM::class,
      ]
      
  3. Publish the package config file (terminal)

    php artisan vendor:publish --provider="LaravelFCM\FCMServiceProvider"
    

USAGE

  1. In your Controller,

    • import libraries

      use LaravelFCM\Message\OptionsBuilder;
      use LaravelFCM\Message\PayloadDataBuilder;
      use LaravelFCM\Message\PayloadNotificationBuilder;
      use FCM;
      
    • sending Downstream Message to device(s)

      $optionBuilder = new OptionsBuilder();
      $optionBuilder->setTimeToLive(60*20);
      
      $notificationBuilder = new PayloadNotificationBuilder('my title');
      $notificationBuilder->setBody('Hello world')->setSound('default');
      
      $dataBuilder = new PayloadDataBuilder();
      $dataBuilder->addData(['a_data' => 'my_data']);
      
      $option = $optionBuilder->build();
      $notification = $notificationBuilder->build();
      $data = $dataBuilder->build();
      
      $token = "a_registration_from_your_database" /* OR */ [ /* Array of tokens */ ];
      
      $downstreamResponse = FCM::sendTo($token, $option, $notification, $data);
      
      $downstreamResponse->numberSuccess();
      $downstreamResponse->numberFailure();
      $downstreamResponse->numberModification();
      
      // return Array - you must remove all this tokens in your database
      $downstreamResponse->tokensToDelete();
      
      // return Array (key : oldToken, value : new token - you must change the token in your database)
      $downstreamResponse->tokensToModify();
      
      // return Array - you should try to resend the message to the tokens in the array
      $downstreamResponse->tokensToRetry();
      
      // return Array (key:token, value:error) - in production you should remove from your database the tokens
      $downstreamResponse->tokensWithError();
      
like image 39
TalESid Avatar answered Nov 03 '25 11:11

TalESid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!