简体   繁体   中英

Sending Firebase Push Notification

I'm new to android programming and I want to send a push notification to my app through a php script. Below is the code that I have used.

<?php

function send_notification($tokens,$message)
{
    $url = 'https://fcm.googleapis.com/fcm/send';

    $feilds = array
        (
            'registration_ids' =>$tokens,
            'data' => $message
        );

        $headers = array
        (
            'Authorization:key=MY_AUTH_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_VERIFYHOST,0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($feilds));

        $result = curl_exec($ch);
        if($result == FALSE)
        {
            die('CURL FAILED : '.curl_error($ch));
        }
        curl_close($ch);

        return $result;
}

$conn = mysqli_connect("localhost","root","","my_tavel_database_all");

$sql = "SELECT reg_token FROM customer_main";

$result = mysqli_query($conn,$sql);

$tokens = array();

if(mysqli_num_rows($result)>0)
{
    while($row = mysqli_fetch_assoc($result))
    {
        $tokens[] = $row["reg_token"];
    }
}

mysqli_close($conn);


$message = array("message" => "FCM test Meaagse");

$message_status = send_notification($tokens,$message);

echo $message_status;

?>

I run this script on my localhost and get the fallowing output.

{"multicast_id":7722789472959616021,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1539494402770756%ab8b1f6bf9fd7ecd"}]}

It says one message is success. but I'm not getting the push notification to my device.But when I'm sending notification from the firebase console, my device recieves the notification. can anyone help?

Maybe you need to change your field array like this:

    if($_POST['send_to']=='topic'){
        $fields = array(
            'to' => '/topics/' . $topic,
            'data' => $requestData,
        );

    }else{

        $fields = array(
            'to' => $firebase_token,
            'data' => $requestData,
        );
    }

See this link http://www.androiddeft.com/2017/11/18/push-notification-android-firebase-php/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM