阿里云 短信验证码

    @GetMapping("/sendSms")
    public AjaxResult sendSmsAli(String phoneNum) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = SmsSendUtils.sendSmsAli(phoneNum, redisCache);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (ajaxResult.isSuccess()) {
            return AjaxResult.success();
        }
        return ajaxResult;
    }

在这里插入图片描述
在这里插入图片描述

      #AccessKey管理里面的账号
    public static String accessKeyId = "";
     #AccessKey管理里面的密码第一次保存的
    public static String accessKeySecret = "";
     #模板名称
    public static String signName = "阿里云验证码";
     #模板CODE
    public static String templateCode = "";

  public static AjaxResult sendSmsAli(String phoneNumber, RedisCache redisCache) throws Exception {

        // 生成验证码
        String code = getCode();

        // 短信内容使用阿里云模板规范,短信参数应该是 JSON 格式
        String templateParam = String.format("{\"code\":\"%s\"}", code);

        // 创建短信客户端
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        Client client = new Client(config);

        // 构建短信请求
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phoneNumber)
                .setTemplateParam(templateParam);

        // 运行时配置
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 发送短信
            client.sendSmsWithOptions(sendSmsRequest, runtime);
            System.out.println("短信发送成功" + code);

            // 将验证码存入 Redis,3 分钟过期
            redisCache.setCacheObject(qcode + phoneNumber, code, 3, TimeUnit.MINUTES);

            // 返回成功的 AjaxResult
            return AjaxResult.success(code);

        } catch (Exception error) {
            // 处理发送失败的异常
            System.err.println("短信发送失败:" + error.getMessage());
            return AjaxResult.error("短信发送失败:" + error.getMessage());
        }
    }
    public static String getCode() {
        Random random = new Random();
        int min = 100000; // 最小值为100000
        int max = 999999; // 最大值为999999
        int randomNumber = random.nextInt(max - min + 1) + min;
        return String.valueOf(randomNumber);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值