问题
I'm a bit confused. I have a GCM PHP server side app server that uses a key from Google Developer Console. I can create Android key as per the instructions given in getting started guide here, or I can create a browser key, server key or OAuth key.
Can somebody tell which key I should use on the server side PHP when sending messages via GCM to Android devices?
This is the function that sends the message to GCM
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
Obviously the XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX string is replaced by my API_KEY in the original code.
p.s: My android is registering fine with the GCM, I have the registration id sent to server as well, it's the send message post request that always returns 401 Unauthorized, I'm afraid I'm using a wrong key?
p.s2: I've tried all 3 sort of API_KEYs without success.
回答1:
Solved
I was concentrating on Android or Server API_KEY but I actually had to use browser key.
Moreover, to test initially I removed all IP addresses from white listing to make sure that's not the factor playing it's role.
Now I have the push service working with above code using Browser API Key and IP restriction in place for white listing.
Cheers :)
回答2:
Be sure you include the 'Authorization' header with value 'key=APIKEY'.
ApiKey can be either server key or browser key.
If you define IP whitelist for server key, you can only send messages from the specified IPs.
来源:https://stackoverflow.com/questions/20787059/gcm-push-server-side-which-api-key-to-use