php - 未经授权的错误 401 GCM 错误

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

请注意,这个问题应该与其他具有相似名称的问题有本质上的不同,因为 API 在过去几年中似乎发生了重大变化。

我正在尝试使用 GCM 向 iOS 设备发送推送通知。

我(我认为)大部分设置都是正确的。我有 GCM 提供的 API key ,我已在 Apple Developer 上设置了 SSL 证书,并且我的设备正确获取了注册 ID。

我写了一些测试脚本来尝试测试它,结果出现 401 未经授权的错误。这是我的代码:

define('API_ACCESS_KEY', '<API KEY HERE>');

$fields = array(
    'to' => '<REG_ID HERE>',
    'registration_ids' => '<REG_ID HERE>',
    'notification' => array('body' => 'test', 'title' => 'Test'),
  );

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

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');

  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

  $result = curl_exec($ch);

  curl_close($ch);

我目前正在使用不受限制的 key 进行测试:

This key is unrestricted. To prevent unauthorized use and quota theft, restrict your key. 
Key restriction lets you specify which web sites, IP addresses, or apps can use this key.

据我所知,这应该将所有内容列入白名单,不是吗?几年前有一些关于如何将服务器列入白名单的答案,但这似乎适用于 API 的旧界面/设置。

什么可能导致此问题?

最佳答案

更新:GCM docs 中现在有一条可见的注释。说:

Starting from Sept. 2016 new server key can only be created in the Firebase Console using the Cloud Messaging tab of the Settings panel. Existing projects that need to create a new server key can be imported in the Firebase console without affecting their existing configuration.


更新:从 GCM 迁移到 FCM 似乎还修复了 401 未经授权错误的问题。

如果您刚刚开始使用 GCM,请在 Firebase 控制台中创建项目,而不是在 Google Developers Console 中创建项目。创建项目后,只需使用自动生成的服务器 key 即可。以下是查找服务器 key 的步骤:

  1. 转到您的 Firebase Console然后点击创建新项目
  2. 填写您所需的项目名称并选择您所在的国家/地区。此后,新项目应该处于事件状态。
  3. 然后在左侧面板上,点击齿轮按钮并选择项目设置
  4. 然后转到云消息传递选项卡

对于旧的 GCM 项目,您只需将项目导入到 Firebase 控制台即可:

  1. 转到您的 Firebase Console然后点击导入项目
  2. 选择您要导入的项目和您所在的国家/地区。
  3. 点击添加 FIREBASE。此后,新项目应该处于事件状态。
  4. 然后在左侧面板上,点击齿轮按钮并选择项目设置
  5. 然后转到云消息传递选项卡

过去几天我看到了很多这样的担忧。不受限制的 key 似乎会返回 401 错误,这可能是因为它们正在强制所有 API key 的安全性(您在其中看到警告)。

因此,我通常建议是利用 IP 地址限制(因为这是针对 GCM 的,它应该是服务器 key )并添加您的服务器 IP 地址。 查看我的回答 here .

关于php - 未经授权的错误 401 GCM 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39585610/

相关文章:

php - 瑞典字母 MySQL 和 LAMP 的问题

php - linux:解压缩存档时将文件名中的空格转换为下划线

ios - 为什么我的简单 swift 委托(delegate)和协议(protocol)设置不起作用?

ios - 所有选项卡栏 Controller 的栏按钮

android - flutter 的firebase推送通知图标

firebase - FirebaseMessagingError.FirebaseError 错误 : Requested entity was not found. [作为构造函数]

php - mysql查询,选择一定的结果数组

php - 通知网络服务如果应用程序关闭

iOS7 问题与自定义单元格选择模态视图 Controller segue

android - 当应用程序未运行(iphone/android)时,在远程触发器上创建(重复高音)警报,就像查找我的 iPhone 一样