使用firebase發(fā)送廣播消息

參考文檔

獲取服務(wù)器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

為單個(gè)token發(fā)送消息

func SendMessageToClient(){
    //token某些情況下會(huì)失效
    registrationToken :="*******"
    //獲取方式 firbase后臺(tái) 項(xiàng)目設(shè)置  服務(wù)賬戶  生成新的私鑰
    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 測(cè)試",
        Body: "測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試"+time.Now().Format(beego.AppConfig.String("FORMATDATETIME")),
        ImageURL:"http://test-game-cms.onemenagames.com/storage/image/head/hEviuP1fS55sRXxVIhU77fcoOLYvz8ysDZsDKIYA.jpeg",
    }
    message := &messaging.Message{
        //并沒(méi)有發(fā)現(xiàn)有什么作用
        //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)


}

向多臺(tái)設(shè)備同時(shí)發(fā)送消息

借助 Node、Java 和 .NET 版 REST API 與 Admin FCM API,您可以將消息多播到一系列設(shè)備注冊(cè)令牌。每次調(diào)用時(shí),您最多可以指定 500 個(gè)設(shè)備注冊(cè)令牌

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("沒(méi)有找到fiebase json 文件")
            return false
        }else{
            fun.Client.Set(cacheKey,str,0)
        }

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

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

    app, err := firebase.NewApp(context.Background(),nil,opt)
    if err != nil {
        beego.Error("無(wú)效的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("無(wú)效的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("發(fā)送失敗")
        return false
    }
    beego.Info("推送成功次數(shù)"+strconv.Itoa(response.SuccessCount))
    beego.Info("推送失敗次數(shù)"+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
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容