TWechatController.java 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package com.szwl.controller;
  2. import cn.com.crbank.ommo.exception.MyException;
  3. import com.alibaba.fastjson.JSON;
  4. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  5. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  6. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  7. import com.sun.org.apache.regexp.internal.RE;
  8. import com.szwl.constant.ResponseCodesEnum;
  9. import com.szwl.model.bo.R;
  10. //import com.szwl.model.dto.WechatDTO;
  11. import com.szwl.model.entity.TAdmin;
  12. import com.szwl.model.entity.TWechat;
  13. import com.szwl.model.utils.DateUtils;
  14. import com.szwl.model.utils.HttpClientUtils;
  15. import com.szwl.service.TAdminService;
  16. import com.szwl.service.TWechatService;
  17. import io.swagger.annotations.Api;
  18. import io.swagger.annotations.ApiModelProperty;
  19. import io.swagger.annotations.ApiOperation;
  20. import lombok.extern.slf4j.Slf4j;
  21. import org.apache.commons.lang.StringUtils;
  22. import org.apache.http.Header;
  23. import org.apache.http.HttpEntity;
  24. import org.apache.http.HttpHeaders;
  25. import org.apache.http.client.methods.CloseableHttpResponse;
  26. import org.apache.http.client.methods.HttpGet;
  27. import org.apache.http.impl.client.CloseableHttpClient;
  28. import org.apache.http.impl.client.HttpClientBuilder;
  29. import org.apache.http.impl.client.LaxRedirectStrategy;
  30. import org.apache.http.util.EntityUtils;
  31. import org.json.JSONObject;
  32. import org.springframework.beans.factory.annotation.Autowired;
  33. import org.springframework.beans.factory.annotation.Value;
  34. import org.springframework.format.annotation.DateTimeFormat;
  35. import org.springframework.web.bind.annotation.*;
  36. import org.springframework.web.servlet.view.RedirectView;
  37. import javax.servlet.http.HttpServletRequest;
  38. import javax.servlet.http.HttpServletResponse;
  39. import java.io.IOException;
  40. import java.io.UnsupportedEncodingException;
  41. import java.net.HttpURLConnection;
  42. import java.net.URL;
  43. import java.net.URLEncoder;
  44. import java.security.MessageDigest;
  45. import java.text.SimpleDateFormat;
  46. import java.time.LocalDate;
  47. import java.time.LocalTime;
  48. import java.time.format.DateTimeFormatter;
  49. import java.util.*;
  50. /**
  51. * <p>
  52. * 前端控制器
  53. * </p>
  54. *
  55. * @author wuhs
  56. * @since 2023-05-19
  57. */
  58. @Slf4j
  59. @Api(value = "/WeChatController", tags = {"微信绑定接口"})
  60. @RestController
  61. @RequestMapping("/tWechat")
  62. public class TWechatController {
  63. @Autowired
  64. private TAdminService tAdminService;
  65. @Autowired
  66. private TWechatService tWechatService;
  67. // 从 yml 文件中获取
  68. @Value("${oauth.wx.appid}")
  69. private String appid;
  70. @Value("${oauth.wx.appsecret}")
  71. private String appsecret;
  72. @Value("${oauth.callback.http:http://szwltest.sunzee.com.cn:49002}")
  73. private String http;
  74. @ApiOperation(value = "绑定微信")
  75. @GetMapping("/bindWechat")
  76. public R bindWechat(@RequestParam Long adminId) throws Exception {
  77. if (adminId==null) {
  78. throw new MyException("参数为空");
  79. }
  80. TAdmin tAdmin = tAdminService.getById(adminId);
  81. TWechat tWechat = new TWechat();
  82. if (tAdmin != null) {
  83. List<TWechat> list = tWechatService
  84. .lambdaQuery()
  85. .eq(TWechat::getAdminId, adminId)
  86. .list();
  87. if (!list.isEmpty()) {
  88. tWechat = list.get(0);
  89. tWechatService.updateById(tWechat);
  90. } else {
  91. tWechat.setAdminId(String.valueOf(adminId));
  92. tWechatService.save(tWechat);
  93. }
  94. } else {
  95. throw new MyException("用户不存在!");
  96. }
  97. String path = http + "/tWechat/callback?";
  98. try {
  99. path = URLEncoder.encode(path, "UTF-8");
  100. } catch (UnsupportedEncodingException e) {
  101. throw new RuntimeException(e);
  102. }
  103. // 第一步:用户同意授权,获取code
  104. String url = "http://szwltest.sunzee.com.cn/openWeixin/connect/oauth2/authorize?"
  105. // String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
  106. + "appid=" + appid
  107. + "&redirect_uri=" + path
  108. + "&response_type=code"
  109. + "&scope=snsapi_userinfo"
  110. + "&state=" + adminId +
  111. "#wechat_redirect";
  112. // response.sendRedirect(url);
  113. return R.ok(url);
  114. }
  115. // 绑定微信回调
  116. @GetMapping("/callback")
  117. @CrossOrigin(value = "https://api.weixin.qq.com/")
  118. public JSONObject oauthCallback(HttpServletRequest request) throws IOException {
  119. // 获取code
  120. String code = request.getParameter("code");
  121. String adminId = request.getParameter("state");
  122. // 第二步:通过code换取网页授权access_token
  123. String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
  124. "appid=" + appid +
  125. "&secret=" + appsecret +
  126. "&code=" + code +
  127. "&grant_type=authorization_code";
  128. JSONObject jsonObject = HttpClientUtils.get(url);
  129. String openid = jsonObject.getString("openid");
  130. String accessToken = jsonObject.getString("access_token");
  131. // 第三步:刷新access_token(如果需要)
  132. // 第四步:拉取用户信息(需scope为 snsapi_userinfo)
  133. url = "https://api.weixin.qq.com/sns/userinfo?" +
  134. "access_token=" + accessToken +
  135. "&openid=" + openid +
  136. "&lang=zh_CN";
  137. JSONObject userInfo = HttpClientUtils.get(url);
  138. List<TWechat> list = tWechatService.lambdaQuery()
  139. .eq(TWechat::getAdminId, adminId)
  140. .list();
  141. if (Objects.nonNull(list)) {
  142. TWechat tWechat = list.get(0);
  143. tWechat.setOpenId(userInfo.getString("openid"));
  144. tWechat.setNickName(userInfo.getString("nickname"));
  145. tWechat.setAvatarUrl(userInfo.getString("headimgurl"));
  146. tWechat.setModifyDate(new Date());
  147. tWechatService.updateById(tWechat);
  148. } else {
  149. TWechat tWechat = new TWechat();
  150. tWechat.setOpenId(userInfo.getString("openid"));
  151. tWechat.setNickName(userInfo.getString("nickname"));
  152. tWechat.setAvatarUrl(userInfo.getString("headimgurl"));
  153. tWechat.setCreateDate(new Date());
  154. tWechatService.save(tWechat);
  155. }
  156. return userInfo;
  157. }
  158. }