为 Firebase 云消息传递 PHP 生成 OAUTH 令牌

2023-12-07

我有一个 PHP 页面,我用它来向我开发的移动应用程序的用户发送通知,该页面直到上个月都工作正常,然后它给了我这个错误

{"multicast_id":5174063503598899354,"成功":0,"失败":1,"canonical_ids":0,"结果":[{"错误":"无效注册"}]}

我尝试使用此链接中的文档生成 OAUTH 令牌https://firebase.google.com/docs/cloud-messaging/auth-server#node.js但它需要 NODE.JS 服务器,而我的服务器不支持 Node.Js ,我尝试使用 Firebase Admin SDK 但找不到任何内容。 这是页面的PHP代码

<?php

//Includes the file that contains your project's unique server key from the Firebase Console.
require_once("serverKeyInfo.php");

//Sets the serverKey variable to the googleServerKey variable in the serverKeyInfo.php script.
$serverKey = $googleServerKey;

//URL that we will send our message to for it to be processed by Firebase.
    $url = "https://fcm.googleapis.com/fcm/send";

//Recipient of the message. This can be a device token (to send to an individual device) 
//or a topic (to be sent to all devices subscribed to the specified topic).
$recipient = $_POST['rec'];

//Structure of our notification that will be displayed on the user's screen if the app is in the background.
$notification =array(
    'title'   => $_POST['title'],
    'body'   => $_POST['body'],
    'sound' => 'default'
);

//Structure of the data that will be sent with the message but not visible to the user.
//We can however use Unity to access this data.
$dataPayload =array( 

    "powerLevel" => "9001",
    "dataString" => "This is some string data"
);

//Full structure of message inculding target device(s), notification, and data.
$fields =array(

    'to'  => $recipient,
    'notification' => $notification,
    'data' => $dataPayload
);

//Set the appropriate headers
$headers = array(

'Authorization: key=' . $serverKey,
'Content-Type: application/json'
);
//Send the message using cURL.
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, $url);
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 );

//Result is printed to screen.
echo $result;
?>

任何人都可以给我发一个例子吗我该怎么做(我是 PHP 初学者) 提前致谢

*更新:我还尝试将代码中的 $url 更改为

$url = "https://fcm.googleapis.com/v1/projects/notifications-9ccdd/messages:send";

但它给了我这个错误

“错误”: { “代码”:401, "message": "请求的身份验证凭据无效。需要 OAuth 2 访问令牌、登录 cookie 或其他有效的 身份验证凭证。看https://developers.google.com/identity/sign-in/web/devconsole-project。”, “状态”:“未经身份验证” } 块引用


****** 2023 年更新 ****** FCM http Legacy 已正式弃用,并将于 2024 年 6 月完全删除。任何使用 http Legacy 版本的人都应迁移到 V1。下面的示例使用 V1 而不是 http Legacy 版本:)


对于仍在寻找此问题答案的人 (2021),为了通过您自己的 PHP 系统向 Firebase 消息系统发送推送消息,您需要来自 Google Credentials 的访问令牌。以下是如何做到这一点 - 请注意我只在 PHP Laravel 中完成了此操作,而不是原始 PHP。但是您应该能够通过修改步骤来找到适合此问题的普通 PHP 解决方案(也与 Code Igniter 和其他 PHP 库相同)

  1. In your http://console.firebase.google.com在项目->设置->服务帐户下找到 Firebase 服务帐户。生成新的私钥并下载 json 文件。将其存储在服务器上用户无法访问的地方。

  2. 安装 Google API 客户端。对于 Laravel 来说是:

      composer require google/apiclient --with-all-dependencies
    
  3. 打开composer.json,并将其添加到自动加载数组中。对于 Laravel 来说是:

     "classmap": [
         "vendor/google/apiclient/src/Google"
     ],
    
  4. 创建一个新的 Service 类(或者如果是普通 PHP,则创建一个新的 Class),并添加以下方法来检索访问令牌:

    private function getGoogleAccessToken(){
    
         $credentialsFilePath = 'the-folder-and-filename-of-your-downloaded-service-account-file.json'; //replace this with your actual path and file name
         $client = new \Google_Client();
         $client->setAuthConfig($credentialsFilePath);
         $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
         $client->refreshTokenWithAssertion();
         $token = $client->getAccessToken();
         return $token['access_token'];
    }
    
  5. 现在创建一个方法通过 CURL 将所有消息信息发送到 Firebase:

    public function sendMessage(){
    
     $apiurl = 'https://fcm.googleapis.com/v1/projects/your-project-id/messages:send';   //replace "your-project-id" with...your project ID
    
     $headers = [
             'Authorization: Bearer ' . $this->getGoogleAccessToken(),
             'Content-Type: application/json'
     ];
    
     $notification_tray = [
             'title'             => "Some title",
             'body'              => "Some content",
         ];
    
     $in_app_module = [
             "title"          => "Some data title (optional)",
             "body"           => "Some data body (optional)",
         ];
     //The $in_app_module array above can be empty - I use this to send variables in to my app when it is opened, so the user sees a popup module with the message additional to the generic task tray notification.
    
      $message = [
            'message' => [
                 'notification'     => $notification_tray,
                 'data'             => $in_app_module,
             ],
      ];
    
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $apiurl);
      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($message));
    
      $result = curl_exec($ch);
    
      if ($result === FALSE) {
          //Failed
          die('Curl failed: ' . curl_error($ch));
      }
    
      curl_close($ch);
    
    }
    

