简体   繁体   English

GCM使用PHP推送主题

[英]GCM push to topics using PHP

I'm trying to write a PHP script that will send a push notification to my android app using the topics method . 我正在尝试编写一个PHP脚本,该脚本将使用topics方法将推送通知发送到我的android应用程序。 It seems to be successful and returns a message ID, but nothing will show up on the phone. 它似乎成功,并返回了一条消息ID,但电话上没有任何显示。 I do have a similar python script, and that one works so GCM must have been implemented correctly in the app. 我确实有一个类似的python脚本,并且该脚本可以正常运行,因此GCM必须已在应用程序中正确实现。

Not working PHP script 无法使用PHP脚本

$msg = array(
    'to'          => '/topics/my_little_topic',
    'notifcation' => array(
                            'body'      => 'here is a message message',
                            'title'     => 'This is a title title',
                            'icon'      => "ic_launcher"
    )
);

$headers = array
(
    'Content-Type: application/json',
    'Authorization: key='. API_ACCESS_KEY
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/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( $msg, JSON_UNESCAPED_SLASHES) );
$result = curl_exec($ch );
curl_close( $ch );

echo $result;

?>

Working python script 工作的Python脚本

from urllib2 import *
import urllib
import json
import sys

MY_API_KEY="AIzaSyBh...aWIVA"

messageTitle = sys.argv[1]
messageBody = sys.argv[2]

data={
    "to" : "/topics/my_little_topic",
    "notification" : {
        "body" : messageBody,
        "title" : messageTitle,
        "icon" : "ic_launcher"
    }
}

dataAsJSON = json.dumps(data)

print dataAsJSON

request = Request(
    "https://gcm-http.googleapis.com/gcm/send",
    dataAsJSON,
    { "Authorization" : "key="+MY_API_KEY,
      "Content-type" : "application/json"
    }
)

print urlopen(request).read()

I figured it out. 我想到了。 I copied your whole PHP script and tested it on my end. 我复制了整个PHP脚本并对其进行了测试。 My onMessageReceived() was being triggered, but I noticed that the details wasn't retrieved, same as your scenario. 我的onMessageReceived()已被触发,但我发现未检索到详细信息,与您的情况相同。

It was simply missed. 简直就是错过了。 You misspelled notifcation in your script: 您在脚本中拼写了错误的notifcation

'notifcation' => array(

It's missing an i . 它缺少一个i It should be notification . 应该是notification

Classic and easy to miss (lol). 经典且容易错过 (笑)。 Tried it on my end, was able to show a notification afterwards. 我尝试了此操作,之后能够显示通知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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