使用 Node、Nexmo 和 Firebase 函数发送和接收短信
Firebase 平台允许开发者快速构建应用程序后端,而且使用起来也非常便捷。在本教程中,我将演示如何使用Nexmo来实现短信功能。完成本教程后,您将能够使用Firebase Functions和 Firestore 以及 Nexmo SMS API创建短信日志并向发件人发送回复。
开始之前
你需要准备一些东西才能开始——所以花点时间确保这两样东西都准备好了。
设置 Firebase
第一步是设置 Firebase 项目。以下步骤将引导您使用 Firebase 控制台设置新项目。
创建 Firebase 项目
- 前往Firebase 控制台
- 点击添加项目
- 添加名称并点击“继续”
- 保持 Google Analytics 启用状态,然后点击继续(非必需)。
- 选择一个 Google Analytics(分析)帐户,然后单击“创建项目”(如果已添加)。
- 请稍等片刻,项目即可创建完成——只需不到一分钟。
- 在“⚙️ -> 使用情况和结算 -> 详细信息和设置”中,将结算类型设置为 Blaze。使用第三方 API 需要选择按需付费方案。有关 Google 结算的更多详细信息,请点击此处。

- 设置
Google Cloud Platform (GCP) resource location⚙️ -> Project Settings
安装 Firebase 工具
使用 Firebase 提供的工具集,您几乎可以直接从命令行完成所有操作。
- 使用 npm 安装 Firebase 工具
npm install -g firebase-tools
- 使用以下命令登录 Firebase
firebase login。登录过程将打开您的浏览器进行身份验证。
设置本地环境
编写 Firebase 函数需要一些初始化工作才能开始,但大部分工作都可以使用 Firebase Tools 命令自动完成。
-
创建项目文件夹
mkdir nexmo-project && cd nexmo-project -
初始化 Firebase Functions
firebase init functions
######## #### ######## ######## ######## ### ###### ########
## ## ## ## ## ## ## ## ## ## ##
###### ## ######## ###### ######## ######### ###### ######
## ## ## ## ## ## ## ## ## ## ##
## #### ## ## ######## ######## ## ## ###### ########
You're about to initialize a Firebase project in this directory:
/your_folders/your-project-name
=== Project Setup
First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add,
but for now, we'll just set up a default project.
? Please select an option: (Use arrow keys)
❯ Use an existing project
Create a new project
Add Firebase to an existing Google Cloud Platform project
Don't set up a default project
由于您已在控制面板中创建了一个项目,您可以选择该选项Use an existing project,系统会提示您选择所需的项目。如果您尚未创建项目,请使用该选项Create a new project并为其指定一个唯一的名称。您仍然需要前往控制台更新位置和账单信息,但这是创建 Firebase 项目的另一种方法。
- 选择您创建的项目名称
- 选择 JavaScript
- 如果需要启用 ESLint,请选择 Y(我推荐启用)。
- 立即安装所有依赖项
这些步骤将创建构建 Firebase Functions 所需的文件夹和文件,并安装所有依赖项。NPM 安装完成后,切换到该functions目录,并index.js使用您喜欢的编辑器打开文件,即可开始添加代码。
创建你的第一个函数
您创建的第一个函数将充当 webhook,用于捕获和记录来自 Nexmo 的传入短信。
文件index.js中提供了一些示例代码,您不需要这些代码。请删除所有内容,然后从头开始添加以下代码。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// Initialize Firebase app for database access
admin.initializeApp();
调用此方法后admin.initializeApp();,函数即可对 Firebase 实时数据库进行读写操作。接下来,请使用以下方法创建您的函数。
// This function will serve as the webhook for incoming SMS messages,
// and will log the message into the Firebase Realtime Database
exports.inboundSMS = functions.https.onRequest(async (req, res) => {
await admin.database().ref('/msgq').push(req.body);
res.send(200);
});
该inboundSMS方法监听 HTTPS 请求——这正是 Nexmo Webhook 所需要的。Firebase 函数会捕获这些请求req.body,并将其/msgq作为日志发送到实时数据库中的对象。
由于我们使用了req.body,因此 webhook 需要是POST Method。如果您更喜欢(或必须)使用GETNexmo webhook 的方法,只需将其替换为req.query,GET 方法的工作方式将相同。
现在你已经编写了一些代码,请务必保存文件并将函数部署到 Firebase:
firebase deploy --only functions
=== Deploying to 'nexmo-project'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions@ lint /Users/kellyjandrews/Google Drive/Apps/nexmo-project/functions
> eslint .
✔ functions: Finished running predeploy script.
i functions: ensuring necessary APIs are enabled...
✔ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (38.78 KB) for uploading
✔ functions: functions folder uploaded successfully
i functions: creating Node.js 8 function inboundSMS(us-central1)...
✔ functions[inboundSMS(us-central1)]: Successful create operation.
Function URL (inboundSMS): https://us-central1-nexmo-project.cloudfunctions.net/inboundSMS
✔ Deploy complete!
Project Console: https://console.firebase.google.com/project/nexmo-project/overview
输出结果中最关键的部分是Function URL (inboundSMS)。此 URL 是 Nexmo 中设置 webhook 所必需的,您接下来将进行此操作。
设置 Nexmo
设置 Nexmo 只需几个简单的步骤——所有步骤均可通过命令行完成。
- 安装 CLI
npm install -g nexmo-cli
- 请从控制面板https://dashboard.nexmo.com/getting-started-guide使用您的 API 密钥和密钥设置 CLI。
- 购买一个新的电话号码
nexmo number:buy --country_code US
- 此命令会检索美国境内第一个可用的电话号码。有关 Nexmo 号码的更多信息,您可以查看[号码文档]( https://developer.nexmo.com/numbers/overview )。
- 输入确认,然后复制号码
- 使用此命令将电话号码链接到 webhook。
nexmo link:sms YOUR_NUMBER YOUR_FUNCTION_URL
请等待几秒钟让该过程完全完成配置,然后测试新功能,确保消息已被记录。
拿起手机,向该号码发送一条消息。打开 Firebase 控制台并导航到相应database页面,您应该会看到类似这样的内容:
既然现在可以记录传入的消息,就可以编写一个函数来处理传入的消息。
创建发送函数
目前,您已经创建了一个与 Nexmo 电话号码关联的 Firebase 函数,用于捕获收到的短信。Firebase 函数还可以响应数据库更新。当有新条目时,代码会发送原始文本的回显。
首先将 Nexmo 添加到依赖项列表中 - 请确保在以下目录中执行此操作functions:
npm i nexmo --save
将以下环境变量添加到 Firebase 配置中
firebase functions:config:set nexmo.api_key="YOUR_KEY" nexmo.api_secret="YOUR_SECRET"
接下来,打开index.js顶部nexmo的“需求”部分,并导入环境变量以初始化 Nexmo:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const Nexmo = require('nexmo');
// Initialize Firebase app for database access
admin.initializeApp();
// get Firebase environment variables for Nexmo
const {
api_key,
api_secret
} = functions.config().nexmo;
// Initialize Nexmo with application credentials
const nexmo = new Nexmo({
apiKey: api_key,
apiSecret: api_secret
});
现在您可以为 Firebase 创建一个新函数来发送响应:
// This function listens for updates to the Firebase Realtime Database
// and sends a message back to the original sender
exports.sendSMS = functions.database.ref('/msgq/{pushId}')
.onCreate((message) => {
const { msisdn, text, to } = message.val();
// the incoming object - 'msisdn' is the your phone number, and 'to' is the Nexmo number
// nexmo.message.sendSms(to, msisdn, text);
return nexmo.message.sendSms(to, msisdn, `You sent the following text: ${text}`, (err, res) => {
if (err) {
console.log(err);
} else {
if (res.messages[0]['status'] === "0") {
console.log("Message sent successfully.");
} else {
console.log(`Message failed with error: ${res.messages[0]['error-text']}`);
}
}
})
});
新功能将监听/msgq数据库对象中新增的消息。触发后,完整的 Nexmo 对象将作为参数传递message。该对象包含msisdn`<original phone number>`(即原始电话号码,在本例中为您的电话号码)和 `<number>` to(即您购买的 Nexmo 虚拟号码)。
有了电话号码和短信内容,你现在可以做很多事情。你可以创建一个查找表,根据关键词回复特定数据,转发到另一个系统,或者像我们这里一样,发送原始短信。
从命令行再次部署 Firebase Functions:
firebase deploy --only functions
拿起手机,再发一条消息,然后你应该会收到类似这样的回复You sent the following text: Test message。
包起来
您已完成本教程的所有步骤。您可以在Github上查看完整代码。
现在收发短信的初步步骤已经完成,接下来的几篇文章我将以此为基础,进一步拓展这个概念,实现通过短信控制部分智能家居设备。我也很想知道你们的计划,欢迎在推特上给我留言告诉我。
延伸阅读
- 请访问https://developer.nexmo.com查看开发者文档。
- 关于 Nexmo 短信功能的详细信息:https://developer.nexmo.com/messaging/sms/overview
- Firebase Functions 入门指南https://firebase.google.com/docs/functions/get-started
本文《使用 Firebase 函数发送和接收短信》最初发表于Nexmo 开发者博客。
文章来源:https://dev.to/vonagedev/send-and-receive-sms-messages-with-node-nexmo-and-firebase-functions-k30



