sms.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 = 'http://sms.haotingyun.com/v2/sms/single_send.json';
  20. // this.url = 'http://101.132.42.40:7862/sms';
  21. }
  22. /**
  23. * 发送信息
  24. *
  25. * @param {String|Array} mobile - 发送的电话号码
  26. * @param {String} content - 发送的内容
  27. * @return {Boolean} - 发送结果
  28. */
  29. async send(mobile, content) {
  30. if (mobile instanceof Array) {
  31. mobile = mobile.join(',');
  32. }
  33. let result = false;
  34. const config = this.ctx.app.config.sms;
  35. const postData = {
  36. // action: 'send',
  37. // account: config.account,
  38. // password: config.password,
  39. apikey: config.authKey,
  40. mobile,
  41. text: content,
  42. // extno: config.extno,
  43. };
  44. try {
  45. const response = await this.ctx.helper.sendRequest(this.url, postData, 'POST');
  46. // const xmlData = await this.xmlParse(response);
  47. // if (xmlData === undefined || xmlData.returnstatus.text() !== 'Success') {
  48. // throw '短信发送失败!';
  49. // }
  50. if (response === undefined && response.code !== 0) {
  51. throw '短信发送失败!';
  52. }
  53. result = true;
  54. } catch (error) {
  55. console.log(error);
  56. result = false;
  57. }
  58. return result;
  59. }
  60. /**
  61. * xml解析
  62. *
  63. * @param {String} xml - xml数据
  64. * @return {Object} - 解析结果
  65. */
  66. xmlParse(xml) {
  67. return new Promise(function(resolve, reject) {
  68. xmlReader.read(xml, function(errors, xmlData) {
  69. if (errors) {
  70. reject('');
  71. } else {
  72. resolve(xmlData.returnsms);
  73. }
  74. });
  75. });
  76. }
  77. }
  78. module.exports = SMS;