GCM push to topics using PHP

醉酒当歌 提交于 2020-01-03 05:34:15

问题


I'm trying to write a PHP script that will send a push notification to my android app using the topics method. It seems to be successful and returns a message ID, but nothing will show up on the phone. I do have a similar python script, and that one works so GCM must have been implemented correctly in the app.

Not working PHP script

$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

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()

回答1:


I figured it out. I copied your whole PHP script and tested it on my end. My onMessageReceived() was being triggered, but I noticed that the details wasn't retrieved, same as your scenario.

It was simply missed. You misspelled notifcation in your script:

'notifcation' => array(

It's missing an i. It should be notification.

Classic and easy to miss (lol). Tried it on my end, was able to show a notification afterwards.



来源:https://stackoverflow.com/questions/43357488/gcm-push-to-topics-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!