Third-party service-Alibaba Cloud SMS business integration springboot project
**Use scenario: **Use mobile phone verification code to log in/register
1. Log in to the official website of Alibaba Cloud-Cloud Market and purchase the responsive service
Alibaba Cloud Official Website-Cloud Market Address : Cloud Market Address
Search keywords : After the number of SMS
clicks to purchase the response, you can view it in Alibaba Cloud Control Center-Purchased Services;
2. Use according to the official API documentation
Document address : API documentation addresses
Click to debug button, online debugging interface
which authentication has AppCode and AppSecret two kinds.
-
AppCode method: document address
- AppCode needs to add the Authorization field in the request header, the value is "APPCODE + half-width space + APPCODE value"
-
AppSecret method: document address
AppCode and AppSecret can be viewed in Alibaba Cloud Control Center after purchasing the service
Four request parameters that the API needs to send
The skin template selection comparison table:
Use postman to simulate test sending request
official use
When the verification code needs to be sent in the program, for security (Code and Authorization) considerations. The front-end should send the ajax request, and the back- end sends the SMS service request after the request is accepted .
Extract public third-party container objects
Use @ConfigurationProperties(prefix = "alicloud.sms") annotation to automatically fill in the field in the configuration file application with the prefix of alicloud.sms
@ConfigurationProperties annotation use case
mport lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
@ConfigurationProperties(prefix = "alicloud.sms")
@Data
@Configuration
public class SmsComponent {
private String host;
private String path;
private String skin;
private String sign;
private String appcode;
public void sendSms(String phone,String code){
String urlSend = host + path + "?code=" + code +"&phone="+phone +"&sign="+sign +"&skin="+skin; // 【5】拼接请求链接
try {
URL url = new URL(urlSend);
HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE (中间是英文空格)
int httpCode = httpURLCon.getResponseCode();
if (httpCode == 200) {
String json = read(httpURLCon.getInputStream());
System.out.println("正常请求计费(其他均不计费)");
System.out.println("获取返回的json:");
System.out.print(json);
} else {
Map<String, List<String>> map = httpURLCon.getHeaderFields();
String error = map.get("X-Ca-Error-Message").get(0);
if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
System.out.println("AppCode错误 ");
} else if (httpCode == 400 && error.equals("Invalid Url")) {
System.out.println("请求的 Method、Path 或者环境错误");
} else if (httpCode == 400 && error.equals("Invalid Param Location")) {
System.out.println("参数错误");
} else if (httpCode == 403 && error.equals("Unauthorized")) {
System.out.println("服务未被授权(或URL和Path不正确)");
} else if (httpCode == 403 && error.equals("Quota Exhausted")) {
System.out.println("套餐包次数用完 ");
} else {
System.out.println("参数名错误 或 其他错误");
System.out.println(error);
}
}
} catch (MalformedURLException e) {
System.out.println("URL格式错误");
} catch (UnknownHostException e) {
System.out.println("URL地址错误");
} catch (Exception e) {
// 打开注释查看详细报错异常信息
// e.printStackTrace();
}
}
/*
* 读取返回结果
*/
private static String read(InputStream is) throws IOException {
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
line = new String(line.getBytes(), "utf-8");
sb.append(line);
}
br.close();
return sb.toString();
}
}
Configuration file application.properties
alicloud.sms.host=https://smsmsgs.market.alicloudapi.com
alicloud.sms.path=/sms/
alicloud.sms.skin=1
alicloud.sms.sign=1
alicloud.sms.appcode=自己的appcode
test
@Resource
private SmsComponent smsComponent;
@Test
void contextLoads() {
smsComponent.sendSms("13758768499","11111");
}
result:
正常请求计费(其他均不计费)
获取返回的json:
{"Message":"OK","Code":"OK","RequestId":"","BizId":""}