sms.js 1.8 KB

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