Android Tutorial [B4x]Send Firebase-Message via php

Discussion in 'Tutorials & Examples' started by KMatle, Jul 16, 2016.

  1. KMatle

    KMatle Expert Licensed User

    I use php for all my server stuff so here is an updated tutorial how to use php to send messages to devices.

    1. Follow Erel's instructions to set up Firebase Messaging and download the example.

    2. Add the log line to the example to see the device's token (you need to copy it later)

    Public Sub SubscribeToTopics
    "general"'you can subscribe to more topics
       Log (fm.Token)
    End Sub
    Inside the logs you'll see a long string (=token) like this:

    By subscribing every device will get a unique token which is used to send a message to THIS device.

    3. Copy the php script into an own folder (I've called mine "FCM") inside the htdocs folder of your php installation. I use XAMPP for my tests (no production server is needed). Change "API_ACCESS_KEY" to the one of your project (see Erel's tutorial).

    In the array

    $msg = array
    'title'     => $t,
                'message'     => $m,
                'MyKey1'       => 'MyData1',
                'MyKey2'       => 'MyData2',
    you can use key/value pairs like you want to. Add more if needed.



    switch ($action) {
    Case "M":
            $j=json_decode(notify($r, $t, $m));
    "Success: " . $succ . "<br>";
    "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', 'AIzasogs94sgjsjsg04......... );
            $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, '' );
            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;

    4. Start Erel's example (debug), set a breakpoint at "fm_MessageArrived", copy the token to the clipboard. Open your browser and call the php like this:

    Change the ip-address, too (can be a regular website when you use it in production)

    Insert the copied token after "r=" and your app will receive the message at once:

    Message arrived
    Message data: {MyKey1=MyData1, MyKey2=MyData2, title=Title, message=Message
    As you can see, our key/value pairs arrive as a map. To get the contents of "message":

    Dim mess As String = Message.GetData.Get("message")
    5. Improvements

    Just call the php via httputils to send a message.

    Usually you have more than one device and you do't know the tokens. So you need to store the token and some other unique identifier (email address/name/imei -> alias) into a database. So you can add to the script to store update the tokens. In another function you just call the script with the alias.

    In one of my apps I store all messages to a table to check the status (sent, received). After the message arrives on the device I call the php to update the status to "received".


    There is no security here. Don't use this example 1:1 on your production server(s)! (use Google to search for how to secure a php script/MySql).
    ronell, Paul Garcia, Mashiane and 7 others like this.
  2. chefe82

    chefe82 Member Licensed User


    Is it also possible to send to a Topic not token ?

    MAGAREY Member Licensed User

    just change :
     'registration_ids'     => $tokenarray,
         'to'       => "/topics/all",
    Daniel-White likes this.
  4. Daniel-White

    Daniel-White Active Member Licensed User

    To put to work the message:
    change ' message' to 'body'

    // prep the bundle
            $msg = 
    'title'     => $t,
                'body'     => $m,
              /*  'MyKey1'       => 'MyData1',
                'MyKey2'       => 'MyData2', */
            $fields = 
    'to'       => "/topics/your topic change here",
                'data'            => $msg
  5. tufanv

    tufanv Expert Licensed User


    1) is this example still working without problems ?
    2) is the fcm token changes everytime user launches the app or every device has one token id ?
  6. tufanv

    tufanv Expert Licensed User

    I found the answer the these questions. onlyh problem is message shows null alotugh i send the m paramter. There is no problem with the title. any idea @KMatle ?
  7. DonManfred

    DonManfred Expert Licensed User

    1. You should create a new thread for any Issue you have!
    2. Post the code you are using to send the Message. Also the code you are using to get the Data from the Message arrived.
    KMatle likes this.
  8. tufanv

    tufanv Expert Licensed User

    if anyone has this problem , you have to change message to "body" in the php.
    Erel likes this.
  9. KMatle

    KMatle Expert Licensed User

    @all: Google FCM offers different message types (yep, it really does). It is very important to know this because there are several scenarios how your app (exactly: How the FCM services behave/what your app does).

    Please take a look at the documentation:

    FCM uses keywords like DATA, BODY, TITLE. I use DATA messages only because one can have a list/map(s) with formatted data. With it you then need to set e.g. notifications on your own (which I prefer) without any automatic processing. There are several other keywords (see the docs).

    Notification messages

    Data messages

    tufanv and DonManfred like this.
  10. tufanv

    tufanv Expert Licensed User

    Thanks for detailed answers. I have one problem. I want to send to topic , I have changed the code as advised in this topic. But now

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

    seems not correct as we will not send it to a single token but a topic. What is the correct way to send to topic ?

  11. FrankDev

    FrankDev Active Member Licensed User

    Hi, I'm getting a bug with the php script

    Parse error: syntax error, unexpected 'title' (T_STRING) in /webspace/xxxxxxxxxxxxxx/firebase_message.php on line 38

    used as action times only Action = X

    Best regards
  12. KMatle

    KMatle Expert Licensed User

    Must be a typo (Sytax error). Please Check it. My scripts runs like a charm.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice