Ray Lee | 李宗叡
Learn or Die
Published in
4 min readJul 23, 2024

--

# 前言

紀錄 Laravel 實作 發送 FCM message 到 Android & iOS 端

# 套件

使用 Laravel FCM Channel

# Firebase 設定

在 Firebase 上要建立應用程式,如果要傳送到 Android 裝置,那就要建立 Android 應用程式,iOS 也是相同

# Android

從 console 點擊 建立 Android 應用程式,如下圖

Android 端會給你

  • Android 套件名稱
  • SHA-1

輸入後,直接下一步,就可以下載 Android 端用的 configuration file,下載後交給 Android 端就可以了

# iOS

iOS 的東西比較多一點

首先也是 建立 iOS 應用程式

iOS 端會給你

  • bundle id
  • team id
  • key id
  • Auth_key.p8 file

bundle id 就是上圖中的 APP 軟體包 ID

接著一樣下一步,步驟跟 Android 差不多,可以下載 configuration file,下載後交給 iOS

接著要到 雲端通訊 區塊,如下圖

這邊必須 上傳 APN 驗證金鑰,點擊後如下圖

然後就依序的輸入上面有提到的

  • Auth_key.p8 file
  • key id
  • team id

這邊要設定完畢才算完成,否則 FCM message 是發不到 iOS 端的

# Laravel Notification

Notification for FCM 設定詳見套件教學,不多加贅述。

這邊主要紀錄的是 發給 iOS 端 & Android 端的格式

格式與需求息息相關,此次的需求情境如下:

  • 要做多語系,當使用者的手機是英文語系,收到 FCM 時要顯示英文,同理收到中文也要顯示中文
  • 使用者收到 Pop up message 之後,可以點擊訊息,點擊後跳往到指定頁面

根據上面的需求情境,我們團隊先將 key 定義出來。當事件發生時,後端只丟 key 給 Mobile 端,Mobile 端會根據 key & device locale 來顯示對應的訊息,所以後端需要傳給 Mobile 端的關鍵欄位如下:

  • 跳出在螢幕上的內容標題 (custom_title_key)
  • 跳出在螢幕上的訊息內容 (custom_body_key)
  • 點擊後要跳往的目的連結 (custom_destination)
<?php
public function toFcm($notifiable): FcmMessage
{
return (new FcmMessage())->custom([
'android' => [
"priority" => "high",
"data" => [
"title_loc_key" => 'custom_title_key',
"body_loc_key" => 'custom_body_key',
"destination" => 'custom_destination',
// "body_loc_args" => json_encode(["customArg1", "customArg2"]),
],
],
'apns' => [
"payload" => [
'aps' => [
'alert' => [
'title-loc-key' => 'custom_title_key',
'loc-key' => 'custom_body_key',
// 'subtitle-loc-key' => 'custom-key',
],
"sound" => "default",
],
"destination" => 'custom_destination'
]
]
]);
}

上面的 custom_title_key & custom_body_key & custom_destination 跟 Mobile 端商量好就行,key 是固定不可變更的,但 value 可以,也就是說 title_loc_key 那些是 OS 預設的,不可變動的,但其 value custom_title_key 是可以變動的

--

--

Ray Lee | 李宗叡
Learn or Die

It's Ray. I do both backend and frontend, but more focus on backend. I like coding, and would like to see the whole picture of a product.