Node, Nexmo 및 Firebase 기능을 사용하여 SMS 메시지 전송 및 수신
네가 시작하기 전에
너는 약간의 물건이 있어야만 시작할 수 있으니, 이 두 가지 물건이 모두 준비되었는지 확인하는 데 시간이 좀 걸릴 것이다.
Firebase 설정
첫 번째 단계는 Firebase 프로젝트를 구축하는 것이다.Firebase 콘솔을 사용하여 새 항목을 설정하도록 안내합니다.
Firebase 항목 만들기




Google Cloud Platform (GCP) resource location에 ⚙️ -> Project Settings 설정
Firebase 도구 설치
Firebase를 사용하는 데 필요한 대부분의 작업은 명령줄에서 Firebase가 제공하는 도구 모음을 사용하여 직접 완성할 수 있습니다.
npm install -g firebase-tools
firebase login을 사용하여 Firebase에 로그인합니다.로그인 프로세스는 인증을 위해 브라우저를 엽니다.로컬 환경 설정
Firebase 함수를 작성하려면 초기화 작업이 필요하지만, 주로 Firebase 도구 명령을 사용해서 완성됩니다.
mkdir nexmo-project && cd nexmo-project 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 프로젝트를 만드는 또 다른 옵션입니다.functions 디렉터리로 전환하고 가장 좋아하는 편집기에서 index.js을 열어 코드를 추가합니다.첫 번째 함수 만들기
생성한 첫 번째 함수는 Nexmo에서 전송된 SMS 메시지를 캡처하고 기록하는 웹 훅으로 사용됩니다.
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 웹훅에 필요한 것이다.Firebase 함수는 req.body을 포획하여 실시간 데이터베이스에 로그로 보내는 /msgq 대상입니다.우리가 사용하는 것은
req.body이기 때문에 웹훅은 POST Method이 필요하다.Nexmo webhooks에 GET 메서드를 사용하려면 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에서 웹 훅을 설정하는 데 필요한 것입니다. 다음에 이 동작을 실행할 것입니다.Nexmo 설정
Nexmo 설정에는 명령줄에서 모든 단계를 완료하는 몇 가지 빠른 단계가 있습니다.
npm install -g nexmo-cli
nexmo number:buy --country_code US
nexmo link:sms YOUR_NUMBER YOUR_FUNCTION_URL
프로세스를 완전히 설정하고 새로운 기능을 테스트하여 메시지가 기록될 수 있도록 몇 초의 시간을 주십시오.너의 핸드폰을 잡고 전화번호로 메시지를 보내라.Firebase 콘솔을 열고
database 페이지로 이동하면 다음과 같은 내용을 볼 수 있습니다.
현재 전송된 메시지를 기록하는 방법이 있습니다. 전송된 메시지를 처리하기 위해 함수를 작성할 수 있습니다.
발송 함수 만들기
지금까지 Nexmo 전화 번호에 연결된 Firebase 함수를 만들어 사이트 SMS 메시지를 캡처했습니다.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입니다. 이것은 원시 전화번호입니다. - 이 예에서 당신의 전화번호와 to 번호입니다. 이것은 당신이 구매한 Nexmo 가상 번호입니다.핸드폰 번호와 문자가 생기면 너는 지금 많은 일을 할 수 있다.키워드에 따라 특정한 데이터를 사용하여 응답하거나 다른 시스템으로 전송하거나 우리의 상황에서 원본 메시지를 보내는 검색표를 만들 수 있습니다.
명령줄에서 Firebase 기능 재배치:
firebase deploy --only functions
핸드폰을 들고 메시지를 보내면 You sent the following text: Test message처럼 보이는 답장을 받을 수 있다.총결산
현재, 당신은 이미 이 강좌의 모든 절차를 완성했습니다.Github에서 전체 코드를 볼 수 있습니다.
메시지를 발송하고 수신하는 초기 절차가 이미 완성되었기 때문에 나의 다음 몇 편의 글은 이 개념을 채택하고 이를 문자를 통해 나의 가정 자동화를 제어할 수 있도록 확장할 것이다.나도 네가 무엇을 하려고 하는지 듣고 싶으니 나에게 소식을 보내서 나에게 알려줘.
한층 더 읽다
Reference
이 문제에 관하여(Node, Nexmo 및 Firebase 기능을 사용하여 SMS 메시지 전송 및 수신), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/vonagedev/send-and-receive-sms-messages-with-node-nexmo-and-firebase-functions-k30텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)