• Home
  • About
    • lahuman photo

      lahuman

      열심히 사는 아저씨

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

NAVER CLOUD PLATFORM API를 Typescript 기반에서 사용하기

21 Dec 2020

Reading time ~1 minute

NAVER CLOUD PLATFORM API를 Typescript 기반에서 사용하기

회사의 메일 발송은 NAVER CLOUD PLATFORM API를 이용하고 있습니다.

NAVER CLOUD PLATFORM API를 참조하면 인증키를 생성해서 API를 호출 해야 합니다.

자바를 사용할 경우 쉽게 만들수 있는데, javascript 버젼의 경우 CryptoJS v3.1.2를 사용하는 가이드를 주고 있습니다.

문제는 nodejs기반에선는 CryptoJS v3.1.2보다는 crypto-js를 많이 사용합니다.

다음 코드는 crypto-js를 사용해서 NAVER CLOUD PLATFORM API를 연동한 예제 입니다.

메일 발송 예제

import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common';
import { SendMailDto } from './dto/sendmail.dto';
import { MailResultDto } from './dto/mailresult.dto';
import CryptoJS = require("crypto-js");
import Base64 = require('crypto-js/enc-base64');
import { HttpService } from "@nestjs/common";

@Injectable()
export class MailService {
  constructor(private httpService: HttpService) { }

  private makeSignature(timestamp: string): string {
    const space = " ";				// one space
    const newLine = "\n";				// new line
    const method = "POST";				// method
    const url = "/api/v1/mails";	// url (include query string)
    // const timestamp = new Date().getTime();			// current timestamp (epoch)
    const accessKey = process.env.MAIL_ACCESS_KEY;			// access key id (from portal or Sub Account)
    const secretKey = process.env.MAIL_SECRET_KEY;			// secret key (from portal or Sub Account)
    let baseSignature = (method);
    baseSignature += (space);
    baseSignature += (url);
    baseSignature += (newLine);
    baseSignature += (timestamp);
    baseSignature += (newLine);
    baseSignature += (accessKey);

    const hmac = CryptoJS.HmacSHA256(baseSignature, secretKey);
    return Base64.stringify(hmac);
  }

  public async sendMail(sendMailDto: SendMailDto): Promise<MailResultDto> {
    const timestamp: string = new Date().getTime().toString();
    return this.httpService.post('https://mail.apigw.ntruss.com/api/v1/mails', sendMailDto, {
      headers: {
        "x-ncp-apigw-timestamp": timestamp,
        "x-ncp-iam-access-key": process.env.MAIL_ACCESS_KEY,
        "x-ncp-apigw-signature-v2": this.makeSignature(timestamp),
        "Content-Type": "application/json"
      }
    }).toPromise().then(({ data }) => data)
      .catch(e => {
        this.logger.error(e);
        throw new HttpException("Bad Request.", HttpStatus.BAD_REQUEST);
      });
  }
}

crypto-js를 Typescript 기반에서 사용할때 주의할 것은, import 방식을 다음과 같이 사용하여야 합니다.

import CryptoJS = require("crypto-js");
import Base64 = require('crypto-js/enc-base64');

어렵고도쉬운문제

참고자료

  • NAVER CLOUD PLATFORM API
  • crypto-js with npm
  • crypto-js with google
  • TypeError: sha256_1.default is not a function


naverapitypescript Share Tweet +1