Home » Android » php – How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

php – How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

Posted by: admin March 10, 2020 Leave a comment


I’m starting with the new Google service for the notifications, Firebase Cloud Messaging.

Thanks to this code https://github.com/firebase/quickstart-android/tree/master/messaging I was able to send notifications from my Firebase User Console to my Android device.

Is there any API or way to send a notification without use the Firebase console? I mean, for example, a PHP API or something like that, to create notifications from my own server directly.

How to&Answers:

Firebase Cloud Messaging has a server-side APIs that you can call to send messages. See https://firebase.google.com/docs/cloud-messaging/server.

Sending a message can be as simple as using curl to call a HTTP end-point. See https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol

curl -X POST --header "Authorization: key=<API_ACCESS_KEY>" \
    --Header "Content-Type: application/json" \
    https://fcm.googleapis.com/fcm/send \
    -d "{\"to\":\"<YOUR_DEVICE_ID_TOKEN>\",\"notification\":{\"body\":\"Yellow\"},\"priority\":10}"


This works using CURL

function sendGCM($message, $id) {

    $url = 'https://fcm.googleapis.com/fcm/send';

    $fields = array (
            'registration_ids' => array (
            'data' => array (
                    "message" => $message
    $fields = json_encode ( $fields );

    $headers = array (
            'Authorization: key=' . "YOUR_KEY_HERE",
            'Content-Type: application/json'

    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_POST, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

    $result = curl_exec ( $ch );
    echo $result;
    curl_close ( $ch );


$message is your message to send to the device

$id is the devices registration token

YOUR_KEY_HERE is your Server API Key (or Legacy Server API Key)


Use a service api.

URL: https://fcm.googleapis.com/fcm/send

Method Type: POST


Content-Type: application/json
Authorization: key=your api key


{ "notification": {
    "title": "Your Title",
    "text": "Your Text",
     "click_action": "OPEN_ACTIVITY_1" // should match to your intent filter
    "data": {
    "keyname": "any value " //you can get this data as extras in your activity and this data is optional
  "to" : "to_id(firebase refreshedToken)"

And with this in your app you can add below code in your activity to be called:

    <action android:name="OPEN_ACTIVITY_1" />
    <category android:name="android.intent.category.DEFAULT" />

Also check the answer on Firebase onMessageReceived not called when app in background


Examples using curl

Send messages to specific devices

To send messages to specific devices, set the to the registration token for the specific app instance

curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>"  -X POST -d '{ "data": { "score": "5x1","time": "15:10"},"to" : "<registration token>"}' https://fcm.googleapis.com/fcm/send

Send messages to topics

here the topic is : /topics/foo-bar

curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>"  -X POST -d '{ "to": "/topics/foo-bar","data": { "message": "This is a Firebase Cloud Messaging Topic Message!"}}' https://fcm.googleapis.com/fcm/send

Send messages to device groups

Sending messages to a device group is very similar to sending messages to an individual device. Set the to parameter to the unique notification key for the device group

curl -H "Content-type: application/json" -H "Authorization:key=<Your Api key>"  -X POST -d '{"to": "<aUniqueKey>","data": {"hello": "This is a Firebase Cloud Messaging Device Group Message!"}}' https://fcm.googleapis.com/fcm/send

Examples using Service API

API URL : https://fcm.googleapis.com/fcm/send


Content-type: application/json
Authorization:key=<Your Api key>

Request Method : POST

Request Body

Messages to specific devices

  "data": {
    "score": "5x1",
    "time": "15:10"
  "to": "<registration token>"

Messages to topics

  "to": "/topics/foo-bar",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!"

Messages to device groups

  "to": "<aUniqueKey>",
  "data": {
    "hello": "This is a Firebase Cloud Messaging Device Group Message!"


As mentioned by Frank, you can use Firebase Cloud Messaging (FCM) HTTP API to trigger push notification from your own back-end. But you won’t be able to

  1. send notifications to a Firebase User Identifier (UID) and
  2. send notifications to user segments (targeting properties & events like you can on the user console).

Meaning: you’ll have to store FCM/GCM registration ids (push tokens) yourself or use FCM topics to subscribe users. Keep also in mind that FCM is not an API for Firebase Notifications, it’s a lower-level API without scheduling or open-rate analytics. Firebase Notifications is build on top on FCM.


First you need to get a token from android and then you can call this php code and you can even send data for further actions in your app.


// Call .php?Action=M&t=title&m=message&r=token

switch ($action) {
    Case "M":

        $j=json_decode(notify($r, $t, $m));



        print "Success: " . $succ . "<br>";
        print "Fail   : " . $fail . "<br>";


        print json_encode ("Error: Function not defined ->" . $action);

function notify ($r, $t, $m)
    // API access key from Google API's Console
        if (!defined('API_ACCESS_KEY')) define( 'API_ACCESS_KEY', 'Insert here' );
        $tokenarray = array($r);
        // prep the bundle
        $msg = array
            'title'     => $t,
            'message'     => $m,
           'MyKey1'       => 'MyData1',
            'MyKey2'       => 'MyData2', 

        $fields = array
            'registration_ids'     => $tokenarray,
            'data'            => $msg

        $headers = array
            'Authorization: key=' . API_ACCESS_KEY,
            'Content-Type: application/json'

        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        curl_close( $ch );
        return $result;



You can use for example a PHP script for Google Cloud Messaging (GCM). Firebase, and its console, is just on top of GCM.

I found this one on github:

Hint: This PHP script results in a android notification.

Therefore: Read this answer from Koot if you want to receive and show the notification in Android.


Notification or data message can be sent to firebase base cloud messaging server using FCM HTTP v1 API endpoint.

You need to generate and download private key of service account using Firebase console and generate access key using google api client library. Use any http library to post message to above end point, below code shows posting message using OkHTTP. You can find complete server side and client side code at firebase cloud messaging and sending messages to multiple clients using fcm topic example

If a specific client message needs to sent, you need to get firebase registration key of the client, see sending client or device specific messages to FCM server example

String SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
     = "https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send";

GoogleCredential googleCredential = GoogleCredential
    .fromStream(new FileInputStream("firebase-private-key.json"))
String token = googleCredential.getAccessToken();

final MediaType mediaType = MediaType.parse("application/json");

OkHttpClient httpClient = new OkHttpClient();

Request request = new Request.Builder()
    .addHeader("Content-Type", "application/json; UTF-8")
    .addHeader("Authorization", "Bearer " + token)
    .post(RequestBody.create(mediaType, jsonMessage))

Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
    log.info("Message sent to FCM server");


If you want to send push notifications from android check out my blog post

Send Push Notifications from 1 android phone to another with out server.

sending push notification is nothing but a post request to https://fcm.googleapis.com/fcm/send

code snippet using volley:

    JSONObject json = new JSONObject();
 try {
 JSONObject userData=new JSONObject();
 userData.put("title","your title");
 userData.put("body","your body");

json.put("to", receiverFirebaseToken);
 catch (JSONException e) {

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", json, new Response.Listener<JSONObject>() {
 public void onResponse(JSONObject response) {

Log.i("onResponse", "" + response.toString());
 }, new Response.ErrorListener() {
 public void onErrorResponse(VolleyError error) {

 }) {
 public Map<String, String> getHeaders() throws AuthFailureError {

Map<String, String> params = new HashMap<String, String>();
 params.put("Authorizationey=" + SERVER_API_KEY);
 return params;

I suggest you all to check out my blog post for complete details.


Using Firebase Console you can send message to all users based on application package.But with CURL or PHP API its not possible.

Through API You can send notification to specific device ID or subscribed users to selected topic or subscribed topic users.

Get a view on following link. It will help you.


Or you can use Firebase cloud functions, which is for me the easier way to implement your push notifications.


If you’re using PHP, I recommend using the PHP SDK for Firebase: Firebase Admin SDK. For an easy configuration you can follow these steps:

Get the project credentials json file from Firebase (Initialize the sdk) and include it in your project.

Install the SDK in your project. I use composer:

composer require kreait/firebase-php ^4.35

Try any example from the Cloud Messaging session in the SDK documentation:

use Kreait\Firebase;
use Kreait\Firebase\Messaging\CloudMessage;

$messaging = (new Firebase\Factory())

$message = CloudMessage::withTarget(/* see sections below */)
    ->withNotification(Notification::create('Title', 'Body'))
    ->withData(['key' => 'value']);