问题
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