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

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.

This question is related to php android api firebase firebase-cloud-messaging

The answer is


Go to cloud Messaging select:  Server key



function sendGCM($message, $deviceToken) {

    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array (
            'registration_ids' => array (
                $id
            ),
            'data' => array (
                "title" =>  "Notification title",
                "body" =>  $message,
            )
    );
    $fields = json_encode ( $fields );
    $headers = array (
        'Authorization: key=' . "YOUR_SERVER_KEY",
        '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);
}

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())
->withServiceAccount('/path/to/firebase_credentials.json')
->createMessaging();

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

$messaging->send($message);

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.

 <?php

// Call .php?Action=M&t=title&m=message&r=token
$action=$_GET["Action"];


switch ($action) {
    Case "M":
         $r=$_GET["r"];
        $t=$_GET["t"];
        $m=$_GET["m"];

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

        $succ=0;
        $fail=0;

        $succ=$j->{'success'};
        $fail=$j->{'failure'};

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

        break;


default:
        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;
    }


?>

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


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.


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("data",userData);
json.put("to", receiverFirebaseToken);
 }
 catch (JSONException e) {
 e.printStackTrace();
 }

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

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

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

Map<String, String> params = new HashMap<String, String>();
 params.put("Authorizationey=" + SERVER_API_KEY);
 params.put("Content-Typepplication/json");
 return params;
 }
 };
 MySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);

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


Use a service api.

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

Method Type: POST

Headers:

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

Body/Payload:

{ "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:

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

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


this solution from this link helped me a lot. you can check it out.

The curl.php file with those line of instruction can work.

<?php 
// Server key from Firebase Console define( 'API_ACCESS_KEY', 'AAAA----FE6F' );
$data = array("to" => "cNf2---6Vs9", "notification" => array( "title" => "Shareurcodes.com", "body" => "A Code Sharing Blog!","icon" => "icon.png", "click_action" => "http://shareurcodes.com"));
$data_string = json_encode($data);
echo "The Json Data : ".$data_string;
$headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' );
$ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://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_POSTFIELDS, $data_string);
$result = curl_exec($ch);
curl_close ($ch);
echo "<p>&nbsp;</p>";
echo "The Result : ".$result;

Remember you need to execute curl.php file using another browser ie not from the browser that is used to get the user token. You can see notification only if you are browsing another website.


Works in 2020

$response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization'=> 'key='. $token,
        ])->post($url, [
            'notification' => [
                'body' => $request->summary,
                'title' => $request->title,
                'image' => 'http://'.request()->getHttpHost().$path,
                
            ],
            'priority'=> 'high',
            'data' => [
                'click_action'=> 'FLUTTER_NOTIFICATION_CLICK',
                
                'status'=> 'done',
                
            ],
            'to' => '/topics/all'
        ]);

Here is the working code in my project using CURL.

<?PHP

// API access key from Google API's Console
( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );


 $registrationIds = array( $_GET['id'] );

  // prep the bundle
 $msg = array
 (
   'message'    => 'here is a message. message',
    'title'     => 'This is a title. title',
    'subtitle'  => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1,
    'largeIcon' => 'large_icon',
    'smallIcon' => 'small_icon'
 );

 $fields = array
 (
    // use this to method if want to send to topics
    // 'to' => 'topics/all'
    'registration_ids'  => $registrationIds,
     'data'         => $msg
 );

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

 $ch = curl_init();
 curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/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 );

 echo $result;

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

Headers

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!"
  }
}

Notification or data message can be sent to firebase base cloud messaging server using FCM HTTP v1 API endpoint. https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send.

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";
String FCM_ENDPOINT
     = "https://fcm.googleapis.com/v1/projects/zoftino-stores/messages:send";

GoogleCredential googleCredential = GoogleCredential
    .fromStream(new FileInputStream("firebase-private-key.json"))
    .createScoped(Arrays.asList(SCOPE));
googleCredential.refreshToken();
String token = googleCredential.getAccessToken();



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

OkHttpClient httpClient = new OkHttpClient();

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


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

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: https://gist.github.com/prime31/5675017

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.


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.
https://firebase.google.com/docs/cloud-messaging/send-message

This works using CURL

function sendGCM($message, $id) {


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

    $fields = array (
            'registration_ids' => array (
                    $id
            ),
            '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)


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to api

I am receiving warning in Facebook Application using PHP SDK Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Failed to load resource: the server responded with a status of 404 (Not Found) css Call another rest api from my server in Spring-Boot How to send custom headers with requests in Swagger UI? This page didn't load Google Maps correctly. See the JavaScript console for technical details How can I send a Firebase Cloud Messaging notification without use the Firebase Console? Allow Access-Control-Allow-Origin header using HTML5 fetch API How to send an HTTP request with a header parameter? Laravel 5.1 API Enable Cors

Examples related to firebase

How can I solve the error 'TS2532: Object is possibly 'undefined'? Getting all documents from one collection in Firestore FirebaseInstanceIdService is deprecated Failed to resolve: com.google.firebase:firebase-core:16.0.1 NullInjectorError: No provider for AngularFirestore Firestore Getting documents id from collection How to update an "array of objects" with Firestore? firestore: PERMISSION_DENIED: Missing or insufficient permissions Cloud Firestore collection count iOS Swift - Get the Current Local Time and Date Timestamp

Examples related to firebase-cloud-messaging

FirebaseInstanceIdService is deprecated Error: fix the version conflict (google-services plugin) How do you send a Firebase Notification to all devices via CURL? No notification sound when sending notification from firebase in android FCM getting MismatchSenderId Firebase (FCM) how to get token How to handle notification when app in background in Firebase What is FCM token in Firebase? Firebase FCM force onTokenRefresh() to be called Send push to Android by C# using FCM (Firebase Cloud Messaging)