資料內(nèi)容:
阿里云短信驗證碼獲取
1.工具類生成驗證碼
public class VerificationCodeUtil{
/**
* 六位隨機數(shù)驗證碼
*/
public static String getVerificationCode() {
StringBuilder result = new StringBuilder();
Random random = new Random();
String[] str = {"0", "1", "2", "3", "4", "5", "6", "7",
"8", "9"};
for (int i = 0; i < 6; i++) {
result.append(str[random.nextInt(10)]);
}
return result.toString();
}
}
2.短信驗證碼發(fā)送工具類
public class SmsUtil {
//阿里云服務KEYID
private static final String KEYID = "******************";
//阿里云服務SECRET
private static final String SECRET = "*******************";
/**
* 使用AK&SK初始化賬號Client
*/
public static Client createClient(String accessKeyId, String
accessKeySecret) throws Exception {
Config config = new Config()
// 必填,您的 AccessKey ID
.setAccessKeyId(accessKeyId)
// 必填,您的 AccessKey Secret
.setAccessKeySecret(accessKeySecret);
// 訪問的域名
config.endpoint = "dysmsapi.aliyuncs.com";
return new Client(config);
}
/**
* 短信驗證碼
*
* @param phone 手機號
* @param template_code 短信模板
* @param params 模板參數(shù)
*/
public static void sendMessage(String phone, String
template_code, String params) {
try {
// 創(chuàng)建一個短信服務客戶端實例,使用預設的KEYID和SECRET進行身份認
證
Client client = SmsUtil.createClient(KEYID, SECRET);
// 創(chuàng)建SendSmsRequest對象,設置發(fā)送短信所需參數(shù)
SendSmsRequest sendSmsRequest = new SendSmsRequest()
// 設置接收短信的手機號碼
.setPhoneNumbers(phone)
// 設置模板參數(shù),根據(jù)實際業(yè)務場景替換為動態(tài)內(nèi)容
.setTemplateParam(params)
// 設置短信模板CODE
.setTemplateCode(template_code)
// 設置短信簽名名稱
.setSignName("短信驗證碼");
// 調(diào)用客戶端的sendSmsWithOptions方法發(fā)送短信,并傳入
RuntimeOptions以配置額外的運行時選項
// 這段代碼執(zhí)行后會發(fā)送短信驗證碼到指定的手機號碼上,但此處為了簡潔
沒有打印API返回的結果
client.sendSmsWithOptions(sendSmsRequest, new
RuntimeOptions());
} catch (Exception ignored) {
}
}
}