From 1b1d0ad47ac731413215a982d0e62adc1715ff45 Mon Sep 17 00:00:00 2001 From: Sum1Dream <418471657@qq.com> Date: Mon, 9 May 2022 10:21:40 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=9F=AD=E4=BF=A1=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/com/cweb/config/AuthConfig.java | 1 + .../cweb/controller/SendSmsController.java | 127 ++++-------- .../java/com/hai/config/MessageConfig.java | 180 ++++++++++++++++++ 3 files changed, 214 insertions(+), 94 deletions(-) create mode 100644 hai-service/src/main/java/com/hai/config/MessageConfig.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 8073e896..f8d72008 100644 --- a/hai-cweb/src/main/java/com/cweb/config/AuthConfig.java +++ b/hai-cweb/src/main/java/com/cweb/config/AuthConfig.java @@ -133,6 +133,7 @@ public class AuthConfig implements WebMvcConfigurer { .excludePathPatterns("/sendSms/*") .excludePathPatterns("/test/*") .excludePathPatterns("/sms/*") + .excludePathPatterns("/SendSms/*") .excludePathPatterns("/czOrder/*") .excludePathPatterns("/outRechargeOrder/*") .excludePathPatterns("/userDiscount/*") diff --git a/hai-cweb/src/main/java/com/cweb/controller/SendSmsController.java b/hai-cweb/src/main/java/com/cweb/controller/SendSmsController.java index 7170ad3a..14291cdb 100644 --- a/hai-cweb/src/main/java/com/cweb/controller/SendSmsController.java +++ b/hai-cweb/src/main/java/com/cweb/controller/SendSmsController.java @@ -1,18 +1,14 @@ 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.exception.ErrorCode; +import com.hai.common.exception.ErrorHelp; +import com.hai.common.exception.SysCode; import com.hai.common.utils.ResponseMsgUtil; -import com.hai.model.MtSmsMessageModel; +import com.hai.config.MessageConfig; import com.hai.model.ResponseData; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.apache.http.HttpHeaders; +import org.apache.commons.io.filefilter.IOFileFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; @@ -22,81 +18,49 @@ 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") +@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\""; - + private static Logger log = LoggerFactory.getLogger(SendSmsController.class); @Resource - private RedisUtil redisUtil; + private MessageConfig messageConfig; - @RequestMapping(value = "/sendSmsCode", method = RequestMethod.GET) + @RequestMapping(value = "/sendSmsCodeByHw", method = RequestMethod.GET) @ApiOperation(value = "发送短信验证码") @ResponseBody - public ResponseData sendSmsCode(@RequestParam(value = "phone", required = true) String phone) { + public ResponseData sendSmsCode(@RequestParam(value = "phone", required = true) String phone, + @RequestParam(value = "HWMSG", required = true) Integer HWMSG) { 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); + String smsMsgId; + + switch (HWMSG) { + case 1 : + smsMsgId = MessageConfig.HWMSG_ID1; + break; + case 2 : + smsMsgId = MessageConfig.HWMSG_ID2; + break; + case 3 : + smsMsgId = MessageConfig.HWMSG_ID3; + break; + case 4 : + smsMsgId = MessageConfig.HWMSG_ID5; + break; + default : + smsMsgId = "错误"; } - 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("SMS_"+phone,smsCode, 60*10); - return ResponseMsgUtil.success("发送成功"); + if (HWMSG > 3) { + throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "暂无当前模版"); } - return ResponseMsgUtil.success(object); + + return ResponseMsgUtil.success(messageConfig.sendSmsCodeHw(phone , smsMsgId)); } catch (Exception e) { log.error("CmsContentController --> sendSmsCode() error!", e); return ResponseMsgUtil.exception(e); @@ -104,30 +68,5 @@ public class SendSmsController { } - 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-service/src/main/java/com/hai/config/MessageConfig.java b/hai-service/src/main/java/com/hai/config/MessageConfig.java new file mode 100644 index 00000000..04cba687 --- /dev/null +++ b/hai-service/src/main/java/com/hai/config/MessageConfig.java @@ -0,0 +1,180 @@ +package com.hai.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.hai.common.exception.ErrorCode; +import com.hai.common.exception.ErrorHelp; +import com.hai.common.exception.SysCode; +import com.hai.common.security.VerifyCode; +import com.hai.common.security.VerifyCodeStorage; +import com.hai.common.utils.RedisUtil; +import com.hai.model.MtSmsMessageModel; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import javax.net.ssl.*; +import java.io.*; +import java.math.BigDecimal; +import java.net.URL; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.*; + +/** + * @author Sum1Dream + * @version 1.0.0 + * @serviceName MessageConfig.java + * @Description // 短信接口 + * @createTime 15:28 2022/5/6 + **/ +@Component +public class MessageConfig { + + // 华为短信模版ID + // 嗨森逛绑定工会卡 + public final static String HWMSG_ID1 = "SMS_22041400010"; + // 嗨森逛积分支付密码重置 + public final static String HWMSG_ID2 = "SMS_22041400009"; + // 嗨森逛注册 + public final static String HWMSG_ID3 = "SMS_22041400008"; + // 嗨森逛公司账户充值验证码 + public final static String HWMSG_ID4 = "SMS_22041400005"; + // 嗨森逛账号登录 + public final static String HWMSG_ID5 = "SMS_22050700002"; + + 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(MessageConfig.class); + + /** + * 设置不验证主机 + */ + private static final HostnameVerifier DO_NOT_VERIFY = (hostname, session) -> true; + + @Resource + private RedisUtil redisUtil; + + /** + * @Author Sum1Dream + * @name sendSmsCodeHw.java + * @Description // 普通华为短信验证码发送 + * @Date 16:31 2022/5/6 + * @Param [java.lang.String, java.lang.String] + * @return java.lang.String + */ + public String sendSmsCodeHw(String phone, String HWMSG) throws Exception { + VerifyCode verifyCode = VerifyCodeStorage.getDate(phone); + String smsCode; + if (verifyCode != null) { + smsCode = verifyCode.getObject(); + } else { + // 生成随机6位验证码 + smsCode = String.valueOf(new Random().nextInt(899999) + 100000); + } + // ip:port根据实际情况填写 + String url = "https://139.9.32.119:18312/common/sms/sendTemplateMessage"; + Map templateParas = new HashMap<>(); + templateParas.put("code", smsCode); + String account = "760887"; //实际账号 + String password = "Z.o'&mO%7_?5M,Br"; //实际密码 + + // 如果请求正文不包含签名名称,则设置签名为空 + Map body = buildRequestBody(phone, HWMSG, templateParas, account, password); + if (null == body || body.isEmpty()) { + throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "参数校验失败"); + } + + HttpsURLConnection connection; + InputStream is = null; + BufferedReader br = null; + trustAllHttpsCertificates(); + + 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"); + ObjectMapper objectMapper = new ObjectMapper(); + PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8")); + pw.write(objectMapper.writeValueAsString(body)); + pw.flush(); + pw.close(); + + 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 + ""); + } + connection.disconnect(); + System.out.println(result.toString()); + + is.close(); + br.close(); + + redisUtil.set("SMS_" + phone, smsCode, 60 * 10); + + 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()); + } + +}