Search code examples
phpandroidjsongoogle-cloud-messaging

Google GCM server returns Unauthorized Error 401


I am using GCM services to push information from server.

If I use browser key it shows the success message as :

{"multicast_id":4849013215736515938,"success":1,"failure":0,"canonical_ids":0,"results":
[{"message_id":"0:1348742583011905%2adac3a0f9fd7ecd"}]}

but I did not get any notifications on device.

And if I use server key it shows Unauthorized Error 401. My code is shown below:

$apiKey = "xxxxx";
$registrationIDs = array("xxxxxxxx");
$message = "testing Process";
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
        'registration_ids'  => $registrationIDs,
        'data'              => array("message"=>$message),
        );
$headers = array( 
        'Authorization: key=' . $apiKey,
        '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_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($fields) );
  
$result = curl_exec($ch);
if(curl_errno($ch)){ echo 'Curl error: ' . curl_error($ch); }
curl_close($ch);
echo $result;

Any ideas?


Solution

  • Did you whitelist the IP of your server? This is not necessary by default for the browser key, but it is for the server key.

    You can check it here:

    https://code.google.com/apis/console/#project:[YOUR PROJECT NUMBER]:access