@codebucket/sms
Version:
SMS module
64 lines (63 loc) • 2.62 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MgovProvider = void 0;
const axios_1 = __importDefault(require("axios"));
const BaseProvider_1 = require("./BaseProvider");
const crypto_1 = require("crypto");
const querystring_1 = require("querystring");
class MgovProvider extends BaseProvider_1.BaseProvider {
constructor(cfg) {
super();
this.cfg = cfg;
}
async send(opts) {
const { to, content = '', type = 'text' } = opts;
let { variables = [] } = opts;
if (Array.isArray(variables)) {
let tempVariables = {};
for (let i = 0; i < variables.length; i++) {
tempVariables[`var${i + 1}`] = variables[i];
}
variables = tempVariables;
}
const msg = type === 'unicode' || type === 'unicodeotp'
? this.toUnicode(opts.content || '')
: this.interpolate(opts.content || '', variables);
const svcType = this.getServiceType(type);
const key = this.sha512(this.cfg.username + this.cfg.senderId + msg + this.cfg.secureKey);
const data = {
senderid: this.cfg.senderId,
content: msg,
smsservicetype: svcType,
username: this.cfg.username,
password: this.sha1(this.cfg.password),
key,
templateid: opts.templateId || this.cfg.templateId
};
const field = svcType === 'bulkmsg' ? 'bulkmobno' : 'mobileno';
data[field] = to.join(',');
const headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
return (await axios_1.default.post(this.cfg.url, (0, querystring_1.stringify)(data), { headers })).data;
}
getServiceType(type) {
switch (type) {
case 'bulk': return 'bulkmsg';
case 'unicode': return 'unicodemsg';
case 'otp': return 'otpmsg';
case 'unicodeotp': return 'unicodeotpmsg';
default: return 'singlemsg';
}
}
toUnicode(str) {
return str.split('').map(ch => `&#${ch.charCodeAt(0)};`).join('');
}
interpolate(t, vars) {
return t.replace(/{{(\w+)}}/g, (_, k) => vars[k] != null ? String(vars[k]) : '');
}
sha1(d) { return (0, crypto_1.createHash)('sha1').update(d, 'utf8').digest('hex'); }
sha512(d) { return (0, crypto_1.createHash)('sha512').update(d, 'utf8').digest('hex'); }
}
exports.MgovProvider = MgovProvider;