egg.js calls Alibaba Cloud (Alibaba) SMS verification code service

1. Open Alibaba Cloud SMS service

Alibaba Cloud Login - Welcome to Alibaba Cloud, a secure and stable cloud computing service platform

You can apply for 200 enterprise SMS verification codes for free

The point is:

Signature name: When receiving the content of the verification code, the text in 【】.

SMS template code: equivalent to the id of the SMS content.

can apply

If the application is successful, you can try to test a text message at the address below.

SendSms_SMS service_API debugging-Alibaba Cloud OpenAPI Developer Portal

2. Start the egg backend

I use egg-sms  GitHub - yolopunk/egg-sms: aliyun sms plugin for egg

npm i egg-sms --save
// {app_root}/config/plugin.js
sms: {
    enable: true,
    package: 'egg-sms'
}
{app_root}/config/config.default.js
config.sms = {
    client: {
      accessKeyId: 'id', //阿里云的
      secretAccessKey: 'key'  //阿里云的
    }
  }

example

  // {app_root}/app/controller/sms.js
  ...
  async send () {
    await this.ctx.sms.sendSMS({
      PhoneNumbers: '1500000000',
      SignName: '云通信产品',
      TemplateCode: 'SMS_000000',
      TemplateParam: '{"code":"12345"}'
    })
  }
  ...

Backend controller layer development

routing

router.post('/pc/user/captch', controller.pc.user.captch);//发送验证码

The backend uses redis to save the verification code information for 60s and the backend automatically deletes the data 

async captch() {
        const { ctx, app } = this;
        //参数验证 //2.验证手机号码合法性
        ctx.validate({
            mobile: { 
                type: 'phone',
                trim: true,
                required: true, 
                desc: '手机号' 
            },
        });
        //1.接收手机号码
        const { mobile } = ctx.request.body;
        
        //3.判断是否已经获取过验证码(判断缓存中是否存在当前手机号的验证码,有则提示"你已经获取过验证码了"),防止别有用心之人频繁验证,避免短信费用过高
        let has = await ctx.service.cache.get('sms_' + mobile);
        if (has) {
            ctx.throw(200, '您已获取过验证码了');
        }

        //4.生成4~6位数随机数字 生成六位随机验证码
        let smscode = Math.random().toString().slice(-6);
        
        //5.发送短信(阿里大于)
        let res = await ctx.sms.sendSMS({
            PhoneNumbers: mobile, //手机号码
            SignName: 'xxxxx', //签名
            TemplateCode: 'SMS_xxxxxx',// 模板
            TemplateParam: `{"code":'${smscode}'}`
        })
        //6.手机号=>验证码的形式保存在缓存中(60秒)
        if (!await this.service.cache.set('sms_' + mobile, smscode, 60 * 5)) {
            ctx.throw(200, '验证失败');
        }

        //7.提示成功
        ctx.apiSuccess(res);
    }

The success effect is

The page effect, the front-end code is not displayed, including, the verification code entered by the user when logging in is compared with the redis verification code

Guess you like

Origin blog.csdn.net/deng_zhihao692817/article/details/128917710