星期一, 10月 22, 2018

[FCM] firebase admin 初探筆記: 從backend丟訊息

記錄一下nodejs使用FCM Admin的相關筆記,
主要要透過自已的backend與fcm做溝通,
跟web notification無關。

1. 安裝


npm install firebase-admin --save

2. Firebase開專案


3. 設定金鑰

專案設定頁->點擊服務帳戶的Tab->產生新的私密金鑰



4. 初始化SDK


var admin = require('firebase-admin');
var serviceAccount = require('path/to/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://.firebaseio.com'
});


當然如果不要透過下載.json,也是可以用變數的方式做初始化。


5. 發送訊息 send()

接著就可以透過admin.messaging()內的send方法發送訊息

// The topic name can be optionally prefixed with "/topics/".
var topic = 'highScores';
// See documentation on defining a message payload.
var message = {
  data: {
    score: '850',
    time: '2:45'
  },
  topic: topic};
// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

也可以在send方法內使用測試模式

admin.messaging().send(message, dryRun)

指定條件的訊息

在message也可以加condition

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
// See documentation on defining a message payload.
var message = {
  notification: {
    title: '$GOOG up 1.43% on the day',
    body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  condition: condition};
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

定義訊息

透過fcm可以推播包含webpush/apns(iOS)/android等消息。

一個封裝訊息的欄位參數

参数说明
data键值对映射,其中所有键和值都是字符串。
notification一个包含 title 和 body 字段的对象。
android一个由 Android 消息专用字段组成的对象。要了解详情,请参阅 Android 专用字段
apns一个由 Apple 推送通知服务 (APNS) 专用字段组成的对象。要了解详情,请参阅 APNS 专用字段
webpush一个由 WebPush 协议专用字段组成的对象。要了解详情,请参阅 WebPush 专用字段
token一个用于标识消息的收件人设备的注册令牌。
topic要将消息发送至的主题名称。该主题名称不能包含 /topics/ 前缀。
condition发送消息时所依据的条件,例如 "foo" in topics && "bar" in topics

綜合的訊息

以下是一個主題的推播,並推發到andriod/apns



var message = {
  notification: {
    title: '$GOOG up 1.43% on the day',
    body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
  },
  android: {
    ttl: 3600 * 1000,
    notification: {
      icon: 'stock_ticker_update',
      color: '#f45342',
    },
  },
  apns: {
    payload: {
      aps: {
        badge: 42,
      },
    },
  },
  topic: 'industry-tech'
};

常見授權錯誤

如果你在send訊息出現以下錯誤,

Credential implementation provided to initializeApp() via the \"credential\" property failed to fetch a valid Google OAuth2 access token with the following error

通常都是你目前環境的時間跟FCM的不一致,
只要同步時間就好了,

$>sudo service ntp restart

官方文件
https://firebase.google.com/docs/admin/setup?authuser=2
https://firebase.google.com/docs/cloud-messaging/admin/send-messages?authuser=1

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails