ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ### 封装基于eggJS短信发送类 Service 层 ``` 'use strict'; // 引入阿里SDK const Core = require('@alicloud/pop-core'); const Service = require('egg').Service; /** * 阿里短信验证码封装类 */ class AlismsService extends Service { /** * 发送短信 * @param { String } phone 用户手机号 * @param { String } code 生成的随机验证码 */ async sendSMS(phone, code) { const client = await this._client(); const params = await this._params(phone, code); const requestOption = await this._requestOption(); try { const ret = await this._send(client, params, requestOption); // {"Message":"OK","RequestId":"80A35575-6DD3-4A7D-B4AD-723F918CBBA5","BizId":"627317463804615179^0","Code":"OK"} return JSON.parse(ret); } catch (err) { this.ctx.errorHandle(err) } } async _client() { return new Core({ accessKeyId: this.config.aliSMS.accessKeyId, accessKeySecret: this.config.aliSMS.accessSecret, endpoint: 'https://dysmsapi.aliyuncs.com', apiVersion: '2017-05-25' }); } async _params(phone, code) { return { "RegionId": this.config.aliSMS.regionId, "PhoneNumbers": `${phone}`, "SignName": this.config.aliSMS.SignName, "TemplateCode": this.config.aliSMS.TemplateCode, "TemplateParam": `{\"code\":${code}}` } } async _requestOption() { return { method: 'POST' } } async _send(client, params, requestOption) { return new Promise((resolve, reject) => { client.request('SendSms', params, requestOption).then((result) => { resolve(JSON.stringify(result)) }, (ex) => { reject(ex) }) }) } } module.exports = AlismsService; ```