'use strict'; /** * 短信发送相关接口 * * @author CaiAoLin * @date 2018/1/25 * @version */ const xmlReader = require('xmlreader'); class SMS { /** * 构造函数 * * @param {Object} ctx - egg全局变量 * @return {void} */ constructor(ctx) { this.ctx = ctx; this.url = 'http://101.132.42.40:7862/sms'; } /** * 发送信息 * * @param {String|Array} mobile - 发送的电话号码 * @param {String} content - 发送的内容 * @return {Boolean} - 发送结果 */ async send(mobile, content) { if (mobile instanceof Array) { mobile = mobile.join(','); } let result = false; const config = this.ctx.app.config.sms; const postData = { action: 'send', account: config.account, password: config.password, mobile, content, extno: config.extno, }; try { const response = await this.ctx.helper.sendRequest(this.url, postData, 'POST', 'text'); const xmlData = await this.xmlParse(response); if (xmlData === undefined || xmlData.returnstatus.text() !== 'Success') { throw '短信发送失败!'; } result = true; } catch (error) { result = false; } return result; } /** * xml解析 * * @param {String} xml - xml数据 * @return {Object} - 解析结果 */ xmlParse(xml) { return new Promise(function(resolve, reject) { xmlReader.read(xml, function(errors, xmlData) { if (errors) { reject(''); } else { resolve(xmlData.returnsms); } }); }); } } module.exports = SMS;