Firebase Cloud Messaging (FCM) Server Side Implementation. (FCM PHP Backend)

In my last post I wrote about FCM Setup in Android, in this post I includes the server side (PHP) implementation to send message notification from the backend server to the Android device.

In this example I am not using all the properties of sending message from server. For a complete list of targets,options and payloads available to send message from server refer this link.

Here are some of the basic properties required to the send downstream messages.

  • to – Type String – (Optional) [Recipient of a message]
    The value must be a single registration token, notification key, or topic. Do not set this field when sending to multiple topics
  • registration_ids – Type String array – (Optional) [Recipients of a message]
    Multiple registration tokens, min 1 max 1000.
  • priority– Type String – (Optional) [ default normal]
    Allowed values normal and high.

    Normal priority optimizes the client app’s battery consumption and the app may receive the message with unspecified delay.

    High priority sends the message immediately, and the app can wake a sleeping device and open a network connection to the server.

  • delay_while_idle – Type boolean – (Optional) [default value false]
    true indicates that the message should not be sent until the device becomes active.
  • time_to_live – Type JSON number – (Optional) [default value 4 week maximum 4 week]
    This parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline
  • data – Type JSON Object
    Specifies the custom key-value pairs of the message’s payload.
    eg. {“post_id”:”1234″,”post_title”:”A Blog Post Title”}

    In Android you can receive it in onMessageReceived() as Map data…

We direct all the HTTP requests to https://fcm.googleapis.com/fcm/send.

OK Lets start coding… For easy implementation I created a function named sendMessage with two parameters data and target. here is the function.

Pass Array as the data parameter and pass String or Array as the target parameter. To send message to multiple ids use Array as the target parameter or use String if send to single id or a Topic. All other things are well commented in the function. Let me know if you have any trouble.

Note:
In the sendMessage function replace PASTE_YOUR_SERVER_KEY_HERE with your secret Server Key. To get the Server Key …

1. Go to Firebase Console
2. Select Your Project … then click on the gear icon next to project name and click on Project settings then move on to CLOUD MESSAGING tab.

fcm-server-key

 

sab99r

 

29 thoughts on “Firebase Cloud Messaging (FCM) Server Side Implementation. (FCM PHP Backend)

    1. For icon you can try the optional parameter ‘icon’. (Indicates notification icon. Set value to ‘myicon’ for drawable resource myicon.) In my first test it isn’t worked. If not working for you better notify in ‘onMessageReceived’ using custom code, in that case you can use any icon as you wish.

    1. Ok, I’ve figured out. I had syntax error in $data array.
      But still got a little problem, script does nothing (result is a blank page) because I don’t know where to get token to $target so my $target is empty.
      I’d like to send notification to all devices. I’ve implemented FCM into my android app as you explained in your previous tutorial.

      1. assign token you received in onTokenRefresh to the $target variable. You can use single or multiple tokens. in case of multiple token assign an index array to target.

  1. Hello sab,

    i have try this code, but my devices don’t receive notify/push 🙁

    If i send notify with Firebase Console i receive it, but with this script no.. why?

    Help me please :\

    P.s.: I have only change $fields array with —>

    $fields = array(
    ‘registration_ids’ => $target, //in this case $target is an array of tokens
    ‘priority’ => “high”,
    ‘notification’ => array (“title” => $title, “body” => $message,
    ‘data’ => array (“message” => $message, “image” => $img_url)
    );

    And on function parameters pass ($target, $title, $message, $img_url) where have set $img_url to “”.

    Is this my problem??

    1. May be you are missing something. I am using the same code in my recent projects and all works well…. echo the $result variable and check what it returns… also double check the $server_key.

      1. $server_key is right. I have try to echo $result and it print this error:

        {“multicast_id”:6782339717028231855,”success”:0,”failure”:1,
        “canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}

        But registration id that i pass to $target is right.. so how fix this error?

        Help me please 🙁

        1. The response InvalidRegistration indicates the registration id is wrong (The id you get from app)… Are you saving the registration id to database?

          1. Yes, i have registration ids into Database, but i have also control token that create method on app with token that i have into Database, and are equals..

            So, why ids are wrong?

  2. Do you know which is the best approach to manage the tokens on your server?
    1- How to know which are still valid in order to delete the ones that have been replaced? (My first guess was to send a “heart-beat” but the device can be off at that time).

    2- In relation to question 1, Is there any way you can ask the FCM server to invalidate a token and to generate a new one on the device (this ending up in a call to onTokenRefresh() on the device)?

  3. I have implemented your code but I’m not receiving any oush notifications.
    The $result value is {“multicast_id”:5824575693024907205,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1480970564006919%580ace7df9fd7ecd”}]} which I believe means that the code has worked correctly.

  4. I have same issue like others, I don’t get any notification in my device using PHP code, If I sent it through console then I got the notification.

    My result also display the success 1, Can anyone help me?
    My return result :-
    {“multicast_id”:7242260585078346109,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1482737395745118%9efa1f90f9fd7ecd”}]}

  5. my code was woking good but after i have change target id it gives “NotRegistered” as an error but i can receive message from firebase console please help

  6. I used same code and its working fine on development server but once i moved on live server(ssl enabled) its given error:
    Invalid (legacy) Server-key delivered or Sender is not authorized to perform request.
    Error 401

  7. Sometimes there is a delay in delivering message to client , I set priority: “high” but delay is between 10 min – 1 s .
    Why is the message not be delivered immediately?

Leave a Reply

Your email address will not be published. Required fields are marked *

four × 5 =