ali短信服务完成本地验证码发送功能

pom阿里jar导入

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>4.5.3</version>
    </dependency>

controller

@ApiOperation("获取验证码")
@GetMapping(value = "/getcode")
public Result<Map<String, Object>> getcode(String number) {
    //设置超时时间-可自行调整
    System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
    System.setProperty("sun.net.client.defaultReadTimeout", "10000");
    //初始化ascClient需要的几个参数
	// final String product = "Dysmsapi";//短信API产品名称(短信产品名固定,无需修改)
    final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名(接口地址固定,无需修改)
    //替换成你的AK
    final String accessKeyId = "自己申请的key";
    final String accessKeySecret = "自己申请的keySecret";

    //连接阿里云
    DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
    IAcsClient client = new DefaultAcsClient(profile);
    //构建请求
    CommonRequest request = new CommonRequest();
    //下面的信息不要改
    request.setSysMethod(MethodType.POST);
    request.setSysDomain(domain);
    request.setSysVersion("2017-05-25");
    request.setSysAction("SendSms");
    //自定义的参数(手机号、签名和模版CODE)
    request.putQueryParameter("PhoneNumbers", number);
    request.putQueryParameter("SignName", "公司签名");
    request.putQueryParameter("TemplateCode", "短信模板code");

    //构建一个短信验证码
    HashMap<String, Object> map = new HashMap<>();
    // 生成验证码 放入redis中
    String verificationCode = VerificationCodeUtil.getVerificationCode(6);
    boolean set = redisUtil.set(number, verificationCode, 60L);
    if (!set){
        return Result.failed("获取验证码失败");
    }
    map.put("code", verificationCode);
    request.putQueryParameter("TemplateParam", com.alibaba.fastjson.JSONObject.toJSONString(map));
    //尝试发送
    try {
        CommonResponse response = client.getCommonResponse(request);
        System.out.println(response.getData());
    } catch (ServerException e) {
        e.printStackTrace();
    } catch (ClientException e) {
        e.printStackTrace();
    }
    return Result.success(null);
}

工具类生成验证码

public class VerificationCodeUtil {
 	public static String getVerificationCode(int charCount){
    	String charValue = "";
    	for (int i = 0; i < charCount; i++) {
       		char c = (char) (randomInt(0, 10) + '0');
            charValue += String.valueOf(c);
    	}
    	return charValue;
	}

	public static int randomInt(int from, int to) {
    	Random r = new Random();
    	return from + r.nextInt(to - from);
  	}
}

注意事项

代码开发阶段 验证码的过期时间不宜太长 不然需要反复获取验证码 太过于麻烦!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值