coolsms-node-sdk
Version:
CoolSMS SDK for Node.js(Server Side Only)
417 lines (385 loc) • 16.8 kB
JavaScript
var $cl6Iw$datefns = require("date-fns");
var $cl6Iw$imagetobase64 = require("image-to-base64");
var $cl6Iw$crossfetch = require("cross-fetch");
var $cl6Iw$nanoid = require("nanoid");
var $cl6Iw$cryptojs = require("crypto-js");
var $cl6Iw$url = require("url");
function $parcel$interopDefault(a) {
return a && a.__esModule ? a.default : a;
}
function $parcel$defineInteropFlag(a) {
Object.defineProperty(a, '__esModule', {value: true, configurable: true});
}
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
$parcel$defineInteropFlag(module.exports);
$parcel$export(module.exports, "default", () => $123f4982a51872b4$export$2e2bcd8739ae039);
var $512d3982934257c9$exports = {};
$512d3982934257c9$exports = JSON.parse("{\"version\":\"nodejs/2.0.0\"}");
class $96e7409d4de0ba31$export$7522646e65a7a5d1 extends Error {
constructor(message){
super(message);
this.name = 'InvalidDateError';
}
}
class $96e7409d4de0ba31$export$6efc4418efdbd5bb extends Error {
constructor(message){
super(message);
this.name = 'InvalidApiKeyError';
}
}
class $96e7409d4de0ba31$export$c73ca302efeda3b4 extends Error {
constructor(errorCode, errorMessage){
super(errorMessage);
this.name = errorCode;
}
}
function $551d0f39d46708b0$export$2e2bcd8739ae039(value) {
if (typeof value === 'string') {
value = $cl6Iw$datefns.parseISO(value);
const invalidDateText = 'Invalid Date';
if (value.toString() === invalidDateText) throw new $96e7409d4de0ba31$export$7522646e65a7a5d1(invalidDateText);
}
return value;
}
const $7467382afc84c32e$export$fb47e5c0b633ea53 = {
sdkVersion: $512d3982934257c9$exports.version,
osPlatform: `${process.platform} | ${process.version}`
};
class $7467382afc84c32e$var$DefaultMessageRequest {
constructor(){
this.agent = $7467382afc84c32e$export$fb47e5c0b633ea53;
this.allowDuplicates = false;
}
}
class $7467382afc84c32e$export$ad3dca884a810e33 extends $7467382afc84c32e$var$DefaultMessageRequest {
constructor(message, allowDuplicates, appId){
super();
this.message = message;
if (typeof allowDuplicates === 'boolean') this.allowDuplicates = allowDuplicates;
if (appId) this.appId = appId;
}
}
class $7467382afc84c32e$export$b4becc1d7edb915a extends $7467382afc84c32e$var$DefaultMessageRequest {
constructor(messages, allowDuplicates, appId){
super();
this.messages = messages;
if (typeof allowDuplicates === 'boolean') this.allowDuplicates = allowDuplicates;
if (appId) this.appId = appId;
}
}
class $7467382afc84c32e$export$6ba9c27a351bdec2 {
constructor(messages){
this.messages = messages;
}
}
class $7467382afc84c32e$export$d88a1c09ffb9e02d {
constructor(getMessageRequestType){
var ref;
this.dateType = 'CREATED';
this.startKey = getMessageRequestType.startKey;
this.limit = getMessageRequestType.limit;
if ((ref = getMessageRequestType.duration) === null || ref === void 0 ? void 0 : ref.dateType) this.dateType = getMessageRequestType.duration.dateType;
if (getMessageRequestType.duration) this.startDate = $cl6Iw$datefns.formatISO($551d0f39d46708b0$export$2e2bcd8739ae039(getMessageRequestType.duration.startDate));
if (getMessageRequestType.duration) this.endDate = $cl6Iw$datefns.formatISO($551d0f39d46708b0$export$2e2bcd8739ae039(getMessageRequestType.duration.endDate));
this.messageId = getMessageRequestType.messageId;
this.messageIds = getMessageRequestType.messageIds;
this.groupId = getMessageRequestType.groupId;
this.to = getMessageRequestType.to;
this.from = getMessageRequestType.from;
this.type = getMessageRequestType.type;
this.statusCode = getMessageRequestType.statusCode;
}
}
class $7467382afc84c32e$export$4fede39aef110b5c {
constructor(getStatisticsRequest){
if (getStatisticsRequest.duration) this.startDate = $cl6Iw$datefns.formatISO($551d0f39d46708b0$export$2e2bcd8739ae039(getStatisticsRequest.duration.startDate));
if (getStatisticsRequest.duration) this.endDate = $cl6Iw$datefns.formatISO($551d0f39d46708b0$export$2e2bcd8739ae039(getStatisticsRequest.duration.endDate));
this.masterAccountId = getStatisticsRequest.masterAccountId;
}
}
let $7b1a054c0937d4c0$var$AuthenticateType;
(function(AuthenticateType) {
AuthenticateType[AuthenticateType["API_KEY"] = 0] = "API_KEY";
})($7b1a054c0937d4c0$var$AuthenticateType || ($7b1a054c0937d4c0$var$AuthenticateType = {
}));
function $7b1a054c0937d4c0$export$2e2bcd8739ae039(authenticationParameter, authType = $7b1a054c0937d4c0$var$AuthenticateType.API_KEY) {
const { apiKey: apiKey , apiSecret: apiSecret } = authenticationParameter;
switch(authType){
case $7b1a054c0937d4c0$var$AuthenticateType.API_KEY:
default:
const salt = $cl6Iw$nanoid.customAlphabet('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 32)();
const date = $cl6Iw$datefns.formatISO(new Date());
const hmacData = date + salt;
if (!apiKey || !apiSecret || apiKey === '' || apiSecret === '') throw new $96e7409d4de0ba31$export$6efc4418efdbd5bb('Invalid API Key Error');
const signature = $cl6Iw$cryptojs.HmacSHA256(hmacData, apiSecret).toString();
return `HMAC-SHA256 apiKey=${apiKey}, date=${date}, salt=${salt}, signature=${signature}`;
}
}
async function $f24672c3715df8a1$export$2e2bcd8739ae039(authParameter, request, data) {
const authorizationHeaderData = $7b1a054c0937d4c0$export$2e2bcd8739ae039(authParameter);
return await ($parcel$interopDefault($cl6Iw$crossfetch))(request.url, {
headers: {
'Authorization': authorizationHeaderData,
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
method: request.method
}).then(async (res)=>{
if (res.status >= 400 && res.status < 500) {
const errorResponse = await res.json();
throw new $96e7409d4de0ba31$export$c73ca302efeda3b4(errorResponse.errorCode, errorResponse.errorMessage);
} else if (res.status >= 500) {
const responseText = await res.text();
throw new $96e7409d4de0ba31$export$c73ca302efeda3b4('UnknownException', responseText);
}
try {
return res.json();
} catch (exception) {
throw new Error(await res.text());
}
});
}
function $ff8f5d4d31c52cf4$export$2e2bcd8739ae039(url, data) {
const apiUrl = new $cl6Iw$url.URL(url);
if (data) {
const urlSearchParams = new $cl6Iw$url.URLSearchParams();
Object.keys(data).forEach((key)=>{
const reflectedValue = Reflect.get(data, key);
if (reflectedValue) urlSearchParams.append(key, reflectedValue);
});
apiUrl.search = urlSearchParams.toString();
}
return apiUrl.toString();
}
class $123f4982a51872b4$export$2e2bcd8739ae039 {
constructor(apiKey, apiSecret){
this.baseUrl = 'https://api.coolsms.co.kr';
this.apiKey = apiKey;
this.apiSecret = apiSecret;
this.authInfo = {
apiKey: apiKey,
apiSecret: apiSecret
};
}
/**
* 단일 메시지 발송 기능
* @param message 메시지(문자, 알림톡 등)
* @param appId appstore용 app id
*/ async sendOne(message, appId) {
const parameter = new $7467382afc84c32e$export$ad3dca884a810e33(message, false, appId);
const requestConfig = {
method: 'POST',
url: `${this.baseUrl}/messages/v4/send`
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig, parameter);
}
/**
* 단일 메시지 예약 발송 기능
* @param message 메시지(문자, 알림톡 등)
* @param scheduledDate
*/ async sendOneFuture(message, scheduledDate) {
const groupId = await this.createGroup();
await this.addMessagesToGroup(groupId, [
message
]);
scheduledDate = $551d0f39d46708b0$export$2e2bcd8739ae039(scheduledDate);
return this.reserveGroup(groupId, scheduledDate);
}
/**
* 여러 메시지 즉시 발송 기능
* 한번 요청으로 최대 10,000건의 메시지를 추가할 수 있습니다.
* @param messages 여러 메시지(문자, 알림톡 등)
* @param allowDuplicates 중복 수신번호 허용
* @param appId appstore용 app id
*/ async sendMany(messages, allowDuplicates = false, appId) {
const parameter = new $7467382afc84c32e$export$b4becc1d7edb915a(messages, allowDuplicates, appId);
const requestConfig = {
method: 'POST',
url: `${this.baseUrl}/messages/v4/send-many`
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig, parameter);
}
/**
* 여러 메시지 예약 발송 기능
* 한번 요청으로 최대 10,000건의 메시지를 추가할 수 있습니다.
* @param messages 여러 메시지(문자, 알림톡 등)
* @param scheduledDate 예약 발송 일자
* @param allowDuplicates 중복 수신번호 허용
* @param appId appstore용 app id
*/ async sendManyFuture(messages, scheduledDate, allowDuplicates = false, appId) {
const groupId = await this.createGroup(allowDuplicates, appId);
await this.addMessagesToGroup(groupId, messages);
scheduledDate = $551d0f39d46708b0$export$2e2bcd8739ae039(scheduledDate);
return this.reserveGroup(groupId, scheduledDate);
}
/**
* 그룹 생성
*/ async createGroup(allowDuplicates, appId) {
allowDuplicates = allowDuplicates ?? false;
const { sdkVersion: sdkVersion , osPlatform: osPlatform } = $7467382afc84c32e$export$fb47e5c0b633ea53;
const requestConfig = {
method: 'POST',
url: `${this.baseUrl}/messages/v4/groups`
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig, {
sdkVersion: sdkVersion,
osPlatform: osPlatform,
allowDuplicates: allowDuplicates,
appId: appId
}).then((res)=>res.groupId
);
}
/**
* 그룹 메시지 추가
* 한번 요청으로 최대 10,000건의 메시지를 추가할 수 있습니다.
* @param groupId 생성 된 Group ID
* @param messages 여러 메시지(문자, 알림톡 등)
*/ async addMessagesToGroup(groupId, messages) {
const requestConfig = {
method: 'PUT',
url: `${this.baseUrl}/messages/v4/groups/${groupId}/messages`
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig, new $7467382afc84c32e$export$6ba9c27a351bdec2(messages));
}
/**
* 그룹 메시지 전송 요청
* @param groupId 생성 된 Group ID
*/ async sendGroup(groupId) {
const requestConfig = {
method: 'POST',
url: `${this.baseUrl}/messages/v4/groups/${groupId}/send`
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig);
}
/**
* 그룹 예약 발송 설정
* @param groupId 생성 된 Group ID
* @param scheduledDate 예약발송 할 날짜
*/ async reserveGroup(groupId, scheduledDate) {
const requestConfig = {
method: 'POST',
url: `${this.baseUrl}/messages/v4/groups/${groupId}/schedule`
};
const formattedScheduledDate = $cl6Iw$datefns.formatISO(scheduledDate);
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig, {
scheduledDate: formattedScheduledDate
});
}
/**
* 그룹 통계 정보 조회
* @param data 그룹 정보 상세 조회용 request 데이터, date 관련 파라미터는 iso8601 포맷으로 보내야 함
*/ async getGroups(data) {
const endpoint = $ff8f5d4d31c52cf4$export$2e2bcd8739ae039(`${this.baseUrl}/messages/v4/groups`, data);
const requestConfig = {
method: 'GET',
url: endpoint
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig);
}
/**
* 그룹 내 메시지 목록 조회
* @param groupId 생성 된 Group ID
* @param data startkey, limit 등 쿼리 조건 파라미터
*/ async getGroupMessages(groupId, data) {
const endpoint = $ff8f5d4d31c52cf4$export$2e2bcd8739ae039(`${this.baseUrl}/messages/v4/groups/${groupId}/messages`, data);
const requestConfig = {
method: 'GET',
url: endpoint
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig);
}
/**
* 그룹 내 특정 메시지 삭제
* @param groupId 생성 된 Group Id
* @param messageIds 생성 된 메시지 ID 목록
*/ async removeGroupMessages(groupId, messageIds) {
const requestConfig = {
method: 'DELETE',
url: `${this.baseUrl}/messages/v4/groups/${groupId}/messages`
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig, {
messageIds: messageIds
});
}
/**
* 그룹 내 예약 발송 취소(메시지 실패 전체 처리 됨)
* @param groupId 생성 된 Group ID
*/ async removeReservationToGroup(groupId) {
const requestConfig = {
method: 'DELETE',
url: `${this.baseUrl}/messages/v4/groups/${groupId}/schedule`
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig);
}
/**
* 그룹 삭제
* @param groupId
*/ async removeGroup(groupId) {
const requestConfig = {
method: 'DELETE',
url: `${this.baseUrl}/messages/v4/groups/${groupId}`
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig);
}
/**
* 메시지 목록 조회
* @param data 목록 조회 상세조건 파라미터
*/ async getMessages(data) {
const parameter = data ? new $7467382afc84c32e$export$d88a1c09ffb9e02d(data) : {
};
const endpoint = $ff8f5d4d31c52cf4$export$2e2bcd8739ae039(`${this.baseUrl}/messages/v4/list`, parameter);
const requestConfig = {
method: 'GET',
url: endpoint
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig);
}
/**
* 통계 조회
* @param data 통계 상세 조건 파라미터
* @returns GetStatisticsResponse 통계 결과
*/ async getStatistics(data) {
const parameter = data ? new $7467382afc84c32e$export$4fede39aef110b5c(data) : {
};
const endpoint = $ff8f5d4d31c52cf4$export$2e2bcd8739ae039(`${this.baseUrl}/messages/v4/statistics`, parameter);
const requestConfig = {
method: 'GET',
url: endpoint
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig);
}
/**
* 잔액조회
* @returns GetBalanceResponse
*/ async getBalance() {
const requestConfig = {
method: 'GET',
url: `${this.baseUrl}/cash/v1/balance`
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig);
}
/**
* 파일(이미지) 업로드
* 카카오 친구톡 이미지는 500kb, MMS는 200kb, 발신번호 서류 인증용 파일은 2mb의 제한이 있음
* @param filePath 해당 파일의 경로 또는 접근 가능한 이미지 URL
* @param fileType 저장할 파일의 유형, 예) 카카오 친구톡 용 이미지 -> KAKAO, MMS용 사진 -> MMS, 발신번호 서류 인증에 쓰이는 문서 등 -> DOCUMENT, RCS 이미지 -> RCS
* @param name 파일 이름
* @param link 파일 링크, 친구톡의 경우 필수 값
*/ async uploadFile(filePath, fileType, name, link) {
const encodedFile = await ($parcel$interopDefault($cl6Iw$imagetobase64))(filePath);
const requestConfig = {
method: 'POST',
url: `${this.baseUrl}/storage/v1/files`
};
const parameter = {
file: encodedFile,
type: fileType,
name: name,
link: link
};
return $f24672c3715df8a1$export$2e2bcd8739ae039(this.authInfo, requestConfig, parameter);
}
}
//# sourceMappingURL=index.js.map