Daily_Study_Checker(2) - SENSE 사용, Server 생성

오경찬·2023년 1월 4일
0

데일리체커

목록 보기
2/2

SENSE 사용

NCP설정은 저번에 해주었으니 이번에는 SENSE가 잘 작동되는지 테스트 해보도록 하자

SMS설정을 마쳐준후 확인버튼을 눌러준다

문자가 잘발송되는것을 알수가 있다!!

Server 생성

NCP에서 API를 호출하기 위해서 header에 인증을 해줘야한다.
네이버 API 호출 가이드를 따라서 작성을 해보자!!

네이버 인증헤더 구성

네이버 API 가이드 예제코드

네이버에 있는 예제코드를 활용하여 express서버를 생성하기로 하였다.

async function send_message(username,phone) {
  let user_phone_number = phone; //수신 전화번호 기입
  let user_name = username
  let resultCode = 404;
  const my_number = '';
  const date = Date.now().toString();
  const options = {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    };
  let createdDate = new Date().toLocaleString('ko-KR', options);
  const uri = process.env.NCP_API_SERVICE_ID_KEY; //서비스 ID
  const secretKey = process.env.NCP_SECRET_KEY; // Secret Key
  const accessKey = process.env.NCP_API_ACCESS_KEY; //Access Key
  const method = 'POST';
  const space = ' ';
  const newLine = '\n';
  const url = `https://sens.apigw.ntruss.com/sms/v2/services/${uri}/messages`;
  const url2 = `/sms/v2/services/${uri}/messages`;


  const hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secretKey);
  hmac.update(method);
  hmac.update(space);
  hmac.update(url2);
  hmac.update(newLine);
  hmac.update(date);
  hmac.update(newLine);
  hmac.update(accessKey);
  
  const hash = hmac.finalize();
  const signature = hash.toString(CryptoJS.enc.Base64);
  axios({
    method: method,
    // // request는 uri였지만 axios는 url이다
    url: url,
    headers: {
      'Contenc-type': 'application/json; charset=utf-8',
      'x-ncp-iam-access-key': accessKey,
      'x-ncp-apigw-timestamp': date,
      'x-ncp-apigw-signature-v2': signature,
    },
    // request는 body였지만 axios는 data다
    data: {
      type: 'SMS',
      countryCode: '82',
      from: my_number,
      // 원하는 메세지 내용
      content: `${user_name}${createdDate}출석 완료입니다.`,
      messages: [
        // 신청자의 전화번호
        { to: `${user_phone_number}` },
      ],
    },
  })
    .then((res) => {
      console.log(res.status);
    })
    .catch((err) => {
      console.log(err);
    });
  return resultCode;
}

예제코드를 활용하여 기본틀을 작성하고 axios를 활용하여 네이버 API에 요청을 보내도록 작성하였다.

postman으로 잘 작동되는지 요청을 보내보았다.

휴대폰으로도 메세지가 잘온다.
localhost -> 네이버 API -> 휴대폰으로 문자 오는 형식으로 작동 된것이다!
다음번에는 EC2나 Lambda에 올려서 실행을 해볼예정이다!

profile
코린이 입니당 :)

0개의 댓글