文章目錄
一、阿里雲短信環境搭建
1、開啓使用子用戶,創建用戶組和用戶
點擊進入阿里雲控制檯
登錄成功後,點擊AccessKey管理,在彈窗中選擇開始使用子用戶AccessKey
創建用戶組之後,點擊進入權限管理,添加短信管理權限
注意:用戶創建成功後,我們需要立刻複製AccessKey ID和AccessKey Secret的值,因爲AccessKey Secre很快就會消失。
當我們點擊進入用戶時,我們可以看到AccessKey ID的值,但是AccessKey Secret已經看不到啦。
2、開通阿里雲短信服務
這裏的簽名管理和模板管理都需要進行審覈,在申請理由的那一欄中,填寫的理由一定要正當,否則無法審覈通過的哦!
上述工作完成之後,你還忘記一件事哦,既然開通短信服務,發送短信是要收費的,我們需要進行充值幾塊錢就可以的。
二、環境測試
1、新建Spring Boot(web)項目,導入依賴
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、在測試類中進行測試
@Test
void contextLoads() {
// 連接阿里雲
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "你的ID", "你的密碼");
IAcsClient client = new DefaultAcsClient(profile);
// 構建請求
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain("dysmsapi.aliyuncs.com");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
// 自定義參數(手機號,驗證碼,簽名,模板)
request.putQueryParameter("PhoneNumbers", "填寫手機號碼");
request.putQueryParameter("SignName", "填寫簽名");
request.putQueryParameter("TemplateCode", "填寫模板");
// 構建一個短信驗證碼
HashMap<String, Object> map = new HashMap<>();
map.put("code",6666);
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
運行程序,將會得到如下圖所示的短信。
其中,【】裏面的內容代表簽名,數字6666代表驗證碼,除此之外的信息爲模板。
三、真實業務場景實現
1、添加redis的相關配置
server.port=9090
# REDIS (RedisProperties)
# Redis數據庫索引(默認爲0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=127.0.0.1
# Redis服務器連接端口
spring.redis.port=6379
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.jedis.pool.max-active=8
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.jedis.pool.max-wait=-1
# 連接池中的最大空閒連接
spring.redis.jedis.pool.max-idle=8
# 連接池中的最小空閒連接
spring.redis.jedis.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=5000
2、在templates下面添加頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<form action="#" method="post">
請輸入號碼:<input type="text" v-model="phone"><br>
<input type="text">
<input type="button" value="獲取驗證碼" @click="login">
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
phone:""
},
methods:{
login(){
axios.post("http://localhost:9090/send?phone="+this.phone).then((res)=>{
console.log(res.data);
})
}
}
})
</script>
</body>
</html>
這裏使用Vue來實現前後端的分離。
3、新建SendSms接口並創建實現類SendSmsImpl
public interface SendSms {
public boolean send(String phoneNumbers, String templateCode, Map<String,Object> code);
}
@Service
public class SendSmsImpl implements SendSms {
@Override
public boolean send(String phoneNumbers, String templateCode, Map<String, Object> code) {
// 連接阿里雲
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "你的ID", "你的密碼");
IAcsClient client = new DefaultAcsClient(profile);
// 構建請求
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain("dysmsapi.aliyuncs.com");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
// 自定義參數(手機號,驗證碼,簽名,模板)
request.putQueryParameter("PhoneNumbers", phoneNumbers);
request.putQueryParameter("SignName", "你的簽名");
request.putQueryParameter("TemplateCode", templateCode);
/*// 構建一個短信驗證碼
HashMap<String, Object> map = new HashMap<>();
map.put("code", 6666);*/
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
return response.getHttpResponse().isSuccess();
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
return false;
}
}
4、編寫controller層
@RestController
@CrossOrigin // 跨域
public class SmsApiController {
@Autowired
private SendSms sendSms;
@Autowired
private RedisTemplate<String,String> redisTemplate;
@PostMapping("/send")
public String code(String phone) {
// 調用發送方法
String code = redisTemplate.opsForValue().get(phone);
if (!StringUtils.isEmpty(code)) {
return phone + ":" + code + "已存在,還沒有過期";
}
// 生成驗證碼並存儲到redis中
code = UUID.randomUUID().toString().substring(0, 4);
HashMap<String, Object> param = new HashMap<>();
param.put("code",code);
boolean isSend = sendSms.send(phone, "SMS_192195645", param);
if (isSend) {
redisTemplate.opsForValue().set(phone,code,5, TimeUnit.SECONDS);
return phone + ":" + code + "發送成功";
}else {
return "發送失敗";
}
}
}
5、運行結果
先輸入手機號碼,然後點擊獲取驗證碼即可獲取驗證碼。
這裏的驗證碼是一個隨機的四位數,不再是一個固定的值。