UNPKG

coolsms-node-sdk

Version:

CoolSMS SDK for Node.js(Server Side Only)

405 lines (375 loc) 16.4 kB
import {formatISO as $hSjDC$formatISO, parseISO as $hSjDC$parseISO} from "date-fns"; import $hSjDC$imagetobase64 from "image-to-base64"; import $hSjDC$crossfetch from "cross-fetch"; import {customAlphabet as $hSjDC$customAlphabet} from "nanoid"; import {HmacSHA256 as $hSjDC$HmacSHA256} from "crypto-js"; import {URL as $hSjDC$URL, URLSearchParams as $hSjDC$URLSearchParams} from "url"; var $097751060a5066bd$exports = {}; $097751060a5066bd$exports = JSON.parse("{\"version\":\"nodejs/2.0.0\"}"); class $114f87062c9208ec$export$7522646e65a7a5d1 extends Error { constructor(message){ super(message); this.name = 'InvalidDateError'; } } class $114f87062c9208ec$export$6efc4418efdbd5bb extends Error { constructor(message){ super(message); this.name = 'InvalidApiKeyError'; } } class $114f87062c9208ec$export$c73ca302efeda3b4 extends Error { constructor(errorCode, errorMessage){ super(errorMessage); this.name = errorCode; } } function $5f339c8b55dce9e2$export$2e2bcd8739ae039(value) { if (typeof value === 'string') { value = $hSjDC$parseISO(value); const invalidDateText = 'Invalid Date'; if (value.toString() === invalidDateText) throw new $114f87062c9208ec$export$7522646e65a7a5d1(invalidDateText); } return value; } const $090ae41076c76c53$export$fb47e5c0b633ea53 = { sdkVersion: $097751060a5066bd$exports.version, osPlatform: `${process.platform} | ${process.version}` }; class $090ae41076c76c53$var$DefaultMessageRequest { constructor(){ this.agent = $090ae41076c76c53$export$fb47e5c0b633ea53; this.allowDuplicates = false; } } class $090ae41076c76c53$export$ad3dca884a810e33 extends $090ae41076c76c53$var$DefaultMessageRequest { constructor(message, allowDuplicates, appId){ super(); this.message = message; if (typeof allowDuplicates === 'boolean') this.allowDuplicates = allowDuplicates; if (appId) this.appId = appId; } } class $090ae41076c76c53$export$b4becc1d7edb915a extends $090ae41076c76c53$var$DefaultMessageRequest { constructor(messages, allowDuplicates, appId){ super(); this.messages = messages; if (typeof allowDuplicates === 'boolean') this.allowDuplicates = allowDuplicates; if (appId) this.appId = appId; } } class $090ae41076c76c53$export$6ba9c27a351bdec2 { constructor(messages){ this.messages = messages; } } class $090ae41076c76c53$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 = $hSjDC$formatISO($5f339c8b55dce9e2$export$2e2bcd8739ae039(getMessageRequestType.duration.startDate)); if (getMessageRequestType.duration) this.endDate = $hSjDC$formatISO($5f339c8b55dce9e2$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 $090ae41076c76c53$export$4fede39aef110b5c { constructor(getStatisticsRequest){ if (getStatisticsRequest.duration) this.startDate = $hSjDC$formatISO($5f339c8b55dce9e2$export$2e2bcd8739ae039(getStatisticsRequest.duration.startDate)); if (getStatisticsRequest.duration) this.endDate = $hSjDC$formatISO($5f339c8b55dce9e2$export$2e2bcd8739ae039(getStatisticsRequest.duration.endDate)); this.masterAccountId = getStatisticsRequest.masterAccountId; } } let $0cd955c274584bb5$var$AuthenticateType; (function(AuthenticateType) { AuthenticateType[AuthenticateType["API_KEY"] = 0] = "API_KEY"; })($0cd955c274584bb5$var$AuthenticateType || ($0cd955c274584bb5$var$AuthenticateType = { })); function $0cd955c274584bb5$export$2e2bcd8739ae039(authenticationParameter, authType = $0cd955c274584bb5$var$AuthenticateType.API_KEY) { const { apiKey: apiKey , apiSecret: apiSecret } = authenticationParameter; switch(authType){ case $0cd955c274584bb5$var$AuthenticateType.API_KEY: default: const salt = $hSjDC$customAlphabet('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 32)(); const date = $hSjDC$formatISO(new Date()); const hmacData = date + salt; if (!apiKey || !apiSecret || apiKey === '' || apiSecret === '') throw new $114f87062c9208ec$export$6efc4418efdbd5bb('Invalid API Key Error'); const signature = $hSjDC$HmacSHA256(hmacData, apiSecret).toString(); return `HMAC-SHA256 apiKey=${apiKey}, date=${date}, salt=${salt}, signature=${signature}`; } } async function $577cae83fe53c9fe$export$2e2bcd8739ae039(authParameter, request, data) { const authorizationHeaderData = $0cd955c274584bb5$export$2e2bcd8739ae039(authParameter); return await $hSjDC$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 $114f87062c9208ec$export$c73ca302efeda3b4(errorResponse.errorCode, errorResponse.errorMessage); } else if (res.status >= 500) { const responseText = await res.text(); throw new $114f87062c9208ec$export$c73ca302efeda3b4('UnknownException', responseText); } try { return res.json(); } catch (exception) { throw new Error(await res.text()); } }); } function $4d903706b910ba1d$export$2e2bcd8739ae039(url, data) { const apiUrl = new $hSjDC$URL(url); if (data) { const urlSearchParams = new $hSjDC$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 $eb17f609fec572d7$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 $090ae41076c76c53$export$ad3dca884a810e33(message, false, appId); const requestConfig = { method: 'POST', url: `${this.baseUrl}/messages/v4/send` }; return $577cae83fe53c9fe$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 = $5f339c8b55dce9e2$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 $090ae41076c76c53$export$b4becc1d7edb915a(messages, allowDuplicates, appId); const requestConfig = { method: 'POST', url: `${this.baseUrl}/messages/v4/send-many` }; return $577cae83fe53c9fe$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 = $5f339c8b55dce9e2$export$2e2bcd8739ae039(scheduledDate); return this.reserveGroup(groupId, scheduledDate); } /** * 그룹 생성 */ async createGroup(allowDuplicates, appId) { allowDuplicates = allowDuplicates ?? false; const { sdkVersion: sdkVersion , osPlatform: osPlatform } = $090ae41076c76c53$export$fb47e5c0b633ea53; const requestConfig = { method: 'POST', url: `${this.baseUrl}/messages/v4/groups` }; return $577cae83fe53c9fe$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 $577cae83fe53c9fe$export$2e2bcd8739ae039(this.authInfo, requestConfig, new $090ae41076c76c53$export$6ba9c27a351bdec2(messages)); } /** * 그룹 메시지 전송 요청 * @param groupId 생성 된 Group ID */ async sendGroup(groupId) { const requestConfig = { method: 'POST', url: `${this.baseUrl}/messages/v4/groups/${groupId}/send` }; return $577cae83fe53c9fe$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 = $hSjDC$formatISO(scheduledDate); return $577cae83fe53c9fe$export$2e2bcd8739ae039(this.authInfo, requestConfig, { scheduledDate: formattedScheduledDate }); } /** * 그룹 통계 정보 조회 * @param data 그룹 정보 상세 조회용 request 데이터, date 관련 파라미터는 iso8601 포맷으로 보내야 함 */ async getGroups(data) { const endpoint = $4d903706b910ba1d$export$2e2bcd8739ae039(`${this.baseUrl}/messages/v4/groups`, data); const requestConfig = { method: 'GET', url: endpoint }; return $577cae83fe53c9fe$export$2e2bcd8739ae039(this.authInfo, requestConfig); } /** * 그룹 내 메시지 목록 조회 * @param groupId 생성 된 Group ID * @param data startkey, limit 등 쿼리 조건 파라미터 */ async getGroupMessages(groupId, data) { const endpoint = $4d903706b910ba1d$export$2e2bcd8739ae039(`${this.baseUrl}/messages/v4/groups/${groupId}/messages`, data); const requestConfig = { method: 'GET', url: endpoint }; return $577cae83fe53c9fe$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 $577cae83fe53c9fe$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 $577cae83fe53c9fe$export$2e2bcd8739ae039(this.authInfo, requestConfig); } /** * 그룹 삭제 * @param groupId */ async removeGroup(groupId) { const requestConfig = { method: 'DELETE', url: `${this.baseUrl}/messages/v4/groups/${groupId}` }; return $577cae83fe53c9fe$export$2e2bcd8739ae039(this.authInfo, requestConfig); } /** * 메시지 목록 조회 * @param data 목록 조회 상세조건 파라미터 */ async getMessages(data) { const parameter = data ? new $090ae41076c76c53$export$d88a1c09ffb9e02d(data) : { }; const endpoint = $4d903706b910ba1d$export$2e2bcd8739ae039(`${this.baseUrl}/messages/v4/list`, parameter); const requestConfig = { method: 'GET', url: endpoint }; return $577cae83fe53c9fe$export$2e2bcd8739ae039(this.authInfo, requestConfig); } /** * 통계 조회 * @param data 통계 상세 조건 파라미터 * @returns GetStatisticsResponse 통계 결과 */ async getStatistics(data) { const parameter = data ? new $090ae41076c76c53$export$4fede39aef110b5c(data) : { }; const endpoint = $4d903706b910ba1d$export$2e2bcd8739ae039(`${this.baseUrl}/messages/v4/statistics`, parameter); const requestConfig = { method: 'GET', url: endpoint }; return $577cae83fe53c9fe$export$2e2bcd8739ae039(this.authInfo, requestConfig); } /** * 잔액조회 * @returns GetBalanceResponse */ async getBalance() { const requestConfig = { method: 'GET', url: `${this.baseUrl}/cash/v1/balance` }; return $577cae83fe53c9fe$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 $hSjDC$imagetobase64(filePath); const requestConfig = { method: 'POST', url: `${this.baseUrl}/storage/v1/files` }; const parameter = { file: encodedFile, type: fileType, name: name, link: link }; return $577cae83fe53c9fe$export$2e2bcd8739ae039(this.authInfo, requestConfig, parameter); } } export {$eb17f609fec572d7$export$2e2bcd8739ae039 as default}; //# sourceMappingURL=module.js.map