3

I'm using the following code to make HTTP POST request to the gcm server. The code always returns "Unauthorized Error 401". I read that it is about the headers but can't figure out whats wrong. Can anyone tell me what's wrong? Is there any other way to send a gcm message? Any help would be appreciated.

$api_key = "AIzaSyBhuPSdHmq6-************_qxSJr8d0";

$message = array("msg_url" => $msg_url, "msg_title" => $msg_title);

$url = 'https://android.googleapis.com/gcm/send';

$fields = array('registration_ids'  => $ids,'data'=> array( "message" => $message ));

$headers = array('Authorization: key=' . $api_key,'Content-Type: application/json');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'=> $headers ,
        'method'  => 'POST',
        'content' => json_encode($fields),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);
Rahul
  • 49
  • 1
  • 4
  • Perhaps the problem is with your api key. Try testing it [here](http://helmibaraja.com/gcm_demo.html). – Eran Jan 09 '14 at 15:00
  • There's no problem with the api key. I have tested it with the cURL method and it works just fine. But I don't want the cURL method for some server reasons. Is there any alternative to cURL. The link you gave uses cURL. – Rahul Jan 10 '14 at 05:23

1 Answers1

5

Tested your code with my API key. I am able to send request to GCM and getting proper response. It seems like your API Key is having the problem

<?php

$msg_url = "http://msg.com";

$msg_title = "message_title";

$ids = array('reg_id_1', 'reg_id_2'); 

$api_key = "AIzaSyBhuPSdHmq6-************_qxSJr8d0";

$message = array("msg_url" => $msg_url, "msg_title" => $msg_title);

$url = 'https://android.googleapis.com/gcm/send';

$fields = array('registration_ids'  => $ids,'data'=> array( "message" => $message ));

$headers = array('Authorization: key=' . $api_key,'Content-Type: application/json');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'=> $headers ,
        'method'  => 'POST',
        'content' => json_encode($fields),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);
?>
Harikrishnan R
  • 1,444
  • 4
  • 16
  • 27