GCM sending with curl (php)

2019-01-19 09:19发布

问题:

I'm trying to send a message to an Android phone but keep getting response code 401 with text: Unauthorized. Also I keep reading different stories on what key to use, I know of 3 keys: the project ID (number), the Key for server apps and the Key for browser apps. So I have tryed them all 3, all with the same result.

My code:

$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:

I changed the header to:

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

And it works. The mykey is Key for browser apps.



回答2:

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

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