Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCM server side PHP - Unauthorized 401 Error

I setup google developer console enabling Google Cloud Messaging for Android.

In the credential side I create the browser API key typing 0.0.0.0 in the refers. Actually I create both the types of key because I found different indication in different tutorial.

browser-key picture

server-key picture

I tested the key with this PHP script

<?
/**
 * The following function will send a GCM notification using curl.
 * 
 * @param $apiKey       [string] The Browser API key string for your GCM account
 * @param $registrationIdsArray [array]  An array of registration ids to send this notification to
 * @param $messageData      [array]  An named array of data to send as the notification payload
 */
function sendNotification( $apiKey, $registrationIdsArray, $messageData )
{   
    $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
    $data = array(
        'data' => $messageData,
        'registration_ids' => $registrationIdsArray
    );

    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); 
    curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}
?>
<?
// Message to send
$message      = "the test message";
$tickerText   = "ticker text message";
$contentTitle = "content title";
$contentText  = "content body";

$registrationId = '372CBFD0C4BFE728';
$apiKey = "AIzaSyDeNN1XJBFGE_lJ_35VMUmx5cUbRCUGkjo";

$response = sendNotification( 
                $apiKey, 
                array($registrationId), 
                array('message' => $message, 'tickerText' => $tickerText, 'contentTitle' => $contentTitle, "contentText" => $contentText) );

echo $response;    
?>

I expect to obtain something like that

{"multicast_id":6782339717028231855,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

But I obtain (with both keys) Unauthorized 401 Error.

Thanks for the help.

like image 385
tilusup Avatar asked Mar 19 '23 13:03

tilusup


1 Answers

Instead of entering 0.0.0.0 as allowed referrers or allowed IPs, don't enter anything. That should work.

like image 51
Eran Avatar answered Mar 24 '23 18:03

Eran