Skip to content

Commit

Permalink
Merge pull request #3 from darron1217/timestamp
Browse files Browse the repository at this point in the history
timestamp를 sms발송시점에 생성하도록 변경
  • Loading branch information
bumkeyy authored Nov 16, 2020
2 parents 58ffe08 + bc1c631 commit 9bdb2e3
Showing 1 changed file with 36 additions and 21 deletions.
57 changes: 36 additions & 21 deletions src/ncp_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ export type sendSMSReturnType = {
status: number;
};

export type prepareSignatureReturnType = {
timestamp: string;
signature: string;
};

export class NCPClient {
private phoneNumber: string;
private serviceId: string;
Expand All @@ -28,8 +33,6 @@ export class NCPClient {

private url: string;
private method: string;
private signature: string;
private timestamp: string;

/**
*
Expand All @@ -50,24 +53,7 @@ export class NCPClient {
this.secretKey = secretKey;
this.accessKey = accessKey;
this.url = `https://sens.apigw.ntruss.com/sms/v2/services/${this.serviceId}/messages`;
this.timestamp = Date.now().toString();
this.method = 'POST';

const space = ' ';
const newLine = '\n';
const message = [];
const hmac = crypto.createHmac('sha256', this.secretKey);
const url2 = `/sms/v2/services/${this.serviceId}/messages`;

message.push(this.method);
message.push(space);
message.push(url2);
message.push(newLine);
message.push(this.timestamp);
message.push(newLine);
message.push(this.accessKey);

this.signature = hmac.update(message.join('')).digest('base64');
}

/**
Expand All @@ -87,14 +73,15 @@ export class NCPClient {
countryCode = '82'
}: sendSMSType): Promise<sendSMSReturnType> {
try {
const {timestamp, signature} = this.prepareSignature()
const response = await axios({
method: 'POST',
url: this.url,
headers: {
'Content-Type': 'application/json; charset=utf-8',
'x-ncp-iam-access-key': this.accessKey,
'x-ncp-apigw-timestamp': this.timestamp,
'x-ncp-apigw-signature-v2': this.signature,
'x-ncp-apigw-timestamp': timestamp,
'x-ncp-apigw-signature-v2': signature,
},
data: {
type: 'SMS',
Expand Down Expand Up @@ -131,4 +118,32 @@ export class NCPClient {
};
}
}

/**
*
* API 시그니처를 생성하는 함수
*
* @returns timestamp(string), signature(string)
*/
private prepareSignature(): prepareSignatureReturnType {
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);

return {
timestamp,
signature: hmac.update(message.join('')).digest('base64')
};
}
}

0 comments on commit 9bdb2e3

Please sign in to comment.