使用firebase发送广播消息

参考文档

获取服务器json https://firebase.google.com/docs/cloud-messaging/migrate-v1?hl=zh-cn

demo文档 https://firebase.google.com/docs/cloud-messaging/send-message?hl=zh-cn

为单个token发送消息

func SendMessageToClient(){
    //token某些情况下会失效
    registrationToken :="*******"
    //获取方式 firbase后台 项目设置  服务账户  生成新的私钥
    req:=httplib.Get("******.json")
    req.SetTLSClientConfig(&tls.Config{InsecureSkipVerify:true})
    req.SetTimeout(100*time.Second, 30*time.Second).Response()
    str,_ :=req.String()
    opt :=option.WithCredentialsJSON([]byte(str))
    app, err := firebase.NewApp(context.Background(),nil,opt)
    if err != nil {
        beego.Error("error initializing app: %v\n",err)
        log.Fatalf("error initializing app: %v\n", err)
    }

    ctx := context.Background()
    client, err := app.Messaging(ctx)

    // This registration token comes from the client FCM SDKs.
    notification := &messaging.Notification{
        Title: "this is 测试",
        Body: "测试测试测试测试测试测试测试测试"+time.Now().Format(beego.AppConfig.String("FORMATDATETIME")),
        ImageURL:"http://test-game-cms.onemenagames.com/storage/image/head/hEviuP1fS55sRXxVIhU77fcoOLYvz8ysDZsDKIYA.jpeg",
    }
    message := &messaging.Message{
        //并没有发现有什么作用
        //https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#Message.FIELDS.data
        Data: map[string]string{
            "score": "0001",
            "time":  beego.AppConfig.String("FORMATDATETIME"),
            "back":"china",
        },
        Notification:notification,
        Token: registrationToken,
    }

    // Send a message to the device corresponding to the provided
    // registration token.
    response, err := client.Send(ctx, message)
    if err != nil {
        beego.Error(err)
    }
    // Response is a message ID string.
    fmt.Println("Successfully sent message:", response)


}

向多台设备同时发送消息

借助 Node、Java 和 .NET 版 REST API 与 Admin FCM API,您可以将消息多播到一系列设备注册令牌。每次调用时,您最多可以指定 500 个设备注册令牌

func SendGoogleMessageToClients(jsonUrl string,registrationTokens []models.TabUserPushTokenModel,notic messaging.Notification,data string) bool{
    var tokens []string
//json缓存    cacheKey:=beego.AppConfig.String("REDIS_PREFIX")+"_google_fireBase"+fun.StrMd5(jsonUrl)
    var str string
    if !fun.RedisExistsToRedis(cacheKey){
        req:=httplib.Get(jsonUrl)
        req.SetTLSClientConfig(&tls.Config{InsecureSkipVerify:true})
        req.SetTimeout(100*time.Second, 30*time.Second).Response()
        str,err :=req.String()
        if err!=nil{
            beego.Error("没有找到fiebase json 文件")
            return false
        }else{
            fun.Client.Set(cacheKey,str,0)
        }

    }
    str,err := fun.RedisGettDataToRedis(cacheKey)
    if err!=nil{
        beego.Error("没有找到fiebase json 文件")
        return false
    }

    opt :=option.WithCredentialsJSON([]byte(str))

    app, err := firebase.NewApp(context.Background(),nil,opt)
    if err != nil {
        beego.Error("无效的json文件")
        return false
    }
    ctx := context.Background()
    client, err := app.Messaging(ctx)

    // This registration token comes from the client FCM SDKs.

    // See documentation on defining a message payload.
    var pData map[string]string
    err = json.Unmarshal([]byte(data),&pData)
    if err!=nil{
        beego.Error("无效的data 串")
        return false
    }

    for _,v:=range registrationTokens{
        tokens=append(tokens,v.TokenStr)
    }
    message := &messaging.MulticastMessage{
        Data:pData,
        Notification: &notic,
        Tokens: tokens,
    }
    response, err := client.SendMulticast(ctx, message)
    if err != nil {
        beego.Error("发送失败")
        return false
    }
    beego.Info("推送成功次数"+strconv.Itoa(response.SuccessCount))
    beego.Info("推送失败次数"+strconv.Itoa(response.FailureCount))
    for _,v:=range  response.Responses {
        if !v.Success{
            beego.Info(v.Error)
            beego.Info(v.MessageID)
        }
    }
    // Response is a message ID string.

    return true
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容