1. 程式人生 > 實用技巧 >Springboot下實現阿里雲簡訊驗證功能(含程式碼)

Springboot下實現阿里雲簡訊驗證功能(含程式碼)

Springboot下實現阿里雲簡訊驗證功能

一 開通阿里雲簡訊服務

  • 阿里雲官網註冊登入

  • 找到簡訊服務並開通

  • 開啟簡訊服務的管理臺

  • 在國內訊息那欄中新增簽名管理和模板管理(按照格式要求去寫)

  • 在右上角的使用者資訊裡有AccessKey管理(裡面的資訊後續要用並且需要妥善儲存)

  • 簡訊服務的幫助檔案裡有相關Maven依賴和示例

二 程式碼

pom.xml

    <dependencies>

        <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency> <dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

實現的工具類

其中需要修改的一些引數已經標出

package com.zbw.demo;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import net.minidev.json.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest; import java.rmi.ServerException;
import java.util.HashMap; @SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
//連線
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "你的AccessKeyid", "你的AccessKey密碼");
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", "你的阿里雲模板Code");
//構建驗證碼
HashMap<String, Object> map = new HashMap<>();
map.put("code", 這裡寫你想要給手機上發的驗證碼);
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ClientException e) {
e.printStackTrace();
} }
}

三 後續

  • 阿里雲官方檔案中的Demo其實已經介紹的很詳細了,建議去看.
  • 新增依賴時要注意版本號