12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- 'use strict';
- const { Controller } = require('egg');
- const sms = require('@alicloud/dysmsapi20170525');
- const OpenApi = require('@alicloud/openapi-client');
- const Util = require('@alicloud/tea-util');
- const _ = require('lodash');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const assert = require('assert');
- class HomeController extends Controller {
- async index() {
- const { ctx } = this;
- ctx.body = 'hi, egg';
- }
- async sendMessage() {
- const { config, template, params = {}, phone } = this.ctx.request.body;
- console.log(config, template, params, phone);
- assert(config, '缺少服务设置');
- assert(template, '缺少消息模');
- assert(phone, '缺少发送对象');
- const appConfig = _.get(this.app.config.appConfig, config);
- const tt = _.get(appConfig, `template.${template}`);
- const cc = _.pick(appConfig, [ 'accessKeyId', 'accessKeySecret' ]);
- const client = await this.createClient(cc);
- // 设置参数
- tt.phoneNumbers = phone;
- tt.templateParam = JSON.stringify(params);
- const sendSmsRequest = new sms.SendSmsRequest(tt);
- const runtime = new Util.RuntimeOptions({});
- try {
- // 复制代码运行请自行打印 API 的返回值
- const res = await client.sendSmsWithOptions(sendSmsRequest, runtime);
- if (res.body.code !== 'OK') {
- throw new BusinessError(ErrorCode.SERVICE_FAULT, `${_.get(res.body.message)}`);
- }
- this.ctx.ok();
- } catch (error) {
- // 如有需要,请打印 error
- Util.assertAsString(error.message);
- throw new BusinessError(ErrorCode.SERVICE_FAULT, `${error.message}`);
- }
- }
- // api生成客户端
- async createClient({ accessKeyId, accessKeySecret }) {
- const config = new OpenApi.Config({ accessKeyId, accessKeySecret });
- config.endpoint = 'dysmsapi.aliyuncs.com';
- const client = new sms.default(config);
- return client;
- }
- }
- module.exports = HomeController;
|