如何在不使用cURL的情况下在php中发送gcm消息?

Rah*_*hul 3 php push-notification google-cloud-messaging

我正在使用以下代码向gcm服务器发出HTTP POST请求.代码始终返回"Unauthorized Error 401".我读到这是关于标题,但无法弄清楚什么是错的.谁能告诉我什么是错的?有没有其他方式发送gcm消息?任何帮助,将不胜感激.

$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);
Run Code Online (Sandbox Code Playgroud)

Har*_*n R 5

使用我的API密钥测试您的代码.我能够向GCM发送请求并获得适当的响应.您的API Key似乎遇到了问题

<?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);
?>
Run Code Online (Sandbox Code Playgroud)