畢設中用到的短信驗證碼服務,需要先去阿里雲申請服務和驗證碼模板,我申請了三個模板。。。
/***阿里雲發送驗證碼***/
/**
* 驗證碼長度
*/
private final int codeLength = 6;
/**
* 阿里雲發送驗證碼
*
* @param phoneNumbers 目標手機號碼
* @param code 驗證碼
* @param templateCode 模板代碼
*/
public void sendSMS(String phoneNumbers, String code, String templateCode) {
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", PropertiesUtil.getProperty("accessKeyId"), PropertiesUtil.getProperty("accessSecret"));
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", phoneNumbers);
request.putQueryParameter("SignName", "生鮮超市app");
request.putQueryParameter("TemplateCode", templateCode);
request.putQueryParameter("TemplateParam", "{'code':" + code.toString() + "}");
try {
CommonResponse response = client.getCommonResponse(request);
JSONObject jsonObject = JSONObject.parseObject(response.getData());
String resCode = jsonObject.getString("Code");
if ("OK".equals(resCode)) {
System.out.println(phoneNumbers + "》》》發送驗證碼成功");
} else {
throw new CustomException(100, "發送驗證碼失敗");
}
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
/**
* @return 驗證碼字符串
* @see
*/
public String getRandomCode() {
Random rand = new Random();
int a;
String result = "";
for (int j = 0; j < codeLength; j++) {
a = Math.abs(rand.nextInt() % 9);
result += String.valueOf(a);
}
return result;
}