发送Firebase推送通知

时间:2018-10-14 05:23:37

标签: php android firebase push-notification firebase-cloud-messaging

我是android编程的新手,我想通过php脚本向我的应用发送推送通知。下面是我使用的代码。

<?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;

?>

我在本地主机上运行此脚本并获得休闲输出。

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

它说一条信息就是成功。但是我没有收到推送通知到我的设备。但是,当我从Firebase控制台发送通知时,我的设备会收到该通知。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

也许您需要像这样更改字段数组:

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

    }else{

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

查看此链接http://www.androiddeft.com/2017/11/18/push-notification-android-firebase-php/