From 40fec6e678038e44c0043818b903cba64c833296 Mon Sep 17 00:00:00 2001 From: = <=> Date: Wed, 26 May 2021 00:00:46 +0800 Subject: [PATCH] =?UTF-8?q?'=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/com/cweb/config/AuthConfig.java | 1 + .../main/java/com/cweb/config/SysConfig.java | 20 +++ .../cweb/controller/SmsContentController.java | 105 +++++++++++++++ .../com/cweb/controller/WechatController.java | 120 +++++++++++++++++- .../src/main/resources/dev/config.properties | 4 +- .../java/com/hai/common/utils/HttpsUtils.java | 78 ++++++++++++ 6 files changed, 325 insertions(+), 3 deletions(-) create mode 100644 hai-cweb/src/main/java/com/cweb/controller/SmsContentController.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 35867abd..04c3b685 100644 --- a/hai-cweb/src/main/java/com/cweb/config/AuthConfig.java +++ b/hai-cweb/src/main/java/com/cweb/config/AuthConfig.java @@ -102,6 +102,7 @@ public class AuthConfig implements WebMvcConfigurer { .excludePathPatterns("/highMerchantStore/getStoreList") .excludePathPatterns("/highMerchantStore/getMerchantList") .excludePathPatterns("/highMerchantStore/getStoreListByMerchant") + .excludePathPatterns("/sms/sendSmsCode") .excludePathPatterns("/wechat/*") ; } diff --git a/hai-cweb/src/main/java/com/cweb/config/SysConfig.java b/hai-cweb/src/main/java/com/cweb/config/SysConfig.java index 3ce4a0b3..3f41b11a 100644 --- a/hai-cweb/src/main/java/com/cweb/config/SysConfig.java +++ b/hai-cweb/src/main/java/com/cweb/config/SysConfig.java @@ -13,6 +13,10 @@ public class SysConfig { private String wxAppId; private String wxAppSecret; + + private String wxH5AppId; + private String wxH5AppSecret; + private String wxApiKey; private String wxMchId; private String wxMchAppId; @@ -109,4 +113,20 @@ public class SysConfig { public void setWxSubAppId(String wxSubAppId) { this.wxSubAppId = wxSubAppId; } + + public String getWxH5AppId() { + return wxH5AppId; + } + + public void setWxH5AppId(String wxH5AppId) { + this.wxH5AppId = wxH5AppId; + } + + public String getWxH5AppSecret() { + return wxH5AppSecret; + } + + public void setWxH5AppSecret(String wxH5AppSecret) { + this.wxH5AppSecret = wxH5AppSecret; + } } diff --git a/hai-cweb/src/main/java/com/cweb/controller/SmsContentController.java b/hai-cweb/src/main/java/com/cweb/controller/SmsContentController.java new file mode 100644 index 00000000..ce8c0f35 --- /dev/null +++ b/hai-cweb/src/main/java/com/cweb/controller/SmsContentController.java @@ -0,0 +1,105 @@ +package com.cweb.controller; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.hai.common.Base64Util; +import com.hai.common.utils.DateUtil; +import com.hai.common.utils.HttpsUtils; +import com.hai.common.utils.ResponseMsgUtil; +import com.hai.entity.BsCompany; +import com.hai.entity.SecRegion; +import com.hai.model.ResponseData; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import netscape.javascript.JSObject; +import org.bouncycastle.jcajce.provider.digest.SHA256; +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 java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.*; + +@Controller +@Api(value = "内容管理 内容发布") +@RequestMapping(value = "/sms") +public class SmsContentController { + + 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); + + @RequestMapping(value = "/sendSmsCode", method = RequestMethod.GET) + @ApiOperation(value = "发生短信验证码") + @ResponseBody + public ResponseData sendSmsCode(@RequestParam(value = "phone", required = true) String phone) { + try { + + Map map = new LinkedHashMap<>(); + map.put("", "88200409698"); + map.put("to", phone); + map.put("templateId", "f42261f78d54488391f1d1ac4bd5bd3f"); + ArrayList list = new ArrayList<>(); + list.add(phone); + map.put("signature", "嗨森逛"); + + String param = "88200409698&to" + phone + "&templateId=f42261f78d54488391f1d1ac4bd5bd3f&statusCallback=[" + phone +"]&signature=嗨森逛"; + + //JSON.toJSONString(map); + Map body = new LinkedHashMap<>(); + body.put("from", param); + + String nonce = UUID.randomUUID().toString(); + String created = DateUtil.date2String(new Date(), "yyyy-MM-dd'T'HH:mm:ss'Z'"); + + + String passwordDigest = Base64Util.encode(encodeBySHA256(nonce + created + "9CWFv4NlaRX49n43VPA6eucZ8xeQ")); + + // 9CWFv4NlaRX49n43VPA6eucZ8xeQ + Map header = new LinkedHashMap<>(); + header.put("Authorization", "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\""); + header.put("X-WSSE", "UsernameToken Username=\"QR5eMVrcW0Md6r634M6tf2i34cvb\",PasswordDigest=\""+passwordDigest+"\",Nonce=\""+nonce+"\",Created=\""+created+"\""); + System.out.println(header.get("X-WSSE")); + JSONObject object = HttpsUtils.doSmsPost("https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1", body,header); + return ResponseMsgUtil.success(object); + } catch (Exception e) { + log.error("CmsContentController --> getCorporateAdvertising() 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/WechatController.java b/hai-cweb/src/main/java/com/cweb/controller/WechatController.java index e402d69c..07e17cf3 100644 --- a/hai-cweb/src/main/java/com/cweb/controller/WechatController.java +++ b/hai-cweb/src/main/java/com/cweb/controller/WechatController.java @@ -6,12 +6,14 @@ import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo; import cn.binarywang.wx.miniapp.bean.WxMaUserInfo; import com.alibaba.fastjson.JSONObject; import com.cweb.config.SessionKeyCache; +import com.cweb.config.SysConst; import com.cweb.config.WxMaConfiguration; import com.hai.common.exception.ErrorCode; import com.hai.common.exception.ErrorHelp; import com.hai.common.exception.SysCode; import com.hai.common.security.SessionObject; import com.hai.common.security.UserCenter; +import com.hai.common.utils.HttpsUtils; import com.hai.common.utils.ResponseMsgUtil; import com.hai.entity.HighUser; import com.hai.model.HighUserModel; @@ -32,7 +34,11 @@ import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.net.URLEncoder; import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; @Controller @RequestMapping(value = "/wechat") @@ -49,7 +55,7 @@ public class WechatController { @RequestMapping(value = "/handleCode", method = RequestMethod.GET) @ResponseBody - @ApiOperation(value = "微信小程序code解析") + @ApiOperation(value = "小程序code解析") public ResponseData compairCode(@RequestParam(value = "code", required = true) String code, HttpServletRequest request, HttpServletResponse response) { try { @@ -73,7 +79,7 @@ public class WechatController { @RequestMapping(value = "/login", method = RequestMethod.GET) @ResponseBody - @ApiOperation(value = "微信小程序授权用户登录接口") + @ApiOperation(value = "小程序授权用户登录接口") public ResponseData login(@RequestParam(value = "openId", required = true) String openId, HttpServletRequest request, HttpServletResponse response) { try { @@ -218,4 +224,114 @@ public class WechatController { } + @RequestMapping(value = "/getH5Code", method = RequestMethod.GET) + @ResponseBody + @ApiOperation(value = "【H5】获取Code") + public ResponseData getH5Code() { + try { + Map params = new LinkedHashMap<>(); + params.put("appid", SysConst.getSysConfig().getWxH5AppId()); + params.put("redirect_uri", URLEncoder.encode("https://hsgcs.dctpay.com/H5/index.html#/", "utf-8")); + //params.put("redirect_uri", "https://hsgcs.dctpay.com/H5/index.html#/"); + params.put("response_type", "code"); + params.put("scope", "snsapi_userinfo"); + params.put("state", "STATE"); + + String apiUrl = "https://open.weixin.qq.com/connect/oauth2/authorize"; + StringBuffer param = new StringBuffer(); + int i = 0; + for (String key : params.keySet()) { + if (i == 0) + param.append("?"); + else + param.append("&"); + param.append(key).append("=").append(params.get(key)); + i++; + } + apiUrl += param + "#wechat_redirect"; + return ResponseMsgUtil.success(apiUrl); + + } catch (Exception e) { + return ResponseMsgUtil.exception(e); + } + } + + @RequestMapping(value = "/getH5AccessToken", method = RequestMethod.GET) + @ResponseBody + @ApiOperation(value = "【H5】获取AccessToken") + public ResponseData getH5AccessToken(@RequestParam(value = "code", required = true) String code) { + try { + Map params = new HashMap<>(); + params.put("appid", SysConst.getSysConfig().getWxH5AppId()); + params.put("secret", SysConst.getSysConfig().getWxH5AppSecret()); + params.put("code", code); + params.put("grant_type", "authorization_code"); + return ResponseMsgUtil.success(HttpsUtils.doGet("https://api.weixin.qq.com/sns/oauth2/access_token", params)); + + } catch (Exception e) { + return ResponseMsgUtil.exception(e); + } + } + + @RequestMapping(value = "/getH5UserInfo", method = RequestMethod.GET) + @ResponseBody + @ApiOperation(value = "【H5】获取用户信息") + public ResponseData getH5UserInfo(@RequestParam(value = "code", required = true) String code, + HttpServletRequest request, HttpServletResponse response) { + try { + // 获取access_token + Map params = new HashMap<>(); + params.put("appid", SysConst.getSysConfig().getWxH5AppId()); + params.put("secret", SysConst.getSysConfig().getWxH5AppSecret()); + params.put("code", code); + params.put("grant_type", "authorization_code"); + JSONObject jsonObject = HttpsUtils.doGet("https://api.weixin.qq.com/sns/oauth2/access_token", params); + String accessToken = jsonObject.getString("access_token"); + String openid = jsonObject.getString("openid"); + if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(openid)) { + log.error("getH5UserInfo error!", "获取微信access_token失败" ); + throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "获取微信access_token失败"); + } + params.clear(); + params.put("access_token", accessToken); + params.put("openid", openid); + params.put("lang", "zh_CN"); + JSONObject userInfo = HttpsUtils.doGet("https://api.weixin.qq.com/sns/userinfo", params); + System.out.println(userInfo.toJSONString()); + if (StringUtils.isNotBlank(userInfo.getString("errcode"))) { + log.error("getH5UserInfo error!", "获取微信用户信息失败"); + throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "获取微信用户信息失败"); + } + + HighUser user = highUserService.findByOpenId(openid); + if (user == null) { + user = new HighUser(); + user.setOpenId(openid); + user.setRegTime(new Date()); + user.setStatus(1); + user.setGold(0); + user.setHeaderImg(userInfo.getString("headimgurl")); + user.setName(userInfo.getString("nickname")); + highUserService.insertUser(user); + } else { + user.setOpenId(openid); + user.setHeaderImg(userInfo.getString("headimgurl")); + user.setName(userInfo.getString("nickname")); + highUserService.updateUser(user); + } + + // 定义个人所有数据 + HighUserModel highUserModel = new HighUserModel(); + user.setPassword(null); + highUserModel.setHighUser(user); + SessionObject so = new SessionObject(openid, 1 , highUserModel); + userCenter.save(request, response, so); + return ResponseMsgUtil.success(so); + + } catch (Exception e) { + return ResponseMsgUtil.exception(e); + } + } + + } diff --git a/hai-cweb/src/main/resources/dev/config.properties b/hai-cweb/src/main/resources/dev/config.properties index 63f2d82d..39e3ba86 100644 --- a/hai-cweb/src/main/resources/dev/config.properties +++ b/hai-cweb/src/main/resources/dev/config.properties @@ -1,7 +1,9 @@ -# ΢ +# ΢������ wxAppId=wx8d49e2f83025229d wxAppSecret=d8d6dcaef77d3b659258a01b5ddba5df +wxH5AppId=wxa075e8509802f826 +wxH5AppSecret=0e606fc1378d35e359fcf3f15570b2c5 wxApiKey=Skufk5oi85wDFGl888i6wsRSTkdd5df5 wxMchAppId=wx637bd6f7314daa46 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 a9cd8910..742381ca 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 @@ -120,6 +120,44 @@ public class HttpsUtils { } return null; } + + public static JSONObject doWxGet(String url, Map params) { + String apiUrl = url; + StringBuffer param = new StringBuffer(); + int i = 0; + for (String key : params.keySet()) { + if (i == 0) + param.append("?"); + else + param.append("&"); + param.append(key).append("=").append(params.get(key)); + i++; + } + apiUrl += param + "#wechat_redirect"; + String result = null; + HttpClient httpClient = null; + try { + + if (apiUrl.startsWith("https")) { + httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()) + .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build(); + } else { + httpClient = HttpClients.createDefault(); + } + + HttpGet httpGet = new HttpGet(apiUrl); + HttpResponse response = httpClient.execute(httpGet); + HttpEntity entity = response.getEntity(); + if (entity != null) { + InputStream instream = entity.getContent(); + result = IOUtils.toString(instream, "UTF-8"); + } + return JSON.parseObject(result); + } catch (Exception e) { + log.error(e.getMessage(),e); + } + return null; + } /** * 发送 POST 请求(HTTP),不带输入数据 @@ -259,6 +297,46 @@ public class HttpsUtils { } return null; } + + public static JSONObject doSmsPost(String apiUrl, Map body, Map header) { + 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); + for (Map.Entry entry : header.entrySet()) { + httpPost.setHeader(entry.getKey(), entry.getValue().toString()); + } + StringEntity stringEntity = new StringEntity(JSON.toJSONString(body), "UTF-8");// 解决中文乱码问题 + stringEntity.setContentEncoding("UTF-8"); + stringEntity.setContentType("application/x-www-form-urlencoded"); + httpPost.setEntity(stringEntity); + 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形式 *