sms.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use strict';
  2. /**
  3. * 短信发送相关接口
  4. *
  5. * @author CaiAoLin
  6. * @date 2018/1/25
  7. * @version
  8. */
  9. // const xmlReader = require('xmlreader');
  10. class SMS {
  11. /**
  12. * 构造函数
  13. *
  14. * @param {Object} ctx - egg全局变量
  15. * @return {void}
  16. */
  17. constructor(ctx) {
  18. this.ctx = ctx;
  19. // this.url = 'https://sms.yunpian.com/v2/sms/batch_send.json';
  20. this.url = 'http://sms.haotingyun.com/v2/sms/single_send.json';
  21. this.url2 = 'http://sms.haotingyun.com/v2/sms/tpl_single_send.json';
  22. // this.url = 'http://101.132.42.40:7862/sms';
  23. }
  24. /**
  25. * 发送信息
  26. *
  27. * @param {String|Array} mobile - 发送的电话号码
  28. * @param {String} content - 发送的内容
  29. * @param {String} tplId - 补充的tpl_id(防止模板无法找到发送失败)
  30. * @return {Boolean} - 发送结果
  31. */
  32. async send(mobile, content, tplId = '') {
  33. if (mobile instanceof Array) {
  34. mobile = mobile.join(',');
  35. }
  36. let result = false;
  37. const config = this.ctx.app.config.sms;
  38. const postData = {
  39. // action: 'send',
  40. // account: config.account,
  41. // password: config.password,
  42. apikey: config.authKey,
  43. mobile,
  44. text: content,
  45. // extno: config.extno,
  46. };
  47. if (tplId !== '') {
  48. postData.tpl_id = tplId;
  49. }
  50. const url = tplId !== '' ? this.url2 : this.url;
  51. try {
  52. const response = await this.ctx.helper.sendRequest(url, postData, 'POST');
  53. // const xmlData = await this.xmlParse(response);
  54. // if (xmlData === undefined || xmlData.returnstatus.text() !== 'Success') {
  55. // throw '短信发送失败!';
  56. // }
  57. if (response === undefined && response.code !== 0) {
  58. throw '短信发送失败!';
  59. }
  60. result = true;
  61. } catch (error) {
  62. console.log(error);
  63. result = false;
  64. }
  65. return result;
  66. }
  67. /**
  68. * xml解析
  69. *
  70. * @param {String} xml - xml数据
  71. * @return {Object} - 解析结果
  72. */
  73. // xmlParse(xml) {
  74. // return new Promise(function(resolve, reject) {
  75. // xmlReader.read(xml, function(errors, xmlData) {
  76. // if (errors) {
  77. // reject('');
  78. // } else {
  79. // resolve(xmlData.returnsms);
  80. // }
  81. // });
  82. // });
  83. // }
  84. }
  85. module.exports = SMS;