您收到 401 Unauthorized 是因为 GCM 只接受来自基于 HTTPS 的主机的请求,而您的本地控制台不接受。
验证这一点的最简单方法(如果您还没有基于 HTTPS 的网站)是:
第 1 阶段 - 获取启用 HTTPS 的网站
- 在 CloudFlare 上创建帐户
- 将您域的 DNS 更改为 CloudFlare 的
- 在 CloudFlare 控制台中输入您服务器的 IP
- 启用免费 HTTPS(并禁用缓存 - 有时可能很棘手)
现在您网站的流量将通过 CloudFlare 重定向。
从您的客户端到 CloudFlare 的流量将被加密,而从 CloudFlare 到您的服务器的流量则不会。
虽然它不是 100% 安全的,但它可以保护最常见的攻击媒介 - 恶意互联网提供商等,并且只需很少的努力即可获得免费的服务人员就绪网站。
如果你想要自己的证书,可以使用Let's Encrypt
第 2 阶段 - 将 GCM 发送方放在您的 HTTPS 服务器上
我有 PHP 中的示例代码:
<?
function sendPushNotification($data, $ids)
{
echo("<br><br><b>Sending notifications...</b>");
// Insert real GCM API key from the Google APIs Console
$apiKey = 'AIza...';
// Set POST request body
$post = array(
'registration_ids' => $ids,
'data' => $data,
);
// Set CURL request headers
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Initialize curl handle
$ch = curl_init();
// Set URL to GCM push endpoint
curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');
// Set request method to POST
curl_setopt($ch, CURLOPT_POST, true);
// Set custom request headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Get the response back as string instead of printing it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set JSON post data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
// Actually send the request
$result = curl_exec($ch);
// Handle errors
if (curl_errno($ch))
{
echo 'GCM error: ' . curl_error($ch);
}
// Close curl handle
curl_close($ch);
// Debug GCM response
echo $result;
}
$data = array('message' => 'JAAAREEEEK!');
// Please note that currently push payload is not supported. However if you're reading this answer from the future it might work
// The recipient registration tokens for this notification
// https://developer.android.com/google/gcm/
$ids = ['registrationid1','registrationid2']
// Send push notification via Google Cloud Messaging
sendPushNotification($data, $ids);
我遇到了完全相同的问题,这个解决方案解决了它。如果您还有任何问题,请给我留言。