如何在不使用 Firebase 控制台的情况下发送 Firebase 云消息传递通知?

新手上路,请多包涵

我开始使用新的 Google 通知服务 Firebase Cloud Messaging

感谢这段代码 https://github.com/firebase/quickstart-android/tree/master/messaging 我能够从我的 Firebase 用户控制台 向我的 Android 设备发送通知。

是否有任何 API 或方法可以在不使用 Firebase 控制台的情况下发送通知?我的意思是,例如,一个 PHP API 或类似的东西,直接从我自己的服务器创建通知。

原文由 David Corral 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 639
2 个回答

Firebase Cloud Messaging 有一个服务器端 API,您可以调用它来发送消息。请参阅 https://firebase.google.com/docs/cloud-messaging/server

发送消息可以像使用 curl 调用 HTTP 端点一样简单。请参阅 https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol

 curl -X POST --header "Authorization: key=<API_ACCESS_KEY>" \
    --Header "Content-Type: application/json" \
    https://fcm.googleapis.com/fcm/send \
    -d "{\"to\":\"<YOUR_DEVICE_ID_TOKEN>\",\"notification\":{\"title\":\"Hello\",\"body\":\"Yellow\"}}"

您可以在任何环境中使用所有这些 REST API,但是 这里 列出的许多平台都有专用的所谓 Admin SDK。

原文由 Frank van Puffelen 发布,翻译遵循 CC BY-SA 4.0 许可协议

介绍

我编译了上面的大部分答案,并根据 FCM HTTP 连接文档 更新了变量,以策划一个在 2021 年与 FCM 一起使用的解决方案。感谢 Hamzah Malik 的上述非常有见地的回答。

先决条件

首先,确保您已将您的项目与 Firebase 相关联,并且您已在应用程序上设置了所有依赖项。如果还没有,请先查看 FCM 配置文档

如果这样做了,您还需要从 API 复制项目的服务器响应密钥。转到您的 Firebase 控制台,单击您正在处理的项目,然后导航到;

 Project Settings(Setting wheel on upper left corner) -> Cloud Messaging Tab -> Copy the Server key

配置你的 PHP 后端

我使用 Ankit Adlakha 的 API 调用结构 和 FCM Docs 编译了 Hamzah 的答案,以提出以下 PHP 函数:

 function sendGCM() {
  // FCM API Url
  $url = 'https://fcm.googleapis.com/fcm/send';

  // Put your Server Response Key here
  $apiKey = "YOUR SERVER RESPONSE KEY HERE";

  // Compile headers in one variable
  $headers = array (
    'Authorization:key=' . $apiKey,
    'Content-Type:application/json'
  );

  // Add notification content to a variable for easy reference
  $notifData = [
    'title' => "Test Title",
    'body' => "Test notification body",
    'click_action' => "android.intent.action.MAIN"
  ];

  // Create the api body
  $apiBody = [
    'notification' => $notifData,
    'data' => $notifData,
    "time_to_live" => "600" // Optional
    'to' => '/topics/mytargettopic' // Replace 'mytargettopic' with your intended notification audience
  ];

  // Initialize curl with the prepared headers and body
  $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_POSTFIELDS, json_encode($apiBody));

  // Execute call and save result
  $result = curl_exec ( $ch );

  // Close curl after call
  curl_close ( $ch );

  return $result;
}

自定义您的通知推送

要通过令牌提交通知,请使用 'to' => 'registration token'

期待什么

我在我的网站后端设置了该功能,并在 Postman 上对其进行了测试。如果您的配置成功,您应该会收到与以下类似的响应;

 {"message":"{"message_id":3061657653031348530}"}

原文由 Kenneth Murerwa 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题