容联云短信验证码功能

This commit is contained in:
kuang.yifei@iwhalecloud.com 2022-08-01 15:51:49 +08:00
parent e716cc1ee7
commit 3a891072ba
6 changed files with 203 additions and 6 deletions

View File

@ -0,0 +1,79 @@
package com.ghy.web.controller.tool;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ghy.common.config.SmsConfig;
import com.ghy.common.constant.SmsConstants;
import com.ghy.common.core.domain.AjaxResult;
import com.ghy.common.utils.CacheUtils;
import com.ghy.common.utils.ExceptionUtil;
import com.ghy.common.utils.http.HttpUtils;
import com.ghy.common.utils.security.Md5Utils;
import com.ghy.web.pojo.vo.SmsRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 容联云短信
* @author clunt
*/
@Slf4j
@Controller
@RequestMapping("/tool/sms")
public class SMSController {
private static final ThreadLocal<SimpleDateFormat> timeFormat = ThreadLocal.withInitial(()->new SimpleDateFormat("yyyyMMddHHmmss"));
@Autowired
private SmsConfig smsConfig;
@PostMapping("/send")
@ResponseBody
public AjaxResult sendSms(@RequestBody SmsRequest request){
try {
// 短信验证码
String code = String.valueOf((int)((Math.random() * 9 + 1) * Math.pow(10,5)));
// 拼接请求题
List<String> dataList = new ArrayList<>();
dataList.add(code);
dataList.add("3");
request.setAppId(smsConfig.getAppId());
request.setTemplateId(SmsConstants.TEMPLATE_ID);
request.setDatas(dataList);
String url = (smsConfig.getUrl() + SmsConstants.TEMPLATE_PATH).replace("{accountSid}", smsConfig.getAccount());
String time = timeFormat.get().format(new Date());
String sigParameter = Md5Utils.hash(smsConfig.getAccount() + smsConfig.getToken() + time).toUpperCase();
String authorization = Base64.getEncoder().encodeToString((smsConfig.getAccount() + ":" + time).getBytes(StandardCharsets.UTF_8));
url = url.replace("{SigParameter}", sigParameter);
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Content-Type", "application/json;charset=utf-8");
headerMap.put("Accept", "application/json;");
headerMap.put("Authorization", authorization);
// 调用第三方短信服务
String result = HttpUtils.sendPost(url, JSON.toJSONString(request), headerMap);
if("000000".equals(JSONObject.parseObject(result).getString("statusCode"))){
// 将短信验证码放进系统内存
CacheUtils.put(request.getTo(), code);
return AjaxResult.success("验证码发送成功!");
}else {
return AjaxResult.error(result);
}
}catch (Exception e){
e.printStackTrace();
log.error(ExceptionUtil.getExceptionMessage(e));
return AjaxResult.error(e.getMessage());
}
}
}

View File

@ -0,0 +1,21 @@
package com.ghy.web.pojo.vo;
import lombok.Data;
import java.util.List;
/**
* 容联短信请求体
* @author clunt
*/
@Data
public class SmsRequest {
private String to;
private String appId;
private String templateId;
private List<String> datas;
private String subAppend;
private String reqId;
}

View File

@ -130,3 +130,9 @@ jim:
baidu:
ak: 'ZQTgMW7W0GTuE7Ripb0HDp5TqRaOI6PZ'
url: 'https://api.map.baidu.com/reverse_geocoding/v3/?ak=#AK#&output=json&coordtype=wgs84ll&location='
sms:
url: 'https://app.cloopen.com:8883'
account: '8a216da85f008800015f0eb223620557'
appId: '8a216da85f008800015f0eb224db055d'
token: '3cef1bc80d814637a236d93004e7ffa5'

View File

@ -0,0 +1,50 @@
package com.ghy.common.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 容联云短信配置
* @author clunt
*/
@Component
@ConfigurationProperties(prefix = "sms")
public class SmsConfig {
private String url;
private String account;
private String appId;
private String token;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}

View File

@ -0,0 +1,18 @@
package com.ghy.common.constant;
/**
* 容联云短信配置
* @author clunt
*/
public class SmsConstants {
// 短信验证码通知模版
public static final String TEMPLATE_ID = "216263";
// 短信模版发送地址
public static final String TEMPLATE_URL = "https://app.cloopen.com:8883";
// 短信模版发送路径
public static final String TEMPLATE_PATH = "/2013-12-26/Accounts/{accountSid}/SMS/TemplateSMS?sig={SigParameter}";
}

View File

@ -6,6 +6,8 @@ import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
@ -120,6 +122,19 @@ public class HttpUtils
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param)
{
return sendPost(url, param, null);
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数请求参数应该是 name1=value1&name2=value2 的形式
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param, Map<String, String> header)
{
PrintWriter out = null;
BufferedReader in = null;
@ -135,6 +150,9 @@ public class HttpUtils
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
if(header != null){
header.forEach(conn::setRequestProperty);
}
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
@ -242,22 +260,27 @@ public class HttpUtils
return result;
}
public static String sendSSLPost(String url, String param)
{
public static String sendSSLPost(String url, String param){
return sendSSLPost(url, param, null);
}
public static String sendSSLPost(String url, String param, Map<String, String> header){
StringBuilder result = new StringBuilder();
String urlNameString = url + "?" + param;
try
{
log.info("sendSSLPost - {}", urlNameString);
log.info("sendSSLPost - {}", url);
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
URL console = new URL(urlNameString);
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
if(header != null){
header.forEach(conn::setRequestProperty);
}
conn.setDoOutput(true);
conn.setDoInput(true);
@ -271,7 +294,7 @@ public class HttpUtils
{
if (ret != null && !ret.trim().equals(""))
{
result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
result.append(new String(ret.getBytes("utf-8"), "utf-8"));
}
}
log.info("recv - {}", result);