使用前需要先购买阿里云短信以及相关配置
安装依赖
cnpm i @alicloud/pop-core --save
api
// 发送验证码
smsApi.post('/captcha', async ctx => {
const tel = ctx.request.body.tel;
let txt = createCode(4);
ctx.session.verifCode = txt;
await sendSms(tel, txt);
ctx.success({
code: 10254
});
});
方法
import Core from '@alicloud/pop-core'
// ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
const accessKeyId = setting.smsAccessKey;
const secretAccessKey = setting.smsAccessKeySecret;
var client = new Core({
accessKeyId: accessKeyId,
accessKeySecret: secretAccessKey,
endpoint: 'https://dysmsapi.aliyuncs.com',
apiVersion: '2017-05-25'
});
// 发送短信
async function sendSms(tel, code) {
var params = {
"PhoneNumbers": tel,
"SignName": setting.SignName,
"TemplateCode": setting.TemplateCode,
"TemplateParam": "{'code':" + code + "}",
"OutId": "1234"
}
var requestOption = {
method: 'POST'
};
await client.request('SendSms', params, requestOption).then((result) => {
console.log(result)
}, (ex) => {
console.log(ex.data.Message)
throw new ParametersException({code: 10255});
})
}
测试
收到验证码
搞定收工