【问题标题】:How to send a gcm message in php without using cURL?如何在不使用 cURL 的情况下在 php 中发送 gcm 消息?
【发布时间】:2025-12-08 19:35:01
【问题描述】:

我正在使用以下代码向 gcm 服务器发出 HTTP POST 请求。 该代码始终返回“未经授权的错误 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);

【问题讨论】:

  • 可能问题出在您的 api 密钥上。尝试测试它here
  • api密钥没有问题。我已经用 cURL 方法对其进行了测试,它工作得很好。但由于某些服务器原因,我不想要 cURL 方法。是否有任何替代 cURL 的方法。您提供的链接使用 cURL。

标签: php push-notification google-cloud-messaging


【解决方案1】:

使用我的 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);
?>

【讨论】:

    最近更新 更多