home.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. const { Controller } = require('egg');
  3. const sms = require('@alicloud/dysmsapi20170525');
  4. const OpenApi = require('@alicloud/openapi-client');
  5. const Util = require('@alicloud/tea-util');
  6. const _ = require('lodash');
  7. const { BusinessError, ErrorCode } = require('naf-core').Error;
  8. const assert = require('assert');
  9. class HomeController extends Controller {
  10. async index() {
  11. const { ctx } = this;
  12. ctx.body = 'hi, egg';
  13. }
  14. async sendMessage() {
  15. const { config, template, params = {}, phone } = this.ctx.request.body;
  16. console.log(config, template, params, phone);
  17. assert(config, '缺少服务设置');
  18. assert(template, '缺少消息模');
  19. assert(phone, '缺少发送对象');
  20. const appConfig = _.get(this.app.config.appConfig, config);
  21. const tt = _.get(appConfig, `template.${template}`);
  22. const cc = _.pick(appConfig, [ 'accessKeyId', 'accessKeySecret' ]);
  23. const client = await this.createClient(cc);
  24. // 设置参数
  25. tt.phoneNumbers = phone;
  26. tt.templateParam = JSON.stringify(params);
  27. const sendSmsRequest = new sms.SendSmsRequest(tt);
  28. const runtime = new Util.RuntimeOptions({});
  29. try {
  30. // 复制代码运行请自行打印 API 的返回值
  31. const res = await client.sendSmsWithOptions(sendSmsRequest, runtime);
  32. if (res.body.code !== 'OK') {
  33. throw new BusinessError(ErrorCode.SERVICE_FAULT, `${_.get(res.body.message)}`);
  34. }
  35. this.ctx.ok();
  36. } catch (error) {
  37. // 如有需要,请打印 error
  38. Util.assertAsString(error.message);
  39. throw new BusinessError(ErrorCode.SERVICE_FAULT, `${error.message}`);
  40. }
  41. }
  42. // api生成客户端
  43. async createClient({ accessKeyId, accessKeySecret }) {
  44. const config = new OpenApi.Config({ accessKeyId, accessKeySecret });
  45. config.endpoint = 'dysmsapi.aliyuncs.com';
  46. const client = new sms.default(config);
  47. return client;
  48. }
  49. }
  50. module.exports = HomeController;