From a7a5029b8e9965bb1ca9c3fb0acdb21001becca3 Mon Sep 17 00:00:00 2001 From: Sum1Dream <418471657@qq.com> Date: Tue, 19 Oct 2021 23:20:03 +0800 Subject: [PATCH] 1 --- .../main/java/com/cweb/config/AuthConfig.java | 2 + .../cweb/controller/SendSmsController.java | 133 ++++++++++++ .../com/cweb/controller/testController.java | 189 ++++++++++++++++++ .../java/com/hai/common/utils/HttpsUtils.java | 48 +++++ .../java/com/hai/model/MtSmsMessageModel.java | 71 +++++++ 5 files changed, 443 insertions(+) create mode 100644 hai-cweb/src/main/java/com/cweb/controller/SendSmsController.java create mode 100644 hai-cweb/src/main/java/com/cweb/controller/testController.java create mode 100644 hai-service/src/main/java/com/hai/model/MtSmsMessageModel.java diff --git a/hai-cweb/src/main/java/com/cweb/config/AuthConfig.java b/hai-cweb/src/main/java/com/cweb/config/AuthConfig.java index 4b8642bb..e7040d78 100644 --- a/hai-cweb/src/main/java/com/cweb/config/AuthConfig.java +++ b/hai-cweb/src/main/java/com/cweb/config/AuthConfig.java @@ -122,6 +122,8 @@ public class AuthConfig implements WebMvcConfigurer { .excludePathPatterns("/tPig/*") .excludePathPatterns("/telApi/*") .excludePathPatterns("/cmsContent/*") + .excludePathPatterns("/sendSms/*") + .excludePathPatterns("/test/*") ; } diff --git a/hai-cweb/src/main/java/com/cweb/controller/SendSmsController.java b/hai-cweb/src/main/java/com/cweb/controller/SendSmsController.java new file mode 100644 index 00000000..4b4588dc --- /dev/null +++ b/hai-cweb/src/main/java/com/cweb/controller/SendSmsController.java @@ -0,0 +1,133 @@ +package com.cweb.controller; + +import com.alibaba.fastjson.JSONObject; +import com.hai.common.Base64Util; +import com.hai.common.security.VerifyCode; +import com.hai.common.security.VerifyCodeStorage; +import com.hai.common.utils.DateUtil; +import com.hai.common.utils.HttpsUtils; +import com.hai.common.utils.RedisUtil; +import com.hai.common.utils.ResponseMsgUtil; +import com.hai.model.MtSmsMessageModel; +import com.hai.model.ResponseData; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.apache.http.HttpHeaders; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.annotation.Resource; +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.*; + + +@Controller +@Api(value = "华为云短信发送") +@RequestMapping(value = "/sendSms") +public class SendSmsController { + + private static final String[] HEX_DIGITS = {"0" ,"1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; + + private static Logger log = LoggerFactory.getLogger(CmsContentController.class); + + //无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值 + private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\""; + //无需修改,用于格式化鉴权头域,给"Authorization"参数赋值 + private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\""; + + + @Resource + private RedisUtil redisUtil; + + @RequestMapping(value = "/sendSmsCode", method = RequestMethod.GET) + @ApiOperation(value = "发送短信验证码") + @ResponseBody + public ResponseData sendSmsCode(@RequestParam(value = "phone", required = true) String phone) { + try { + + // ip:port根据实际情况填写 + String url = "https://139.9.32.119:18312/common/sms/sendTemplateMessage"; + String smsTemplateId = "SMS_21092300061"; + Map templateParas = new HashMap(); + String account = "760887"; //实际账号 + String password = "Z.o'&mO%7_?5M,Br"; //实际密码 + + VerifyCode verifyCode = VerifyCodeStorage.getDate(phone); + String smsCode; + if (verifyCode != null){ + smsCode = verifyCode.getObject(); + }else{ + // 生成随机6位验证码 + smsCode = String.valueOf(new Random().nextInt(899999) + 100000); + } + + templateParas.put("code" , smsCode); + + Map map = new HashMap(); + + List requestLists = new ArrayList(); + MtSmsMessageModel mtSmsMessage = new MtSmsMessageModel(); + List mobiles = new ArrayList(); + mobiles.add(phone); + mtSmsMessage.setMobiles(mobiles); + mtSmsMessage.setTemplateId(smsTemplateId); + mtSmsMessage.setTemplateParas(templateParas); + + requestLists.add(mtSmsMessage); + + map.put("account" , account); + map.put("password" , password); + map.put("requestLists" , requestLists); + + + Map header = new LinkedHashMap<>(); + header.put(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE); + + JSONObject object = HttpsUtils.doPostSendSms(url, map); + String code = object.getString("code"); + if (code.equals("000000")) { + redisUtil.set(phone,smsCode, 60*10); + return ResponseMsgUtil.success("发送成功"); + } + return ResponseMsgUtil.success(object); + } catch (Exception e) { + log.error("CmsContentController --> sendSmsCode() error!", e); + return ResponseMsgUtil.exception(e); + } + } + + + public String encodeBySHA256(String str) { + try{ + MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.reset(); + messageDigest.update(str.getBytes("UTF-8")); + return getFormattedText(messageDigest.digest()); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (Exception e) { + throw new RuntimeException(e); + } + return ""; + } + + private String getFormattedText(byte[] bytes) { + int len = bytes.length; + StringBuilder buf = new StringBuilder(len * 2); + // 把密文转换成十六进制的字符串形式 + for (int j=0;j> 4) & 0x0f]); + buf.append(HEX_DIGITS[bytes[j] & 0x0f]); + } + return buf.toString(); + } +} diff --git a/hai-cweb/src/main/java/com/cweb/controller/testController.java b/hai-cweb/src/main/java/com/cweb/controller/testController.java new file mode 100644 index 00000000..9387d1f9 --- /dev/null +++ b/hai-cweb/src/main/java/com/cweb/controller/testController.java @@ -0,0 +1,189 @@ +package com.cweb.controller; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.hai.model.MtSmsMessageModel; +import com.hai.model.ResponseData; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.URL; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +@Controller +@Api(value = "华为云短信发送") +@RequestMapping(value = "/test") +public class testController { + /** + * 设置不验证主机 + */ + + + private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { + + + @Override + public boolean verify(String hostname, SSLSession session) { + + + return true; + + + } + + + }; + + @RequestMapping(value = "/sendSmsCode", method = RequestMethod.GET) + @ApiOperation(value = "发送短信验证码") + @ResponseBody + public String sendSmsCode(@RequestParam(value = "phone", required = true) String phone) throws Exception { + // ip:port根据实际情况填写 + String url = "https://139.9.32.119:18312/common/sms/sendTemplateMessage"; + String msisdn = "18090580471"; + String smsTemplateId = "SMS_21092300061"; + Map templateParas = new HashMap(); + templateParas.put("code", "123456"); + String account = "760887"; //实际账号 + String password = "Z.o'&mO%7_?5M,Br"; //实际密码 + + // If the request body does not contain the signature name, set signature to null. + Map body = buildRequestBody(msisdn, smsTemplateId, templateParas, account, password); + if (null == body || body.isEmpty()) { + System.out.println("body is null."); + return ""; + } + + + HttpsURLConnection connection = null; + InputStream is = null; + BufferedReader br = null; + trustAllHttpsCertificates(); + try { + + + URL realUrl = new URL(url); + connection = (HttpsURLConnection) realUrl.openConnection(); + connection.setHostnameVerifier(DO_NOT_VERIFY); + connection.setDoInput(true); // 设置可输入 + connection.setDoOutput(true); // 设置该连接是可以输出的 + connection.setRequestMethod("POST"); // 设置请求方式 + connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); + // connection.connect(); + ObjectMapper objectMapper = new ObjectMapper(); + PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8")); + pw.write(objectMapper.writeValueAsString(body)); + pw.flush(); + pw.close(); + + + br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); + int status = connection.getResponseCode(); + if (200 == status) { // 200 + is = connection.getInputStream(); + } else { // 400/401 + is = connection.getErrorStream(); + } + br = new BufferedReader(new InputStreamReader(is, "UTF-8")); + String line = null; + StringBuilder result = new StringBuilder(); + while ((line = br.readLine()) != null) { // 读取数据 + result.append(line + "\n"); + } + connection.disconnect(); + System.out.println(result.toString()); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + + + if (null != is) { + is.close(); + } + if (null != br) { + br.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + return ""; + } + + // msisdn, smsTemplateId, paramValues, countryID + public static Map buildRequestBody(String msisdn, String smsTemplateId, + Map paramValues, String accout, String passward) { + if (null == msisdn || null == smsTemplateId || null == accout || null == passward) { + System.out.println( + "buildRequestBody(): mobiles, templateId or templateParas or account or password is null."); + return null; + } + + + Map map = new HashMap(); + List requestLists = new ArrayList(); + MtSmsMessageModel mtSmsMessage = new MtSmsMessageModel(); + List mobiles = new ArrayList(); + mobiles.add(msisdn); + mtSmsMessage.setMobiles(mobiles); + mtSmsMessage.setTemplateId(smsTemplateId); + mtSmsMessage.setTemplateParas(paramValues); + mtSmsMessage.setSignature("【嗨森逛】"); + requestLists.add(mtSmsMessage); + map.put("account", accout); + map.put("password", passward); + map.put("requestLists", requestLists); + return map; + } + + + static void trustAllHttpsCertificates() throws Exception { + TrustManager[] trustAllCerts = new TrustManager[] { + new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + return; + } + + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + return; + } + + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + } + }; + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, null); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + } + +} diff --git a/hai-service/src/main/java/com/hai/common/utils/HttpsUtils.java b/hai-service/src/main/java/com/hai/common/utils/HttpsUtils.java index 6b15ddd1..78b92d62 100644 --- a/hai-service/src/main/java/com/hai/common/utils/HttpsUtils.java +++ b/hai-service/src/main/java/com/hai/common/utils/HttpsUtils.java @@ -298,6 +298,54 @@ public class HttpsUtils { } return null; } + + + /** + * 发送 POST 请求,K-V形式 + * + * @param apiUrl + * API接口URL + * @param params + * 参数map + * @return + */ + public static JSONObject doPostSendSms(String apiUrl, Map params) { + CloseableHttpClient httpClient = null; + + if (apiUrl.startsWith("https")) { + httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()) + .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build(); + } else { + httpClient = HttpClients.createDefault(); + } + String httpStr = null; + CloseableHttpResponse response = null; + try { + HttpPost httpPost = new HttpPost(apiUrl); + httpPost.setConfig(requestConfig); + List pairList = new ArrayList<>(params.size()); + for (Map.Entry entry : params.entrySet()) { + NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString()); + pairList.add(pair); + } + httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8"))); + response = httpClient.execute(httpPost); + HttpEntity entity = response.getEntity(); + httpStr = EntityUtils.toString(entity, "UTF-8"); + return JSON.parseObject(httpStr); + } catch (Exception e) { + log.error(e.getMessage(),e); + } finally { + if (response != null) { + try { + EntityUtils.consume(response.getEntity()); + } catch (IOException e) { + log.error(e.getMessage(),e); + } + } + } + return null; + } /** * 发送 POST 请求,JSON形式 diff --git a/hai-service/src/main/java/com/hai/model/MtSmsMessageModel.java b/hai-service/src/main/java/com/hai/model/MtSmsMessageModel.java new file mode 100644 index 00000000..d0120db7 --- /dev/null +++ b/hai-service/src/main/java/com/hai/model/MtSmsMessageModel.java @@ -0,0 +1,71 @@ +package com.hai.model; + +import java.util.List; +import java.util.Map; + +public class MtSmsMessageModel { + List mobiles; + + + String templateId; + + + Map templateParas; + + + String signature; + + + String messageId; + + + String extCode; + + public List getMobiles() { + return mobiles; + } + + public void setMobiles(List mobiles) { + this.mobiles = mobiles; + } + + public String getTemplateId() { + return templateId; + } + + public void setTemplateId(String templateId) { + this.templateId = templateId; + } + + public Map getTemplateParas() { + return templateParas; + } + + public void setTemplateParas(Map templateParas) { + this.templateParas = templateParas; + } + + public String getSignature() { + return signature; + } + + public void setSignature(String signature) { + this.signature = signature; + } + + public String getMessageId() { + return messageId; + } + + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + public String getExtCode() { + return extCode; + } + + public void setExtCode(String extCode) { + this.extCode = extCode; + } +}