'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 = 'https://sms.yunpian.com/v2/sms/batch_send.json'; // this.url = 'http://sms.haotingyun.com/v2/sms/single_send.json'; this.url2 = 'http://sms.haotingyun.com/v2/sms/tpl_single_send.json'; // this.url = 'http://101.132.42.40:7862/sms'; } /** * 发送信息 * * @param {String|Array} mobile - 发送的电话号码 * @param {String} content - 发送的内容 * @param {String} tplId - 补充的tpl_id(防止模板无法找到发送失败) * @return {Boolean} - 发送结果 */ async send(mobile, content, tplId = '') { 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, apikey: config.authKey, mobile, text: content, // extno: config.extno, }; if (tplId !== '') { postData.tpl_id = tplId; } const url = tplId !== '' ? this.url2 : this.url; try { const response = await this.ctx.helper.sendRequest(url, postData, 'POST'); // const xmlData = await this.xmlParse(response); // if (xmlData === undefined || xmlData.returnstatus.text() !== 'Success') { // throw '短信发送失败!'; // } if (response === undefined && response.code !== 0) { throw '短信发送失败!'; } result = true; } catch (error) { console.log(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); // } // }); // }); // } /** * 关键字转换 * * @param {String} content - 内容 * @return {Object} - 解析结果 */ async contentChange(content) { let str = content.replace(/【/g, '('); str = str.replace(/】/g, ')'); str = str.replace(/工程款/g, '***'); return str; } } module.exports = SMS;