Golang:使用 FCM 实现推送通知_golang fcm

设备令牌是主要参赛者,负责推送通知。这不是一个花哨的词,它只是每个设备唯一的 id。当我们安装任何应用程序时,我们设备的唯一令牌会存储在他们的服务器上,他们可以使用它来通知我们。

Firebase 是用于将通知推送到应用程序/手机/平板电脑的工具。
它提供了一个设置来配置用于推送通知的云消息传递 (FCM) 服务。

注意:应用端使用的 firebase 配置文件(android 为 google_services.json 文件,iOS 为 GoogleService-Info.plist)和 service_account 密钥必须从 firebase 控制台为同一个项目创建。

在本文中,我们将探讨如何使用 Golang 和 Firebase 发送推送通知。

让我们跳到实施。

  1. 配置 Firebase 身份验证密钥

所需软件包:

firebase.google.com/go
firebase.google.com/go/messaging

使用加密格式的敏感内容总是更好。为了达到这个目的,我将服务帐户密钥以 base64 格式存储为环境变量。

在这里,FIREBASE_AUTH_KEY 包含一个 base64 编码的服务帐户密钥。

首先,让我们解码服务帐户密钥。

func getDecodedFireBaseKey() ([]byte, error) {

  fireBaseAuthKey := os.Getenv("FIREBASE_AUTH_KEY")

  decodedKey, err :=  base64.StdEncoding.DecodeString(fireBaseAuthKey)
  if err != nil {
     return nil, err
  }

  return decodedKey, nil
}

上述方法将返回解码后的服务帐户密钥,该密钥将在下一步中使用。

使用以下代码检索解码的密钥并初始化 firebase 应用程序。

decodedKey, err := getDecodedFireBaseKey()
if err != nil {
   return err
}

opts :=  []option.ClientOption{option.WithCredentialsJSON(decodedKey)}

// Initialize firebase app
app, err := firebase.NewApp(context.Background(), nil, opts...)

if err != nil {
   log.Debug("Error in initializing firebase app: %s", err)
   return err
}

3.初始化firebase客户端

创建fcmClient用于消息传递(推送通知)。
fcmClient, err := app.Messaging(context.Background())

if err != nil {
   return err
}

最后,让我们编写一个发送通知的代码。

4.向单个设备发送推送通知

response, err := fcmClient.Send(context.Background(), &messaging.Message{

  Notification: &messaging.Notification{
    Title: "Congratulations!!",
    Body: "You have just implement push notification",
  },
    Token: "sample-device-token", // it's a single device token
})

if err != nil {
     return err
}

上面的代码将向单个设备发送推送通知。

  1. 向多个设备发送推送通知

如果您想通知多个设备,请考虑一个场景。这与我们向单个设备发送推送通知几乎相同,只需将 fcmClient 的 Send() 方法替换为 SendMulticast() 即可。

response, err := fcmClient.SendMulticast(context.Background(), &messaging.MulticastMessage{
   Notification: &messaging.Notification{
     Title: "Congratulations!!",
     Body:  "You have just implement push notification",
   },
   Tokens: deviceTokens, // it's an array of device tokens
  })

  if err != nil {
     return err
  }

log.Debug("Response success count : ", response.SuccessCount)
log.Debug("Response failure count : ", response.FailureCount)

耶 !!你已经在你的 Golang 项目中实现了推送通知🎊。
响应变量将包含已发送通知的成功计数和失败计数。

在 FCM with Golang 中查找完整代码。调用 SendPushNotification() 并繁荣!检查应用程序中收到的通知。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值