阿里云短信服務介面
阿里云短信服務(Short Message Service)是阿里云為用戶提供的一種通信服務的能力,
支持向國內和國際快速發送驗證碼、短信通知和推廣短信,服務范圍覆寫全球200多個國家和地區,國內短信支持三網合一專屬通道,與工信部攜號轉網平臺實時互聯,電信級運維保障,實時監控自動切換,到達率高達99%,完美支撐雙11期間20億短信發送,6億用戶觸達,
快速開發
①開啟短信服務
1)登陸阿里云服務平臺

2)選擇控制臺

3)點擊左上角下拉按鈕選擇短信服務

4)開通短信服務

②實名認證
1)如果沒有實名認證需要跳轉實名認證界面

2)選擇相應的認證

3)選擇支付寶快速的認證
③創建簽名與模板
1)添加簽名

2)選擇簽名使用場景
驗證碼:只能使用驗證碼模板
通用:都可以使用(申請較為嚴格)

3)創建短信模板

4)根據常用模板庫申請相應短信模板
根據使用簽名可以創建相應模板,注意:驗證碼簽名只能使用驗證碼模板

④完成前期的準備作業
1)獲取申請成功的簽名(注冊時的簽名名稱)

2)獲取申請成功的短信模板(模版code)

3)獲取AccessKey ID 和 AccessKey Secret

⑤代碼書寫
1)匯入相應坐標
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.0.0</version>
</dependency>
2)創建短信發送工具類
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.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
public class SendSms {
private static final String AccessKeyId = "";//你的accessKeyId
private static final String AccessKeySecret = "";//你的accessKeySecret
private static final String SignName = "";//使用的簽名
private static final String TemplateCode = "";//發送短信使用的模板
private static IAcsClient acs = null;//服務物件
private static SendSmsRequest req = new SendSmsRequest();//短信發送請求物件
static {
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AccessKeyId, AccessKeySecret);
acs = new DefaultAcsClient(profile);
}
//隨機生成指定位數驗證碼
public static StringBuffer randomCode(int number){
//驗證碼內容集
final char[] CHARS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
StringBuffer stringBuffer=new StringBuffer();
Random r=new Random();
for(int i=0;i<number;i++){
stringBuffer.append(CHARS[r.nextInt(CHARS.length)]);
}
return stringBuffer;
}
//自定義發送方法
public static boolean sendCode(String mobile, String code) throws ClientException {
req.setPhoneNumbers(mobile);//設定接收短信手機號
req.setSignName(SignName);//設定使用簽名
req.setTemplateCode(TemplateCode);//設定使用通知模板id
req.setTemplateParam("{\"code\":\"" + code + "\"}");//設定請求引數 以json字串形式與模板一致
SendSmsResponse res = acs.getAcsResponse(req);//向服務器發送請求
//System.out.println("res code: " + res.getCode());//回應狀態碼
// System.out.println("res message: " + res.getMessage());//回應資訊
if (res.getCode() == null && !res.getCode().equals("OK")) {
System.out.println(res.getMessage());
return false;
}
return true;
}
public static void main(String[] args) throws ClientException {
System.out.println(sendCode("手機號","驗證碼"));
}
}
更多請查看阿里短信服務手冊
阿里短信服務手冊
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/135278.html
標籤:其他
上一篇:python正則匹配查詢資料
下一篇:網易互娛筆試2021批題解
