GCM transfer with curl (php)

I'm trying to send a message to an Android phone, but I continue to receive a 401 response code with the text: "Unauthorized." I also read different stories about which key to use, I know 3 keys: the project identifier (number), the key for server applications and the key for browser applications. So I tried all 3 of them, all with the same result.

My code is:

$headers = array("Content-Type" => "application/json", "Authorization" => "key=" . "mykey"); $data = array( 'data' => $messageText, 'registration_ids' => array($deviceRegistrationId) ); $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)); error_log(json_encode($data)); $response = curl_exec($ch); curl_close($ch); error_log($response); 
+1
source share
2 answers

I changed the title to:

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

And it works. Mykey is a key for browser applications.

+4
source

You could make your headers like this, just to make it a little easier to read and eliminate concatenation:

 $headers = array( "Authorization:key=mykey", "Content-Type:application/json", ); 
0
source

Source: https://habr.com/ru/post/1436075/


All Articles