使用FCM将通知从PHP推送到Android应用

时间:2018-08-23 15:04:15

标签: php android firebase push-notification localhost

我是PHP的初学者,我想编写一个程序,以从localhost(在PHP中)向Android应用发送简单的通知(标题和小消息)。为此,我使用Firebase。目前,我可以将通知从FCM发送到android,但不能从PHP程序发送到android应用。我尝试了许多不同的方式和程序来发送此通知,但总是失败。 这是我使用的程序:

<html>
<?php
 $read = shell_exec ('gpio read 0');
 $status = intval($read);
 if ($status == 1) {
 function sendFCM($mess,$id) {
    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array (
        'AAAAS4YkIPw:A.........rLQjQ' => $id,   
        'notification' => array (
        "body" => $mess,
                "Doorbell" => "Title",
        //        "icon" => "myicon"
        )
    );
    $fields = json_encode ( $fields );
    $headers = array (
            'Authorization: key=' . "AIzaSy.....J_Hy0",
            '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_POSTFIELDS, $fields );

    $result = curl_exec ( $ch );
    curl_close ( $ch );
    }
    print ("oui");
    sleep(30);
    header("Refresh:0");
 } 
    else {
    print ("non");
    sleep(2);
    header("Refresh:0");
}
?>
</html>

在我使用的每个程序中,也许我每次都犯同样的错误,但是我找不到它。只是为了说明,该程序读取了一个GPIO,并且根据结果的功能,他告诉“ oui”或“ non”并发送一个通知,告知它是“ oui”。我在网站上执行的程序位于6号线和30号线之间。其余所有工作。我的问题是我必须不收到通知。

1 个答案:

答案 0 :(得分:0)

我看到一个错误后就更改程序,所以这是新错误。

<html>
<head>
</head>
<?php

function sendFCM($mess,$id) {
    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array (
        'AAAAS4Yk.........KirLQjQ' => $id,  
        'notification' => array (
        "body" => $mess,
                "Doorbell" => "Title",
        //        "icon" => "myicon"
        )
    );
    $fields = json_encode ( $fields );
    $headers = array (
            'Authorization: key=>' . "$ip",
            '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_POSTFIELDS, $fields );

    $result = curl_exec ( $ch );
    curl_close ( $ch );
    }

$read = shell_exec ('gpio read 0');
$status = intval($read);
if ($status == 1) {
    sendFCM('Yolo','AIzaSy......xdJ_Hy0');
    print ("oui");
    sleep(30);
    header("Refresh:0");
} 
    else {
    print ("non");
    sleep(2);
    header("Refresh:0");
}
?>
</html>