1)調用阿里的短信接口是很方便的,前提是你要開通好阿里的短信服務;java
1)登陸阿里控制檯----->開通短信服務------>交錢-------->獲取AK-------->配置簽名(配置消息簽名,通常是公司名)web
-------->配置模板(配置消息內容,例如:你的驗證碼是${code},請妥善保管.....)------->開發數據庫
<dependency>
<groupId>aliyun.java.sdk</groupId>
<artifactId>core</artifactId>
<version>3.3.1</version>
<systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/aliyun-java-sdk-core-3.3.1.jar</systemPath>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>aliyun.java.sdk</groupId>
<artifactId>dysmsapi</artifactId>
<version>1.0.0</version>
<systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/aliyun-java-sdk-dysmsapi-1.0.0.jar</systemPath>
<scope>compile</scope>
</dependency>
@Controller
public class ShortMessageController {
//產品名稱:雲通訊短信API產品,開發者無需替換
static final String product = "Dysmsapi";
//產品域名,開發者無需替換
static final String domain = "dysmsapi.aliyuncs.com";
// TODO 此處須要替換成開發者本身的AK(在阿里雲訪問控制檯尋找)
static final String accessKeyId = "**********";
static final String accessKeySecret = "**************";
@Autowired
private VerificationCodeMapper verificationCodeMapper;
@RequestMapping("getSsm")
@ResponseBody
public String getSsm(String number) {
//可自助調整超時時間
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暫不支持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);
//隨機生成六位驗證碼
int code = (int)((Math.random()*9+1)*100000);
//刪除該號碼上次的驗證碼記錄
verificationCodeMapper.deleteVerificationCodeMapper(number);
//保存到數據庫
VerificationCode verificationCode = new VerificationCode();
verificationCode.setCode(code+"");
verificationCode.setNumber(number);
int i =verificationCodeMapper.addVerificationCode(verificationCode);
//組裝請求對象-具體描述見控制檯-文檔部份內容
SendSmsRequest request = new SendSmsRequest();
//必填:待發送手機號
request.setPhoneNumbers(number);
//必填:短信簽名-可在短信控制檯中找到,你在簽名管理裏的內容
request.setSignName("星晨");
//必填:短信模板-可在短信控制檯中找到,你模板管理裏的模板編號
request.setTemplateCode("SMS_115760262");
//可選:模板中的變量替換JSON串,如模板內容爲"親愛的${name},您的驗證碼爲${code}"時,此處的值爲
request.setTemplateParam("{\"code\":\""+code+"\"}");
//選填-上行短信擴展碼(無特殊需求用戶請忽略此字段)
//request.setSmsUpExtendCode("90997");
//可選:outId爲提供給業務方擴展字段,最終在短信回執消息中將此值帶回給調用者
//request.setOutId("yourOutId");
//hint 此處可能會拋出異常,注意catch
SendSmsResponse sendSmsResponse = null;
try {
sendSmsResponse = acsClient.getAcsResponse(request);
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
//獲取發送狀態
String cod = sendSmsResponse.getCode();
return cod;
}
}