Search code examples
phpjqueryfirebasefirebase-cloud-messagingfirebase-notifications

How can I confirm that firebase notification was actually sent (fcm)?


I allow users to send notifications out through my website. The notifications are working, however, I would like a way to actually confirm if the notification was sent out (in code), or if that is not possible at least confirmation that the curl worked, so I can show a message on my website that it either succeeded or failed. In my jquery post request, the status seems to always be "success", even if I provide an invalid API_ACCESS_KEY in my php (so it obviously is not sending the notification yet it is still saying success). How can I know for sure that the notification was sent out? Grateful for any help.

Here is my post request in index.html:

$("#send-button").click(function(){     
    if($("#send").val().length == 0) {
        return;
    } else {
        $.post("php/send-notification.php",
        {
            notification_message: $("#send").val()
        },
        function(data, status) {
            alert("Data: " + data + "\nStatus: " + status);
            // status seems to always be "success" even with an invalid API_ACCESS_KEY
        });
    }
});

Here is send-notification.php:

<?php
    define( 'API_ACCESS_KEY', 'AAA....AAA' );

    $msg = array
    (
        'body'  => $_POST['notification_message'],
        'vibrate'   => 1,
        'sound'     => 1,
        'badge'     => 1
    );

    $fields = array
    (
        'to'            => "/topics/global",
        'notification'  => $msg,
        'priority'      => 'high'
    );

    $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_SSL_VERIFYPEER, false );
    curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
    $result = curl_exec( $ch );
    curl_close( $ch );
?>

Solution

  • You can use curl_getinfo

    to check response information, if yur status code 200 that meet everything ok.

    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if($httpcode == 200) {
        //everything ok
    }