219

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.

Alexander Farber
  • 18,345
  • 68
  • 208
  • 375
David Corral
  • 3,364
  • 3
  • 24
  • 29
  • 1
    Where are you hosting your server to send notifications? – Rodrigo Ruiz Jun 02 '16 at 21:16
  • https://istudy.io/android-push-notifications-using-firebase-fcm/ – YasirSE Jul 25 '16 at 12:09
  • @David Corral, Check my answer for same. http://stackoverflow.com/a/38992689/2122328 – Sandeep_Devhare Aug 17 '16 at 12:11
  • Have written a spring app to send FCM notifications incase you wish to see how it works -> https://github.com/aniket91/WebDynamo/blob/master/src/com/osfg/controllers/FCMSender.java – Aniket Thakur Dec 03 '16 at 09:57
  • You can use retrofit to mesage davice to device. http://stackoverflow.com/questions/37435750/how-to-send-device-to-device-messages-using-firebase-cloud-messaging/41913555#41913555 – eurosecom Jan 28 '17 at 19:45
  • Read this blogpost for more details http://developine.com/how-to-send-firebase-push-notifications-from-app-server-tutorial/ – Developine Nov 11 '17 at 15:36
  • @David I have created a chat application in which when a user sends a message to receiver the receiver should get a notification message. In this case how can I use your answer? So what should I have to give the value for the field " to " ? – Arj 1411 Jan 16 '18 at 06:41
  • You can view bellow link. It has Spring java implementation https://stackoverflow.com/a/51172021/3073945 – Md. Sajedul Karim Jul 29 '18 at 05:01

17 Answers17

238

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\"}}"
Frank van Puffelen
  • 418,229
  • 62
  • 649
  • 645
  • 4
    How can I get the device id on iOS? Is it the device token we get on *didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData* or the long one we get with *FIRInstanceID.instanceID().token()* ? – FelipeOliveira May 26 '16 at 13:33
  • 3
    Frank I followed the guide at firebase docs and codelabs for adding push notifications on a progressive webapp and using POstman to post a http request, yet i keep getting 401 error. ANy suggestions. I'm copying my server key directly from my firebase console. – jasan May 26 '16 at 19:58
  • 32
    how to send to all users rather than a particular users or topics? – vinbhai4u Aug 09 '16 at 06:48
  • 3
    I got this error message back in one of my early tries with the CURL snippet: Field "priority" must be a JSON number: 10. After I removed the quotation marks from the 10 at the end, it worked. – albert c braun Sep 29 '16 at 19:11
  • 2
    @vinbhai4u Do you get the answer? I am also stuck at that. How to send that to all application users? – Rohit Oct 18 '16 at 19:47
  • @jasan - Did you find the answer for when using Postman? I'm stuck at the same place with a 401 error. I'm providing the correct Headers as far as I know. Thanks – user1203605 Nov 06 '16 at 23:52
  • 1
    @user1203605 I used this guide https://firebase.google.com/docs/cloud-messaging/js/client to add FCM to my webapp. and then used this https://firebase.google.com/docs/cloud-messaging/send-message to send the message through server or Postman and it works – jasan Nov 07 '16 at 07:30
  • @jasan - Thanks for your help, I've got it working. I also found that for Postman, when you enter the Key/Value pair, it expects Authorization in the Key and the Key/Value pair in the Value e.g. key=AIzaSyCFF...nNhHHz. (just in case anyone else turns up here with the same issue). – user1203605 Nov 07 '16 at 21:26
  • @jasan Thanks for the links. Do I really need to import the firebase js files just to be able to send push notifications? Like others I also am stuck at 401 errors... – Spock Nov 22 '16 at 08:36
  • @Spock you dont need to import anything other than your FCM Server Token(Server Key is being depreciated) , found in firebase console in order to send FCM messages. I think you are referring to the the following imports, maybe: `importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js')` then the answer is Yes. Those imports are needed in the service worker file , in order to handle FCm in foreground/background. – jasan Nov 22 '16 at 10:34
  • @jasan thank you.. I just find it so weird, because the Web Push protocol is not provider dependend, and should work with all browsers that support the protocol.. I'm super confused, because I hear different things all the time, while the implementation details in the browsers and endpoints change nonstop. I really don't want to import vendor-specific stuff into my service worker code :( – Spock Nov 22 '16 at 13:06
  • how can i send a notification without using the console and also without using php i mean just android , for exemple in my case when user like photo of his friend the other user recive a notification fi the app closed or in background ? – Amine Harbaoui Dec 13 '16 at 08:35
  • There is no way to directly send messages from one Android device to another Android device. See http://stackoverflow.com/questions/37435750/how-to-send-device-to-device-messages-using-firebase-cloud-messaging, http://stackoverflow.com/questions/38432243/how-to-send-device-to-device-notification-by-using-fcm-without-using-xmpp-or-any or one of the others in this page: https://www.google.com/search?q=site:stackoverflow.com+firebase+device+to+device – Frank van Puffelen Dec 13 '16 at 23:22
  • @vinbhai4u you can loop through a set of device tokens and send push notifications to each individual device token. For example, if you have an array of device tokens, just loop through each index and send a push notification to the device token at that index. – Anish Muthali Jun 07 '17 at 02:44
  • Read this blog post for more complete guide. http://developine.com/how-to-send-firebase-push-notifications-from-app-server-tutorial/ – Developine Nov 14 '17 at 07:08
  • Sir, can this be used to send all the devices and web browsers? – Dushyant Joshi Jan 13 '18 at 17:51
  • @FrankvanPuffelen, Hi I have created a chat application in which when a user sends a message to receiver the receiver should get a notification message. In this case how can I use your answer? So what should I have to give the value for the field " to " ? – Arj 1411 Jan 16 '18 at 06:40
  • what is thsi -> YOUR_DEVICE_ID_TOKEN – Alberto Acuña Jul 10 '18 at 21:35
  • 3
    @vinbhai4u for send to all users, is needed to subscribe theme to 'all' topic. and so send to '/topics/all' – roghayeh hosseini Jan 19 '20 at 10:04
60

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)

AO_
  • 1,964
  • 1
  • 23
  • 30
Hamzah Malik
  • 2,310
  • 3
  • 23
  • 41
  • Firebase Console have no save push messaging data into https://fcm.googleapis.com/fcm/send? – Mahmudul Haque Khan Sep 17 '16 at 07:39
  • 1
    to send push notification to browser from where i can get device registration id ? – Amit Joshi Jun 04 '19 at 03:08
  • this works perfectly but, because of the long text I am getting `{"multicast_id":3694931298664346108,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MessageTooBig"}]}`. What can be done to fix this? – Alisha Lamichhane Oct 22 '19 at 14:11
  • @AlishaLamichhane Is your message bigger than 4096 bytes? If not you can base64 encode your message (there might be something wrong with the text). If it is bigger than 4096 bytes... well, that's the FCM limit. – Rik Oct 22 '19 at 15:14
  • `to` replaces `registration_ids` – Yohanes AI Mar 25 '21 at 08:35
53

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

AO_
  • 1,964
  • 1
  • 23
  • 30
Ankit Adlakha
  • 1,228
  • 9
  • 14
  • Ankit, I can send to specific device id. However, I can't send to all. What I've to put `"to" : "to_id(firebase refreshedToken)"` instead of device id? `"all"` is not working at all. I'm using C# `WebRequest` to send notification. @AshikurRahman your suggestion also welcome. I'm struggling and searching since 3-4 days. – Ravimallya Feb 13 '17 at 17:04
  • 4
    Nevermind. I found the solution. to : "/topics/all" will send notifications to all devices or if you want to target only IOS replace all with ios and for android, replace with `android'. These are the default topics set. I guess. – Ravimallya Feb 14 '17 at 04:44
  • http://developine.com/how-to-send-firebase-push-notifications-from-app-server-tutorial/ – Developine Nov 11 '17 at 15:36
  • Read this blogpost for more details - > http://developine.com/how-to-send-firebase-push-notifications-from-app-server-tutorial/ – Developine Nov 11 '17 at 15:39
  • @Ankit, Hi, could you please specify how to get the target device's id? – Arj 1411 Jan 16 '18 at 06:37
  • @AnandRaj https://stackoverflow.com/questions/37787373/firebase-fcm-how-to-get-token You can get the token and save in your storage(Database) on server. – Ankit Adlakha May 25 '20 at 12:40
45

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!"
  }
}
J.R
  • 1,985
  • 16
  • 20
  • Where did you find the endpoint url https://fcm.googleapis.com/fcm/send , its no wherw mentioned in firebase doc? – Utsav Gupta Dec 08 '16 at 07:37
  • 1
    You can find that in this link https://firebase.google.com/docs/cloud-messaging/server – J.R Dec 08 '16 at 13:02
  • @J.R. I have created a chat application in which when a user sends a message to receiver the receiver should get a notification message. In this case how can I use your answer? So what should I have to give the value for the field " to " ? – Arj 1411 Jan 16 '18 at 06:39
  • @ Anad Raj refer "Send messages to specific devices" in my answer – J.R Jan 16 '18 at 07:16
25

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.

Frank van Puffelen
  • 418,229
  • 62
  • 649
  • 645
Antoine Guénard
  • 472
  • 4
  • 11
6

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


?>
Sandi Horvat
  • 397
  • 1
  • 4
  • 12
5

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.

Ruberandinda Patience
  • 2,075
  • 2
  • 13
  • 16
3

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.

Community
  • 1
  • 1
P-Zenker
  • 361
  • 2
  • 10
3

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

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");
}
Arnav Rao
  • 5,423
  • 1
  • 29
  • 29
2
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);
}
Julio fils
  • 41
  • 3
1

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}"}
xwaxes
  • 188
  • 6
0

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.

Manohar Reddy
  • 15,894
  • 7
  • 77
  • 109
0

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
PRATEEK BHARDWAJ
  • 2,100
  • 2
  • 21
  • 34
0

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

Laurent Maquet
  • 320
  • 2
  • 14
0

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);
J.C. Gras
  • 3,419
  • 28
  • 32
0

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;
Raheel Khan
  • 384
  • 7
  • 11
  • define is missing in API_ACCESS_KEY line . Also google cloud messaging old url is deprecated use https://fcm.googleapis.com/fcm/send – sreekanth balu Apr 25 '21 at 18:21