Skip to content
Advertisement

How to send an push notification with image & badge using firebase in php? [closed]

I am really confusing how to send Firebase push notification with image & badge (real time counting of the notification) using PHP CURL?

Thanks in advance!

Advertisement

Answer

here is the complete example of the real-time badge counting for the push notification.

function sendFCM($message ,$tokens ,$title)
{
    // For Badge Count
    global $conn;
    $badge = 1;
    foreach ($tokens as $key => $valueTokens) 
    {
        $getBadgeQ = "SELECT badge FROM tablename WHERE token = '".$valueTokens."' ";
        $getBadgeE = mysqli_fetch_assoc(mysqli_query($conn, $getBadgeQ));
        $badge = $badge + $getBadgeE['badge'];
        $updateQ = mysqli_query($conn,"UPDATE tablename SET badge = '".$badge."' WHERE token = '".$valueTokens."' ");
    }
    $url = 'https://fcm.googleapis.com/fcm/send';
    $key = '<your api server key>';
    $fields = array(
        'registration_ids' => $tokens,
        'notification' =>array('title' => $title, 'body' =>  $message , 'badge'=>$badge, 'sound'=>'Default','image'=>'<full path of the image>' ),
    );   
    $fields = json_encode($fields);
    $headers = array(
        'Authorization: key=' . $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_SSL_VERIFYPEER, false);// skip ssl certificate verification
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    $response = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    if ($err) {
        return $err;
    } else {
        return (json_decode($response));
    }
}

$message = "This is test message..!!";
$title = "Testing Push";
$tokens[] = "<your device token>";

$response = sendFCM($message ,$tokens ,$title);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement