egg.js 调用阿里云(阿里大于)短信验证码服务

1.开通阿里云短信服务

阿里云登录 - 欢迎登录阿里云,安全稳定的云计算服务平台

可以免费申请 企业短信验证码 200条

重点是:

签名名称:接收验证码内容时,【】里的文字。

短信模板code:相当于短信内容的 id。

可以申请

如果能申请成功,可在 下面地址 尝试测试一条短信。

SendSms_短信服务_API调试-阿里云OpenAPI开发者门户

2. 开始 egg后端

我使用的是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'  //阿里云的
    }
  }

示例

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

后端controller层开发

路由

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

后端使用redis保存 验证码信息 60s后端自动删除该笔数据 

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);
    }

成功效果是

页面效果,前端代码 就不展示了,包含,登录时 用户输入的验证码 跟 redis的验证码 进行比较

猜你喜欢

转载自blog.csdn.net/deng_zhihao692817/article/details/128917710
今日推荐