const request = require('request') const username = 'BJHHEhy' const password = 'jMRYvR4f)!qD#T^IfqoNnX8F!*Kq!HZN' /** * 东八区当前时间戳,精确到秒,10位长度。 */ const timest = () => { var tmp = Date.parse( new Date() ).toString() tmp = tmp.substr(0,10) return tmp } /** * 密码,密码采用32位小写MD5二次加密,例:md5( md5( password ) + tKey ) , +为拼接符,不参与加密。 * @param {*} data 明文密码 */ const md5 = data => { var Buffer = require('buffer').Buffer var buf = new Buffer(data) var str = buf.toString('binary') var crypto = require('crypto') return crypto.createHash('md5WithRSAEncryption').update(str).digest('hex') } /** * 处理请求, 使用Promise将异步操作变为同步 * @param {*} event */ const handleRequest = options => { return new Promise((resolve, reject) => { request(options, (error, response, body) => { if (!error && response.statusCode === 200) { resolve(body) } else { reject(error) } }) }) } /** * 短信模板查询 * @param {*} event */ const templateQuery = event => { //生成十位时间戳 const tKey = timest() // 配置 POST 请求的选项 const options = { // url: 'https://api-shss.zthysms.com/v2/sendSms', url: 'https://api-shss.zthysms.com/sms/v2/template/query', method: 'POST', headers: { 'Content-Type': 'application/json' }, json: true, body: { username, password: md5(md5(password) + tKey), tKey, temId: 397495, } } return handleRequest(options) } /** * 短信模板列表查询 * @param {*} event */ const templateList = event => { //生成十位时间戳 const tKey = timest() // 配置 POST 请求的选项 const options = { url: 'https://api-shss.zthysms.com/sms/v2/template/list', method: 'POST', headers: { 'Content-Type': 'application/json' }, json: true, body: { username, password: md5(md5(password) + tKey), tKey, page: 1, size: 10, } } return handleRequest(options) } /** * 短信签名列表查询 * @param {*} event */ const signList = event => { //生成十位时间戳 const tKey = timest() // 配置 POST 请求的选项 const options = { url: 'https://api-shss.zthysms.com/sms/v1/sign/list', method: 'POST', headers: { 'Content-Type': 'application/json' }, json: true, body: { username, password: md5(md5(password) + tKey), tKey, // 审核状态 (1.待审核 2.审核通过 3.审核不通过) status: 2, page: 1, size: 10, } } return handleRequest(options) } /** * 模板短信发送 * @param {*} event */ const sendSmsTp = event => { //生成十位时间戳 const tKey = timest() // 配置 POST 请求的选项 const options = { url: 'https://api-shss.zthysms.com/v2/sendSmsTp', method: 'POST', headers: { 'Content-Type': 'application/json' }, json: true, body: { username, password: md5(md5(password) + tKey), tKey, // 已报备的签名 signature: '【红孩儿智慧教育】', // 模板id tpId: 397495, // 扩展号。纯数字,最多8位。 ext: '', // 发送时间。若为空,立即发送;若不为空,设置定时字符串日期,定时时间必须大于当前时间,格式:yyyy-MM-dd HH:mm:ss time: '', // 自定义参数,在获取状态报告时返回,最大长度100。 extend: '', records: [ { mobile: event.mobile, tpContent: { valid_code: event.code, } } ] } } return handleRequest(options) } module.exports = { // 根据模版Id查询模版 templateQuery, // 查询所有模版 templateList, // 短信签名列表查询 signList, // 模板短信发送 sendSmsTp, }