iT邦幫忙

2024 iThome 鐵人賽

DAY 17
2
Mobile Development

從零開始以Flutter打造跨平台聊天APP系列 第 17

Day-17 使用 Go 透過 Firebase Cloud Message 發送推播通知

  • 分享至 

  • xImage
  •  

Generated from Stable Diffusion 3 Medium

昨天的教學中提到了如何透過 Firebase Cloud Messaging (FCM) 實現推播通知,並在 Firebase 的網頁中發訊息給 Flutter APP。

為了讓我們未來的伺服器可以針對特定的裝置發送訊息,我們可以自己架設 server,並透過 Firebase 提供的 API 推送訊息。這次實作我們使用 firbase 提供的 Golang 套件 https://pkg.go.dev/firebase.google.com/go/v4

安裝 SDK

go get firebase.google.com/go/v4@latest

為了初始化 Firebase,我們需要有 Google Application Default Credentials,至於要怎麼取得這個神祕金鑰呢?我們可以進入 Firebase 的控制台 (console) > 專案設定 > 服務帳戶 > 產生新的私密金鑰。接著就可以得到一個 json 檔,只要給予 json 檔路徑便可讓 Firebase 取得金鑰

取得私密金鑰

import (
	"context"
	"fmt"
	"log"

	firebase "firebase.google.com/go/v4"
	"firebase.google.com/go/v4/messaging"
	"google.golang.org/api/option"
)

func initializeFirebase() *firebase.App {
	opt := option.WithCredentialsFile("path/to/serviceAccountKey.json")
	app, err := firebase.NewApp(context.Background(), nil, opt)
	if err != nil {
		panic(fmt.Errorf("error initializing app: %v", err))
		// return nil,
	}
	return app
}

使用 app.Messaging 發送訊息

初始化後,我們可以直接發送訊息,其中 registrationToken (註冊權杖),可以由前一篇教學中針對不同裝置取得。message 中可以放入 Data 和 Notification,其中 Notification 的部分與昨天的 Demo 類似。最後使用 client.Sendmessage 發出。相關的設定可以參考官方文檔:https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages

const registrationToken = "caY...LC7"

func main() {
	app := initializeFirebase()
	// Obtain a messaging.Client from the App.
	ctx := context.Background()
	client, err := app.Messaging(ctx)
	if err != nil {
		log.Fatalf("error getting Messaging client: %v\n", err)
	}

	// See documentation on defining a message payload.
	message := &messaging.Message{
		Data: map[string]string{
			"score": "850",
			"time":  "2:45",
		},
		Notification: &messaging.Notification{
			Title:    "徒町小铃",
			Body:     "ちぇすとー!",
			ImageURL: "https://raw.githubusercontent.com/ksw2000/ironman-2024/master/golang-server/push_notification/push_image.png",
		},
		Token: registrationToken,
	}

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

昨天 Demo 沒有加入圖片,今天 Demo 把圖片加進來

針對 Android 裝置圖片不得超過 1MB

省電模式或震動模式可能會影響圖片載入

範例圖片:

最終成果:

Web 背景通知

Web背景通知

Web 前景通知

Web前景通知

Android 後景與前景通知

Android 通知

btw. 鎖定螢幕是楡井希実


後記:今天只有教 Go 耶 (雖然還是改了一下昨天的 flutter)


上一篇
Day-16 在 Flutter 中使用推播通知 Firebase Cloud Messaging
下一篇
Day-18 在 Flutter 中使用 pointycastle 進行端對端加密
系列文
從零開始以Flutter打造跨平台聊天APP25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言