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);
}
}
注意事项
代码开发阶段 验证码的过期时间不宜太长 不然需要反复获取验证码 太过于麻烦!