準備工作:
- 阿里雲-RAM用戶登錄
- 創建AccessKey,獲取AccessKeyId和AccessKeySecret
- 找到短信服務,獲取簽名
- 獲取短信模板code
5.查看模板內容中的變量
如圖變量則爲code
一、導入jar包
<!-- 短信驗證碼 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.1.0</version>
</dependency>
二、配置參數
/**
* 手機驗證部分配置
*/
public class ShortMessage {
// 設置超時時間-可自行調整
public final static String defaultConnectTimeout = "sun.net.client.defaultConnectTimeout";
public final static String defaultReadTimeout = "sun.net.client.defaultReadTimeout";
public final static String Timeout = "10000";
// 初始化ascClient需要的幾個參數
public final static String product = "Dysmsapi";// 短信API產品名稱(短信產品名固定,無需修改)
public final static String domain = "dysmsapi.aliyuncs.com";// 短信API產品域名(接口地址固定,無需修改)
// 替換成AK (產品密)
public final static String accessKeyId = "accessKeyId";
public final static String accessKeySecret = "accessKeySecret";
// 必填:短信簽名-可在短信控制檯中找到
public final static String SignName = "簽名"; // 阿里雲配置自己的短信簽名填入
// 必填:短信模板-可在短信控制檯中找到
public final static String TemplateCode= "SMS_xxx";
}
三、短信發送工具類
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
public class ShortMessageUtil {
/**
* 阿里雲短信服務配置
* @param mobile
* @param templateCode 短信模板
* @param templateParam 模板中的變量替換JSON串
* @return 錯誤列表
*/
public static String getPhoneMsg(String mobile, String templateCode, String templateParam) {
/**
* 進行正則關係校驗
*/
System.out.println(mobile);
if (mobile == null || mobile == "") {
System.out.println("手機號爲空");
return "";
}
/**
* 短信驗證
*/
// 設置超時時間-可自行調整
System.setProperty(ShortMessage.defaultConnectTimeout, ShortMessage.Timeout);
System.setProperty(ShortMessage.defaultReadTimeout, ShortMessage.Timeout);
// 初始化ascClient需要的幾個參數
final String product = ShortMessage.product;// 短信API產品名稱(短信產品名固定,無需修改)
final String domain = ShortMessage.domain;// 短信API產品域名(接口地址固定,無需修改)
// 替換成你的AK
final String accessKeyId = ShortMessage.accessKeyId;// 你的accessKeyId,參考本文檔步驟2
final String accessKeySecret = ShortMessage.accessKeySecret;// 你的accessKeySecret,參考本文檔步驟2
// 初始化ascClient,暫時不支持多region
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
accessKeyId, accessKeySecret);
try {
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product,
domain);
} catch (ClientException e1) {
e1.printStackTrace();
}
IAcsClient acsClient = new DefaultAcsClient(profile);
// 組裝請求對象
SendSmsRequest request = new SendSmsRequest();
// 使用post提交
request.setMethod(MethodType.POST);
// 必填:待發送手機號。支持以逗號分隔的形式進行批量調用,批量上限爲1000個手機號碼,批量調用相對於單條調用及時性稍有延遲,驗證碼類型的短信推薦使用單條調用的方式
request.setPhoneNumbers(mobile);
// 必填:短信簽名-可在短信控制檯中找到
request.setSignName(ShortMessage.SignName);
// 必填:短信模板-可在短信控制檯中找到
request.setTemplateCode(templateCode);
// 可選:模板中的變量替換JSON串,如模板內容爲"親愛的${code},您的驗證碼爲${code}"時,此處的值爲
// 友情提示:如果JSON中需要帶換行符,請參照標準的JSON協議對換行符的要求,比如短信內容中包含\r\n的情況在JSON中需要表示成\\r\\n,否則會導致JSON在服務端解析失敗
//request.setTemplateParam("{ \"code\":\""+code+"\"}");
request.setTemplateParam(templateParam);
// 可選:outId爲提供給業務方擴展字段,最終在短信回執消息中將此值帶回給調用者
//request.setOutId("yourOutId");
// 請求失敗這裏會拋ClientException異常
SendSmsResponse sendSmsResponse;
try {
sendSmsResponse = acsClient.getAcsResponse(request);
if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
// 請求成功
return sendSmsResponse.getCode();
} else {
//請求失敗,返回錯誤信息描述
return sendSmsResponse.getMessage();
}
} catch (ClientException e) {
throw new ThirdPartException(e.getMessage());
}
}
}
注:如果獲取驗證碼失敗:sendSmsResponse.getCode() 會返回一個錯誤碼,可通過sendSmsResponse.getMessage() 獲取失敗的原因,如:返回isv.AMOUNT_NOT_ENOUGH 爲:賬戶餘額不足。可查看幫助文檔,裏面有全部的錯誤碼的描述。
官方文檔鏈接:幫助文檔
四、 測試
public class Test {
private static String code ;
public static void main(String[] args) {
String tel = "12345678910"; //輸入手機號
getVerificationCode(tel);
}
/**
* 獲取短信驗證碼
* @param tel
*/
public static void getVerificationCode(String tel) {
String templateParam = {\"code\":\""+code+"\"}";
String result = ShortMessageUtil.getPhoneMsg(tel, ShortMessage.VerificationCode,templateParam);
if (result != null && result.equals("OK")){
// 請求成功
System.out.println("獲取驗證碼成功!!!");
}else{
//
System.out.println("獲取驗證碼失敗"+result);
throw new ThirdPartException(result);
}
}
/**
* 生成6位隨機數驗證碼
* @return
*/
public static String vcode(){
StringBuilder code = new StringBuilder();
for (int i = 0; i < 6; i++) {
int random = (int) (Math.random() * 10);
code = code.append(random);
}
return code.toString();
}
}