Skip to content

Instantly share code, notes, and snippets.

@Repox
Created April 12, 2018 06:04
Show Gist options
  • Save Repox/64ac4b3582f8ac42a6a1b41667db7440 to your computer and use it in GitHub Desktop.
Save Repox/64ac4b3582f8ac42a6a1b41667db7440 to your computer and use it in GitHub Desktop.
Google API PHP Client - Firebase Cloud Messaging Service v1 example
<?php
/**
* This serves as an example of how to use the Google API PHP Client
* with Firebase Cloud Messaging Service.
*
* The client can be found here:
* https://github.com/google/google-api-php-client
*
* At the time of writing this, there's no Service object for the correct
* scope for Firebase Messaging, so here's an example of how this can be
* done with provididing the scope manually.
*
* Info regarding authorization and requests can be found here:
* https://firebase.google.com/docs/cloud-messaging/server
*/
require 'vendor/autoload.php';
$client = new Google_Client();
// Authentication with the GOOGLE_APPLICATION_CREDENTIALS environment variable
$client->useApplicationDefaultCredentials();
// Alternatively, provide the JSON authentication file directly.
$client->setAuthConfig(__DIR__.'/auth.json');
// Add the scope as a string (multiple scopes can be provided as an array)
$client->addScope('https://www.googleapis.com/auth/firebase.messaging');
// Returns an instance of GuzzleHttp\Client that authenticates with the Google API.
$httpClient = $client->authorize();
// Your Firebase project ID
$project = "myproject-4e6ed";
// Creates a notification for subscribers to the debug topic
$message = [
"message" => [
"topic" => "debug",
"notification" => [
"body" => "This is an FCM notification message!",
"title" => "FCM Message",
]
]
];
// Send the Push Notification - use $response to inspect success or errors
$response = $httpClient->post("https://fcm.googleapis.com/v1/projects/{$project}/messages:send", ['json' => $message]);
@nayzawoo
Copy link

Thanks

@mgerasimchuk
Copy link

Thank you..!!! it help me a lot to!!!

@nyufeng
Copy link

nyufeng commented Sep 19, 2018

Thanks.

@3ffusi0on
Copy link

The $project variable used in the url https://fcm.googleapis.com/v1/projects/{$project}/messages:send should be the one defined in the .json f file for project_id key. I had trouble using the project_id defined on firebase page.

@jsancheztak
Copy link

I have been trying to send push notifications. Your code works, but I having problems sending notification to one device.

My code

    $token = "fFIF0lT6mEs:APA91bGpCdSXzjX....h3JDyDp"; //Token generated in app
    $title = "FCM Message";
    $body = "This is an FCM notification message!";

    $client = new Google_Client();

    // Set auth config file
    $client->setAuthConfig($json_file_path);
    $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
    // Returns an instance of GuzzleHttp\Client that authenticates with the Google API.
    $httpClient = $client->authorize();

    // Your Firebase project ID
    $project = 'my_project_id';

    // Creates a notification for subscribers to the debug topic
    $message = [
        "message" => [
            // Send with token is not working, but works without it
            "token" => $token,
            "topic" => "debug",
            "notification" => [
                "body" => $body,
                "title" => $title,
            ]
        ]
    ];

    // Send the Push Notification - use $response to inspect success or errors
    $response = $httpClient->post("https://fcm.googleapis.com/v1/projects/$project/messages:send", ['json' => $message]);
    dump($response);

This code always returns reasonPhrase: "Bad Request" with statusCode: 400

Am i missing something? Thanks!

@jsancheztak
Copy link

Sorry, after lots of tests I have change the message al follows:

    // Creates a notification for subscribers to the debug topic
    $message = [
        "message" => [
            //"topic" => "debug", // Send to topic or token are incompatibles
            "notification" => [
                "body" => $body,
                "title" => $title,
            ],
            // Send with token is not working
            "token" => $token,
        ]
    ];

Thanks a lot!

@KiyokGU
Copy link

KiyokGU commented Jan 31, 2019

Hi everybody, I'm trying this code but I get 403 Forbidden as response!
Could you help me to understand what I'm doing wrong!

Thanks, Martin