Google 建议您仅在无法直接将 JSON 文件作为环境变量添加到服务器上时才使用此方法。 我不知道为什么 Google 没有关于这个主题的 PHP 更好的文档,它似乎更喜欢 Node.js 、Go、Java 和 C++。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为 Firebase 云消息传递 PHP 生成 OAUTH 令牌 的相关文章

  • 删除PHP字符串中所有不匹配的字符?

    我有一个文本 我想从中删除所有不属于以下字符的字符 所需字符 0123456789 abcdefghijklmnopqrstuvwxyz n 最后一个是我确实想保留的 n 换行符 要匹配除列出的字符之外的所有字符 请使用反转字符集 http
  • 重定向而不改变url

    我总是不喜欢 htaccess 我正在尝试建立一个所有请求都通过index php 的网站 但我希望URL 类似于www sample com home 该网址实际上会加载 www sample com index php page hom
  • ApiGee OAUTH 授权

    我是 Apigee 的新手 我需要在代理中进行标注以从谷歌融合表中获取数据 FT 服务要求使用誓言 2 0 进行安全呼叫 我已经使用自定义代理创建了此工作流程 没有任何 OAUTH 策略 并在键值映射中存储令牌 刷新令牌和过期时间 我还制作
  • 如何使用 phpunit 运行单个测试方法?

    我正在努力运行一个名为testSaveAndDrop在文件中escalation EscalationGroupTest php with phpunit 我尝试了以下组合 phpunit EscalationGroupTest escal
  • 如何解压 PHP/Lumen/Laravel 的 gzip 请求?

    我收到来自第三方的 gzip 编码文本请求 1mb 所以这是有道理的 我的测试路线 router gt post testgzip function Illuminate Http Request request decompressed
  • 如何检查PHP变量是否包含非数字?

    我只是想知道检查 PHP 变量中是否有非数字的方法以及它是否也检测字符之间的空格 需要确保我的表单字段中没有添加任何奇怪的内容 提前致谢 如果您的意思是您只想要一个包含数字的值 那么您可以使用ctype digit http php net
  • PHP严格标准:声明应该兼容

    我有以下类层次结构 class O Base class O extends O Base abstract class A Abstract public function save O Base obj class A extends
  • “使用未定义常量”注意,但该常量应该被定义

    共有三个文件 common php controller php 和 user php 文件 common php 如下所示 文件controller php看起来像 文件 user php 如下所示 执行脚本时 会给出通知 注意 使用未定
  • 交换关联数组中的两个项目

    Example arr array apple gt sweet grapefruit gt bitter pear gt tasty banana gt yellow 我想调换一下柚子和梨的位置 这样数组就变成了 arr array ap
  • 在 PHP 中撤销 Google 访问令牌

    正如标题所示 我想以编程方式撤销授予的访问令牌 即在 PHP 中 我发现这个他们的网站 https developers google com identity protocols OAuth2WebServer tokenrevoke 但
  • 随机组合 MySQL 数据库中的两个单词

    我有一个包含名词和形容词的数据库 例如 id type word 1 noun apple 2 noun ball 3 adj clammy 4 noun keyboard 5 adj bloody ect 我想创建一个查询 它将抓取 10
  • PHP 与 MySQL 查询性能( if 、 函数 )

    我只看到这个artice http www onextrapixel com 2010 06 23 mysql has functions part 5 php vs mysql performance 我需要知道在这种情况下什么是最好的表
  • 在 apache docker 容器中运行虚拟主机

    我在同一个 apache 容器中有两个 php 应用程序 我试图在端口上运行其中一个应用程序 因为它需要通过根域而不是子文件夹进行访问 我想在端口 8060 上运行应用程序 我尝试使用 apache 虚拟主机执行此操作 但它不会加载页面 h
  • 跟踪用户何时点击浏览器上的后退按钮

    是否可以检测用户何时单击浏览器的后退按钮 我有一个 Ajax 应用程序 如果我可以检测到用户何时单击后退按钮 我可以显示适当的数据 任何使用 PHP JavaScript 的解决方案都是优选的 任何语言的解决方案都可以 只需要我可以翻译成
  • PHP HEREDoc (EOF) 语法在 Sublime Text 3 上突出显示与正斜杠的差异

    我不熟悉 Sublime Text 3 如何使用语法突出显示 例如 如果它纯粹依赖于主题 或者它内置于主题运行的标准中 但就我而言 使用 PHP 的 HERE 文档和转发存在一些语法突出显示差异斜线 一旦出现正斜杠 ST3 就会认为以下所有
  • 表单提交后如何保留选择字段中的选定值?

    我有一个用于将票证上传到数据库的主页 我有一个选择字段 我想保留用户在提交表单之前选择的值 但它没有发生 这是我选择字段的代码
  • firebase :: 无法读取 null 的属性“props”

    你好 我正在尝试将react router与firebase一起使用 但它给了我这个错误 无法读取 null 的属性 props 这正是代码 我正在其中使用我的反应路由器 向下代码位于作为登录面板组件的组件上 else if this em
  • Doctrine EntityManager 清除嵌套实体中的方法

    我想用学说批量插入处理 http doctrine orm readthedocs org en latest reference batch processing html为了优化大量实体的插入 问题出在 Clear 方法上 它表示此方法
  • 为什么 Composer 降级了我的包?

    php composer phar update这样做了 删除了 2 3 0 软件包并安装了整个 2 2 5 Zend Framework php composer phar update Loading composer reposito
  • Magento - 自定义支付模块

    这是一个非常普遍的问题 但这里是 我正在尝试在 Magento 中创建一个自定义支付模块 我创建了一个 常规 模块 可以连接到 Magento 事件 观察者模型 但是我如何告诉 Magento 将模块视为支付模块 以便它显示在管理后端和结账

随机推荐