기억은 짧고 기록은 길다
NCP-SENS를 이용하여 SMS 발송 API 구현하기 #2 본문
Intro
프로젝트를 Node.js로 진행했기 때문에 Node.js로 구현한 SENS API를 기반으로 포스팅을 해보겠다.
1. ncp_config.js
const sensSecret = {
phoneNumber: 발신번호 등록에서 등록한 전화번호,
serviceId: 프로젝트의 서비스 ID,
accessKey: 인증키 관리 > Access Key ID,
secretKey: 인증키 관리 > Secret Key,
}
module.exports = {
sensSecret,
}
2. ncp_client.js
해당 링크를 참고하여 코드를 이해한 후 사용하기 바란다.
SMS API - SENS
api.ncloud-docs.com
const axios = require("axios");
const crypto = require("crypto");
class NCPClient {
constructor(options) {
const { phoneNumber, serviceId, secretKey, accessKey } = options;
this.phoneNumber = phoneNumber;
this.serviceId = serviceId;
this.secretKey = secretKey;
this.accessKey = accessKey;
this.url = `https://sens.apigw.ntruss.com/sms/v2/services/${this.serviceId}/messages`;
this.method = "POST";
}
async sendSMS({ to, content, countryCode = "82" }) {
try {
const { timestamp, signature } = this.prepareSignature();
const response = await axios({
method: this.method,
url: this.url,
headers: {
"Content-Type": "application/json; charset=utf-8",
"x-ncp-apigw-timestamp": timestamp,
"x-ncp-iam-access-key": this.accessKey,
"x-ncp-apigw-signature-v2": signature,
},
data: {
type: "SMS",
contentType: "COMM",
countryCode,
from: this.phoneNumber,
content,
messages: [
{
to: `${to}`,
},
],
},
});
if (response.status === 202) {
return {
success: true,
status: response.status,
msg: response.statusText,
};
} else {
return {
success: false,
status: response.status,
msg: response.statusText,
};
}
} catch (error) {
return {
success: false,
msg: error.response.statusText || "Internal Server Error",
status: error.response.status || 500,
};
}
}
prepareSignature() {
const space = " ";
const newLine = "\n";
const message = [];
const hmac = crypto.createHmac("sha256", this.secretKey);
const url2 = `/sms/v2/services/${this.serviceId}/messages`;
const timestamp = Date.now().toString();
message.push(this.method);
message.push(space);
message.push(url2);
message.push(newLine);
message.push(timestamp);
message.push(newLine);
message.push(this.accessKey);
const signature = hmac.update(message.join("")).digest("base64");
return {
timestamp,
signature,
};
}
}
module.exports = {
NCPClient,
};
3. Controller.js
const { NCPClient } = require("ncp_client");
const sensKey = require("ncp_config").sensSecret;
// 랜덤 인증번호 생성 함수
function createAuthNum() {
const randNum = Math.floor(Math.random() * 9000) + 1000;
return randNum;
}
/**
* API Name : ncp-sens test
* [POST] /sens/test
*/
exports.sensTest = async function (req, res) {
const sendAuth = createAuthNum();
const ncp = new NCPClient({
...sensKey,
});
const to = ""; // 문자를 보낼 전화번호 (숫자만)
const content = `[당근마켓] 인증번호 [${sendAuth}]`;
const { success, status, msg } = await ncp.sendSMS({
to,
content,
});
if (!success) {
console.log(
`(ERROR) node-sens error: ${msg}, Status ${status} Date ${Date.now()}`
);
res.send("SMS 전송 중 오류가 발생했습니다.");
} else {
console.log(success);
console.log(status);
console.log(msg);
return res.send(response(baseResponse.SUCCESS));
};
...
<output>
true
202
Accepted
4. Route.js
module.exports = function (app) {
const controller = require("Controller");
// sens-test API
app.post("/sens/test", controller.sensTest);
};
5. Test
이 글을 보고 그대로 SENS API를 해결할 수 있겠지만 첨부된 링크를 통해 코드를 이해한 뒤 사용하기를 바란다!!
참조
'Node.js' 카테고리의 다른 글
[Node.js] nodemailer로 이메일 보내기 (0) | 2021.08.26 |
---|---|
카카오 local 주소검색 API를 사용해서 주소를 주고 위도, 경도를 받아보자 (0) | 2021.08.15 |
NCP-SENS를 이용하여 SMS 발송 API 구현하기 #1 (0) | 2021.08.12 |
Comments