@sakilimran
Copy link

sakilimran commented Apr 9, 2019

Getting the following error response. Is there any permission issue for service account? @Repox

{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}

@kbsali
Copy link

kbsali commented Apr 11, 2019

thanks for the good hint!

@hristo-atanasov
Copy link

Is this code still working? I don't know why but I constantly get error 401 Unautorized .. :|

@zingmeup
Copy link

zingmeup commented Jun 19, 2019

This was helpful.
Download and install composer then use windows powershell to use composer.
composer require google/apiclient:"^2.0"

Make sure to use your service account json file which contains the private key.
From your filebase console->settings->service account

There is an issue with the guzzle
ErrorException/app/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php

The solution:
#replace this
if (count($this->handles) >= $this->maxHandles)
#with this
if ( $this->handles != null && count($this->handles) >= $this->maxHandles )

in the file on line 67, and everything works like a charm.

@su1736
Copy link

su1736 commented Aug 17, 2019

Thanks a lot!
I was trying to do it with GoogleApi docs but google documentation sometimes so quirky.. )

@ekohadim
Copy link

ekohadim commented Nov 8, 2019

Thanks! It works. But i have issues to send message to web app running on Firefox and Edge. Send to chrome is fine. Any one have any clue?

@davists
Copy link

davists commented Nov 13, 2019

Thank you.. it help me a lot. =)

@akshaywo
Copy link

How to use multiple device tokens here?

@Repox
Copy link
Author

Repox commented Sep 3, 2020

How to use multiple device tokens here?

Hey @akshaywo

The solution proposed in this Gist is a couple of years old, I wouldn't recommend this approach anymore.

The package from krait called firebase-php is what I would recommend these days as this package easily solves what you need, also sending to multiple device tokens.

Quick and easy implementation too:

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;

$factory = (new Factory)->withServiceAccount(base_path('service_account_credentials.json')); // or use auto-loading of credentials

$messaging = $factory->createMessaging();

$message = CloudMessage::withTarget('topic', 'debug')
                ->withNotification(Notification::create('Notification title', 'This is an FCM notification message!'));

$messaging->send($message);

@akshaywo
Copy link

akshaywo commented Sep 4, 2020

Thank you so much for your reply! It helps a lot.

@Jean-Kenned
Copy link

Thanks a lot! Very helpful !

@mohammed-almubarak
Copy link

Thanks a lot, @Repox! I've been looking for something similar without any luck. You nailed it.

@BenLaKnet
Copy link

BenLaKnet commented Aug 4, 2023

Hi @Repox ,

Thanks for your code, what is the json file ?

I tried your code in a function but nothing is returned.

`function notifPushEnvoi ($regid, $title, $body, $id) {

require 'vendor/autoload.php';

$client = new Google_Client();

$client->useApplicationDefaultCredentials(); 

$client->setAuthConfig('mon.json');

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

$httpClient = $client->authorize();

$project = "monprojet";

// Creates a notification for subscribers to the debug topic
$message = [
	"message" => [
		"token" => $regid,
		//"topic" => "debug",
		"notification" => [
			"body" => $body,
			"title" => $title
		]
	]
];

// Send the Push Notification - use $response to inspect success or errors
$response = $httpClient->post("https://fcm.googleapis.com/v1/projects/$project/messages:send", ['json' => $message]);
	
return (json_encode($response));`

@Repox
Copy link
Author

Repox commented Aug 4, 2023

Hi @BenLaKnet

Thanks for your code, what is the json file ?

Tje JSON file is a file containing your credentials for the service account.

You can read more from Google's official documentation on that topic. How to create and download the JSON credentials file.

I tried your code in a function but nothing is returned.

I see you tried my original Gist; it no longer works. You should try and look at the updated example I made three years ago, which still works:

https://gist.github.com/Repox/64ac4b3582f8ac42a6a1b41667db7440?permalink_comment_id=3440955#gistcomment-3440955

@BenLaKnet
Copy link

@Repox , I am on a share hosting, how could I install firebase-php ? or how I can use "use" in your example ?
Many thanks

@Repox
Copy link
Author

Repox commented Aug 5, 2023

