-
Notifications
You must be signed in to change notification settings - Fork 0
/
oneway.ts
418 lines (402 loc) · 12.3 KB
/
oneway.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// Copyright 2020 KwanJunWen. All rights reserved. MIT license.
import {
CheckCreditBalanceOutput,
CheckCreditBalanceURLParams,
CheckTransactionStatusInput,
CheckTransactionStatusOutput,
CheckTransactionStatusURLParams,
LanguageType,
MTTransactionStatus,
OneWayClient,
OneWayClientConfig,
OneWayURLParams,
OneWayURLPath,
SendSMSInput,
SendSMSOutput,
SendSMSURLParams,
} from "./types.ts";
import {
OneWayError,
OneWayErrorType,
} from "./error.ts";
/**
* SDK Version constant.
*/
const VERSION = "0.1.2";
// Based on specifications found in http://smsd2.onewaysms.sg/api.pdf.
export class OneWay implements OneWayClient {
private readonly config: OneWayClientConfig;
constructor(config: OneWayClientConfig) {
this.config = config;
}
/**
* Convert message into hexadecimal value.
* Automatically pad each character to 4 values with "0".
*/
private messageToHex(message: string): string {
const buf = [];
for (let n = 0, l = message.length; n < l; n++) {
buf.push(Number(message.charCodeAt(n)).toString(16).padStart(4, "0"));
}
return buf.join("");
}
/**
* Get language type based on the message provided.
* Checking is done based on byte length of each character.
*/
private getLanguageType(message: string): LanguageType {
const encoder = new TextEncoder();
for (let n = 0, l = message.length; n < l; n++) {
if (encoder.encode(message.charAt(n)).byteLength > 1) {
return "2";
}
}
return "1";
}
/**
* Builds request URL to access OneWaySMS API.
*/
private buildRequestURL<T = OneWayURLParams>(
path: OneWayURLPath,
urlParams: { [P in keyof T]: string },
): string {
const { baseURL } = this.config;
const params = new URLSearchParams();
for (const key in urlParams) {
params.set(key, urlParams[key]);
}
return `${baseURL}/${path}?${params.toString()}`;
}
/**
* Builds request URL to send mobile terminating message based on SMS provided.
*/
private buildSendSMSRequestURL(input: SendSMSInput): string {
const { apiUsername, apiPassword, senderID } = this.config;
if (!input.languageType) {
input.languageType = this.getLanguageType(input.message);
}
return this.buildRequestURL<SendSMSURLParams>("api.aspx", {
apiusername: apiUsername,
apipassword: apiPassword,
senderid: input.senderID || senderID,
mobileno: input.mobileNo.toString(),
languagetype: input.languageType,
message: input.languageType === "2"
? this.messageToHex(input.message)
: input.message,
});
}
/**
* Builds request URL to check transaction status based on mobile terminating ID provided.
*/
private buildCheckTransactionStatusRequestURL(
input: CheckTransactionStatusInput,
): string {
return this.buildRequestURL<CheckTransactionStatusURLParams>(
"bulktrx.aspx",
{ mtid: input.mtID.toString() },
);
}
/**
* Builds request URL to check remaining credit balance based on API Username and API Password
* from client's config.
*/
private buildCheckCreditBalanceRequestURL(): string {
const { apiUsername, apiPassword } = this.config;
return this.buildRequestURL<CheckCreditBalanceURLParams>(
"bulkcredit.aspx",
{ apiusername: apiUsername, apipassword: apiPassword },
);
}
/**
* Calls "GET" request with User-Agent set to this client library.
*/
private async getRequest(requestURL: string): Promise<Response> {
const headers = new Headers();
headers.set("User-Agent", `onewaysms-sdk-deno/${VERSION}`);
return fetch(requestURL, {
headers,
});
}
/**
* Initiate send SMS request. SMS's language type will be automatically set unless it is
* defined in the SMS request structure.
*
* const svc = new OneWay({
* baseURL: "API_BASE_URL",
* apiUsername: "API_USERNAME",
* apiPassword: "API_PASSWORD",
* senderID: "SENDER_ID",
* });
* try {
* const data = await svc.sendSMS({
* message: "Hello, 世界",
* mobileNo: ["60123456789", "60129876543"],
* });
* // mtIDs - Mobile terminating IDs
* console.log(data.mtIDs);
* } catch (err) {
* if (err instanceof OneWayError) {
* switch (err.code) {
* case OneWayErrorType.RequestFailure:
* // Handle RequestFailure
* case OneWayErrorType.InvalidCredentials:
* // Handle InvalidCredentials
* case OneWayErrorType.InvalidSenderID:
* // Handle InvalidSenderID
* case OneWayErrorType.InvalidMobileNo:
* // Handle InvalidMobileNo
* case OneWayErrorType.InvalidLanguageType:
* // Handle InvalidLanguageType
* case OneWayErrorType.InvalidMessageCharacters:
* // Handle InvalidMessageCharacters
* case OneWayErrorType.InsufficientCreditBalance:
* // Handle InsufficientCreditBalance
* case OneWayErrorType.UnknownError:
* // Handle UnknownError
* default:
* }
* } else {
* // Handle Generic Error
* }
* }
*/
async sendSMS(
input: SendSMSInput,
): Promise<SendSMSOutput> {
const requestURL = this.buildSendSMSRequestURL(input);
return Promise.resolve(
new Promise((res, rej) => {
this.getRequest(requestURL).then((resp) => {
if (!resp.ok) {
rej(
new OneWayError(
"request failure",
OneWayErrorType.RequestFailure,
resp.status,
),
);
}
return resp.text();
}).then((respText: string): void => {
const mtIDs = respText.split(",").map((t: string) => parseInt(t));
if (mtIDs.length <= 0) {
rej(
new OneWayError(
"unknown error",
OneWayErrorType.UnknownError,
),
);
return;
}
if (mtIDs[0] > 0) {
res({ mtIDs });
return;
}
switch (mtIDs[0]) {
case -100:
rej(
new OneWayError(
"apiusername or apipassword is invalid",
OneWayErrorType.InvalidCredentials,
),
);
return;
case -200:
rej(
new OneWayError(
"senderid parameter is invalid",
OneWayErrorType.InvalidSenderID,
),
);
return;
case -300:
rej(
new OneWayError(
"mobileno parameter is invalid",
OneWayErrorType.InvalidMobileNo,
),
);
return;
case -400:
rej(
new OneWayError(
"languagetype is invalid",
OneWayErrorType.InvalidLanguageType,
),
);
return;
case -500:
rej(
new OneWayError(
"characters in message are invalid",
OneWayErrorType.InvalidMessageCharacters,
),
);
return;
case -600:
rej(
new OneWayError(
"insufficient credit balance",
OneWayErrorType.InsufficientCreditBalance,
),
);
return;
default:
rej(
new OneWayError(
"unknown error",
OneWayErrorType.UnknownError,
),
);
return;
}
})
.catch(rej);
}),
);
}
/**
* Check transaction status based on mobile terminating ID provided.
*
* const svc = new OneWay({
* url: "API_BASE_URL",
* apiUsername: "API_USERNAME",
* apiPassword: "API_PASSWORD",
* senderID: "SENDER_ID",
* });
* try {
* const data = await svc.checkTransactionStatus({ mtID: MT_ID });
* switch (data.status) {
* case MTTransactionStatus.Success:
* // Handle success status
* case MTTransactionStatus.TelcoDelivered:
* // Handle telco delivered status
* default:
* }
* } catch (err) {
* if (err instanceof OneWayError) {
* switch (err.code) {
* case OneWayErrorType.MTInvalidNotFound:
* // Handle MTInvalidNotFound
* case OneWayErrorType.MessageDeliveryFailure:
* // Handle MessageDeliveryFailure
* case OneWayErrorType.UnknownError:
* // Handle UnknownError
* default:
* }
* } else {
* // Handle Generic Error
* }
* }
*/
async checkTransactionStatus(
input: CheckTransactionStatusInput,
): Promise<CheckTransactionStatusOutput> {
const requestURL = this.buildCheckTransactionStatusRequestURL(input);
return Promise.resolve(
new Promise((res, rej) => {
this.getRequest(requestURL)
.then((resp) => resp.text())
.then((respText: string): void => {
const status = parseInt(respText);
switch (status) {
case 0:
res({ status: MTTransactionStatus.Success });
return;
case 100:
res({ status: MTTransactionStatus.TelcoDelivered });
return;
case -100:
rej(
new OneWayError(
"mtid is invalid or not found",
OneWayErrorType.MTInvalidNotFound,
),
);
return;
case -200:
rej(
new OneWayError(
"message delivery failed",
OneWayErrorType.MessageDeliveryFailure,
),
);
return;
default:
rej(
new OneWayError(
"unknown error",
OneWayErrorType.UnknownError,
),
);
return;
}
})
.catch(rej);
}),
);
}
/**
* Check remaining credit balance based on API Username and Password from client's config.
*
* const svc = new OneWay({
* baseURL: "API_BASE_URL",
* apiUsername: "API_USERNAME",
* apiPassword: "API_PASSWORD",
* senderID: "SENDER_ID",
* });
* try {
* const data = await svc.checkCreditBalance();
* // creditBalance - Remaining credit balance for this account
* console.log(data.creditBalance);
* } catch (err) {
* if (err instanceof OneWayError) {
* switch (err.code) {
* case OneWayErrorType.InvalidCredentials:
* // Handle InvalidCredentials
* case OneWayErrorType.UnknownError:
* // Handle UnknownError
* default:
* }
* } else {
* // Handle Generic Error
* }
* }
*/
async checkCreditBalance(): Promise<CheckCreditBalanceOutput> {
const requestURL = this.buildCheckCreditBalanceRequestURL();
return Promise.resolve(
new Promise((res, rej) => {
this.getRequest(requestURL)
.then((resp) => resp.text())
.then((respText: string): void => {
const creditBalance = parseInt(respText);
if (creditBalance >= 0) {
res({ creditBalance });
return;
}
switch (creditBalance) {
case -100:
rej(
new OneWayError(
"apiusername or apipassword is invalid",
OneWayErrorType.InvalidCredentials,
),
);
return;
default:
rej(
new OneWayError(
"unknown error",
OneWayErrorType.UnknownError,
),
);
return;
}
})
.catch(rej);
}),
);
}
}