【问题标题】:How do you send React Native Push Notifications with Firebase Admin SDK in a Ruby on Rails server?如何在 Ruby on Rails 服务器中使用 Firebase Admin SDK 发送 React Native Push Notifications?
【发布时间】:2020-07-16 02:39:26
【问题描述】:

我正在尝试在我的 React Native 项目中实现推送通知,并已设置推送通知以在我的 iOS 应用程序中工作。我想从我的 Ruby on Rails 服务器发送通知,即当用户收到好友请求时,但 Firebase Admin SDK 仅提供与 Node.js、Java、Python、C# 和 Go 的兼容性。 我用 Ruby on Rails 编写了我的服务器代码,并想从 Rails 调用 Firebase Admin SDK。

我正在尝试遵循这个使用 Firebase 的 React Native Push Notifications 教程:https://rnfirebase.io/messaging/server-integration 使用通知令牌向特定设备发送通知,但一切都是用 Node.js 编写的,我不知道如何导航实现而是使用 Ruby 中的代码。

我还查看了 用于 Firebase Admin SDK 的 REST API 的不同 Ruby 帮助程序库https://firebase.google.com/docs/database/rest/start,但这些库的文档对我来说有点太神秘了,我无法理解。

理想情况下,我想要实现的功能类似于:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
exports.sendPushNotification = functions.database
  .ref("users/{userID}")
  .onCreate(event => {
    const data = event._data;
    payload = {
      notification: {
        title: "Welcome",
        body: "thank for installed our app",
      },
    };
    admin
      .messaging()
      .sendToDevice(data.notification_token, payload)
      .then(function(response) {
        console.log("Notification sent successfully:", response);
      })
      .catch(function(error) {
        console.log("Notification sent failed:", error);
      });
  });

但很遗憾,https://www.instamobile.io/react-native-tutorials/push-notifications-react-native-firebase/ 中的这段代码在 Node.js 中,无法在我的 Ruby on Rails 服务器上运行。

【问题讨论】:

  • 只是一个建议,您只想发送推送通知。试试onesignal。将 onesignal 集成到 rails 非常容易。

标签: ruby-on-rails ruby firebase react-native firebase-admin


【解决方案1】:

https://firebase.google.com/docs/cloud-messaging/send-message 中有一些 FCM 的 REST 示例。您需要像 https://github.com/googleapis/google-auth-library-ruby 这样的授权库来授权您的请求。然后弄清楚如何从 Ruby 进行 REST 调用。这是我过去使用的一些示例代码:

require 'googleauth'
require 'net/http'
require 'json'
require 'uri'

authorizer = Google::Auth.get_application_default(scopes)

req = Net::HTTP::Get.new(uri)
# Add authorization header to the request
some_headers = {}
authorizer.apply!(some_headers)
some_headers.each do |key, value|
    req[key] = value
end

res = http.request(req)
parsed_results = JSON.parse(res.body)

【讨论】:

  • 谢谢黑兰亚!这很有帮助,我会研究一下 Google Auth Library for Ruby。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
  • 2020-12-13
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多