@BenLaKnet , you can install it locally with composer or download the zip package from the repository. After that, upload it to your shared hosting, like you normally would.

@BenLaKnet
Copy link

BenLaKnet commented Aug 6, 2023

@Repox ,
So sorry, but I can not understand where scripts firebase-php are included, with use ? or namespace or other ?
May I declarde a variable in shared hosting ?

I am using v6.9.6 with php 7.4 on my shared hosting.

require_once "common.php";

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;


function notifPushEnvoi_FirebaseAPI ($regid, $title, $body, $id) {
	
	$factory = (new Factory)->withServiceAccount(base_path('*****.json')); // or use auto-loading of credentials

	$messaging = $factory->createMessaging();

	$message = CloudMessage::withTarget('topic', 'debug')
					->withNotification(Notification::create('Notification title', 'This is an FCM notification message!'));

	$messaging->send($message);
	
	return (true);
	
}

Uncaught Error: Class 'Kreait\Firebase\Factory' not found in //testsnotifs.php:16 Stack trace: #0 //testsnotifs.php(91): notifPushEnvoi_FirebaseAPI('d7-so8quEvo:APA...', 'Alors...', 'Goooooo', 1) #1 {main} thrown in /****/testsnotifs.php on line 16

Ok, so sorry, I understood why using composer.

Many thanks.

@BenLaKnet
Copy link

BenLaKnet commented Aug 7, 2023

@Repox ,

I used Composer to install locally, but with PHP 8.2
My shared hosting is PHP 7.4, I can not migrate at this time, because I encounteer an error 500.

How is it possible to download locally firebase-php with PHP 7.4 ?

I install a virtual machine with PHP 7.4 locally to obtain firebase-php 6.9.6 and now:

composer require "kreait/firebase-php:6.9.6"

PHP Fatal error:  Uncaught Error: Call to undefined function Symfony\Component\Console\str_contains() in /usr/share/php/Symfony/Component/Console/Application.php:860
Stack trace:
#0 /usr/share/php/Symfony/Component/Console/Application.php(840): Symfony\Component\Console\Application->doRenderThrowable()
#1 /usr/share/php/Symfony/Component/Console/Application.php(154): Symfony\Component\Console\Application->renderThrowable()
#2 [internal function]: Symfony\Component\Console\Application->Symfony\Component\Console\{closure}()
#3 {main}
  thrown in /usr/share/php/Symfony/Component/Console/Application.php on line 860

@BenLaKnet
Copy link

@Repox ,

Finally, I migrated PHP8.2, reinstall with composer and it is running.

Many thanks.

@drussdev
Copy link

drussdev commented May 30, 2024

Hello, Im using the service-account settings. However, I still get the error SENDER_ID_MISMATCH. Can someone help me?

@abhishekpwo
Copy link

@drussdev

The SENDER_ID_MISMATCH error typically occurs when the Firebase Cloud Messaging (FCM) request is sent with a token that doesn't match the sender ID associated with the service account credentials being used. Here’s a step-by-step example of how to correctly set up and use the Google API PHP Client for Firebase Cloud Messaging Service v1, ensuring you avoid this error:

Key Points to Ensure

  1. Service Account JSON File: Make sure the path to the service account JSON file is correct.
  2. Firebase Project ID: Ensure that the project ID matches the one in your Firebase project settings.
  3. Device Token: Verify that the device token is valid and corresponds to the correct Firebase project.

Troubleshooting SENDER_ID_MISMATCH

  • Token Validity: Ensure that the token you are using is from the same Firebase project associated with the service account credentials.
  • Correct Project ID: Double-check that the firebaseProjectId in the script matches the project ID from the Firebase Console.
  • Scope and Permissions: Ensure that the service account has the necessary permissions to send FCM messages. The scope used in the script (https://www.googleapis.com/auth/firebase.messaging) should be correct.

If you've verified all these points and still encounter the issue, it's possible that the token has expired or is invalid. In such cases, try generating a new device token and test again.

@drussdev
Copy link

@abhishekpwo , Key Points to Ensure::3 is my reason. Thank you.

@abhishekpwo
Copy link

Great! Welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment