Firebase 推播訊息 的第二篇文章是在說明當 Firebase 專案建立完成之後,如何利用Nodejs和專案裡的金鑰將message推播出去
本篇會先介紹如何建立一個Nodejs專案,再介紹如何透過程式將訊息推播出去。
- 首先建立一個sendMsg的資料夾
mkdir sendMsg
2. 進入sendMsg 資料夾後執行npm init
cd sendMsg
npm init
3. 接下來一直按enter會出現下列command,最後輸入yes
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (sendmsg)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\exampleProject\sendMsg\package.json:
{
"name": "sendmsg",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)
4. 再來直接在command line 直接輸入code . ,vscode會直接開啟資料夾,或是開啟vscode再引入sendMsg資料夾也可以,目的是要開啟sendMsg資料夾
5. 在sendMsg資料夾內新增index.js
6. 再新增key.json,將剛才firebase的私密金鑰內容完整的貼進來
7. 再來我們要在資料夾內安裝需要的npm
npm i https googleapis -s
8. 之後在index.js輸入下列程式碼
const https = require('https')
var {google} = require('googleapis')
const key = require('./key.json')
const PROJECT_ID = key.project_id;
const HOST = 'fcm.googleapis.com';
const PATH = '/v1/projects/' + PROJECT_ID + '/messages:send';
const MESSAGING_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
const SCOPES = [MESSAGING_SCOPE];
function getAccessToken() {
return new Promise(function(resolve, reject) {
const jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
SCOPES,
null
)
jwtClient.authorize(function(err, tokens) {
if (err) {
reject(err);
return;
}
resolve(tokens.access_token);
});
});
}
/**
* Send HTTP request to FCM with given message.
*
* @param {object} fcmMessage will make up the body of the request.
*/
function sendFcmMessage (fcmMessage) {
getAccessToken().then(function(accessToken) {
const options = {
hostname: HOST,
path: PATH,
method: 'POST',
// [START use_access_token]
headers: {
'Authorization': 'Bearer ' + accessToken
}
// [END use_access_token]
};
const request = https.request(options, function(resp) {
resp.setEncoding('utf8');
resp.on('data', function(data) {
console.log('Message sent to Firebase for delivery, response:');
console.log(data);
});
});
request.on('error', function(err) {
console.log('Unable to send message to Firebase');
console.log(err);
});
request.write(JSON.stringify(fcmMessage));
request.end();
});
}
/**
* Construct a JSON object that will be used to define the
* common parts of a notification message that will be sent
* to any app instance subscribed to the news topic.
*/
function buildCommonMessage() {
return {
'message': {
'topic': 'all',
'notification': {
'title': 'FCM Notification',
'body': 'Notification from FCM',
}
}
};
}
const commonMessage = buildCommonMessage();
console.log('FCM request body for message using common notification object:');
console.log(JSON.stringify(commonMessage, null, 2));
sendFcmMessage(buildCommonMessage());
9. 完成之後,要用node 去執行index.js的程式發送message,在command line下輸入:
node index.js
10. command line就會出現
FCM request body for message using common notification object:
{
"message": {
"topic": "all",
"notification": {
"title": "FCM Notification",
"body": "Notification from FCM",
}
}
}
Message sent to Firebase for delivery, response:
{
"name": "projects/test-18a9a/messages/2560468080093694458"
}
11. 依照firebase官方文件,response出現下列文字就是正常可以發送
{
"name": "projects/test-18a9a/messages/2560468080093694458"
}
參考文件
就如之前所說明的,此方式是針對topic推播訊息,如果需要針對應用程式,就要先將FCM TOKEN全部記錄下來。