设备令牌是主要参赛者,负责推送通知。这不是一个花哨的词,它只是每个设备唯一的 id。当我们安装任何应用程序时,我们设备的唯一令牌会存储在他们的服务器上,他们可以使用它来通知我们。
Firebase 是用于将通知推送到应用程序/手机/平板电脑的工具。
它提供了一个设置来配置用于推送通知的云消息传递 (FCM) 服务。
注意:应用端使用的 firebase 配置文件(android 为 google_services.json 文件,iOS 为 GoogleService-Info.plist)和 service_account 密钥必须从 firebase 控制台为同一个项目创建。
在本文中,我们将探讨如何使用 Golang 和 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
}
上面的代码将向单个设备发送推送通知。
如果您想通知多个设备,请考虑一个场景。这与我们向单个设备发送推送通知几乎相同,只需将 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() 并繁荣!检查应用程序中收到的通知。
同时,您也可以查看调试日志,因为它有 SuccessCount 和 failureCount。这将有助于验证通知被推送到多少令牌。如果发现 failureCount > 0,您必须验证您是否提供了有效的设备令牌。
希望大家能够共同学习、共同努力、共同进步。
小编在这里祝小伙伴们在未来的日子里都可以 升职加薪,当上总经理,出任CEO,迎娶白富美,走上人生巅峰!!
不论遇到什么困难,都不应该成为我们放弃的理由!
很多人在刚接触这个行业的时候或者是在遇到瓶颈期的时候,总会遇到一些问题,比如学了一段时间感觉没有方向感,不知道该从那里入手去学习,需要一份小编整理出来的学习资料的关注我主页或者点击点击文末微信即可免费领取~
这里是关于我自己的Android 学习,面试文档,视频收集大整理,有兴趣的伙伴们可以看看~
如果你看到了这里,觉得文章写得不错就给个赞呗?如果你觉得那里值得改进的,请给我留言,一定会认真查询,修正不足,谢谢。