Google GCM server returns Unauthorized Error 401

Sushil Kandola picture Sushil Kandola · Sep 27, 2012 · Viewed 72.9k times · Source

I am using GCM services to push information from server. If I use browser key it shows the sucess mesaage 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;

Please help me for this issue. Thanks in advance.

Answer

Jos picture Jos · Jan 3, 2013

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