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

PhpAndroidFirebaseFirebase Cloud-Messaging

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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\":{\"title\":\"Hello\",\"body\":\"Yellow\"}}"

Solution 2 - Php

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)

Solution 3 - Php

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"
   },
   "data": {
      "<some_key>": "<some_value>"
   },
   "to": "<device_token>"
}

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 https://stackoverflow.com/questions/37358462/firebase-onmessagereceived-not-called-when-app-in-background/37599088#37599088

Solution 4 - Php

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

Solution 5 - Php

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.

Solution 6 - Php

Introduction

I compiled most of the answers above and updated the variables based on the FCM HTTP Connection Docs to curate a solution that works with FCM in 2021. Credit to Hamzah Malik for his very insightful answer above.

Prerequisites

First, ensure that you have connected your project with Firebase and that you have set up all dependencies on your app. If you haven't, first head over to the FCM Config docs

If that is done, you will also need to copy your project's server response key from the API. Head over to your Firebase Console, click on the project you're working on and then navigate to;

Project Settings(Setting wheel on upper left corner) -> Cloud Messaging Tab -> Copy the Server key

Configuring your PHP Backend

I compiled Hamzah's answer with Ankit Adlakha's API call structure and the FCM Docs to come up with the PHP function below:

function sendGCM() {
  // FCM API Url
  $url = 'https://fcm.googleapis.com/fcm/send';

  // Put your Server Response Key here
  $apiKey = "YOUR SERVER RESPONSE KEY HERE";

  // Compile headers in one variable
  $headers = array (
    'Authorization:key=' . $apiKey,
    'Content-Type:application/json'
  );

  // Add notification content to a variable for easy reference
  $notifData = [
    'title' => "Test Title",
    'body' => "Test notification body",
    'click_action' => "android.intent.action.MAIN"
  ];

  // Create the api body
  $apiBody = [
    'notification' => $notifData,
    'data' => $notifData,
    "time_to_live" => "600" // Optional
    'to' => '/topics/mytargettopic' // Replace 'mytargettopic' with your intended notification audience
  ];

  // Initialize curl with the prepared headers and body
  $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, json_encode($apiBody));

  // Execute call and save result
  $result = curl_exec ( $ch );

  // Close curl after call
  curl_close ( $ch );

  return $result;
}

Customizing your notification push

To submit the notifications via tokens, use 'to' => 'registration token'

What to expect

I set up the function in my website back-end and tested it on Postman. If your configuration was successful, you should expect a response similar to the one below;

{"message":"{"message_id":3061657653031348530}"}

Solution 7 - Php

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.

Solution 8 - Php

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


?>

Solution 9 - Php

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.

Solution 10 - Php

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'
        ]);

Solution 11 - Php

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");
}

Solution 12 - Php

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);
}

Solution 13 - Php

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

Solution 14 - Php

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);

Solution 15 - Php

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;

Solution 16 - Php

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.

Solution 17 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid CorralView Question on Stackoverflow
Solution 1 - PhpFrank van PuffelenView Answer on Stackoverflow
Solution 2 - PhpHamzah MalikView Answer on Stackoverflow
Solution 3 - PhpAnkit AdlakhaView Answer on Stackoverflow
Solution 4 - PhpJ.RView Answer on Stackoverflow
Solution 5 - PhpAntoine GuénardView Answer on Stackoverflow
Solution 6 - PhpKenneth MurerwaView Answer on Stackoverflow
Solution 7 - PhpRuberandinda PatienceView Answer on Stackoverflow
Solution 8 - PhpSandi HorvatView Answer on Stackoverflow
Solution 9 - PhpP-ZenkerView Answer on Stackoverflow
Solution 10 - PhpJames Christian KaguoView Answer on Stackoverflow
Solution 11 - PhpArnav RaoView Answer on Stackoverflow
Solution 12 - PhpJulio filsView Answer on Stackoverflow
Solution 13 - PhpLaurent MaquetView Answer on Stackoverflow
Solution 14 - PhpJ.C. GrasView Answer on Stackoverflow
Solution 15 - PhpRaheel KhanView Answer on Stackoverflow
Solution 16 - PhpManoharView Answer on Stackoverflow
Solution 17 - PhpPRATEEK BHARDWAJView Answer on Stackoverflow