WxController.java 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package com.chuanghai.h3c_reporting.controller;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.baomidou.mybatisplus.core.conditions.interfaces.Func;
  5. import com.chuanghai.h3c_reporting.common.exception.BizCodeEnume;
  6. import com.chuanghai.h3c_reporting.common.exception.RRException;
  7. import com.chuanghai.h3c_reporting.common.http.HttpsClient;
  8. import com.chuanghai.h3c_reporting.common.utils.CommonResult;
  9. import com.chuanghai.h3c_reporting.entity.InformationReporting;
  10. import com.chuanghai.h3c_reporting.entity.Message;
  11. import com.chuanghai.h3c_reporting.entity.SubscribeMessages;
  12. import com.chuanghai.h3c_reporting.entity.TemplateData;
  13. import com.chuanghai.h3c_reporting.service.SubscribeMessagesService;
  14. import org.springframework.beans.BeanUtils;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import org.springframework.beans.factory.annotation.Value;
  17. import org.springframework.http.HttpEntity;
  18. import org.springframework.http.HttpHeaders;
  19. import org.springframework.http.ResponseEntity;
  20. import org.springframework.scheduling.annotation.Scheduled;
  21. import org.springframework.stereotype.Controller;
  22. import org.springframework.web.bind.annotation.GetMapping;
  23. import org.springframework.web.bind.annotation.RequestMapping;
  24. import org.springframework.web.bind.annotation.ResponseBody;
  25. import org.springframework.web.client.RestTemplate;
  26. import java.io.*;
  27. import java.net.HttpURLConnection;
  28. import java.net.URL;
  29. import java.net.URLEncoder;
  30. import java.time.LocalDateTime;
  31. import java.util.HashMap;
  32. import java.util.Map;
  33. import java.util.Objects;
  34. import java.util.Set;
  35. import java.util.stream.Collectors;
  36. import com.google.gson.Gson;
  37. import com.google.gson.reflect.TypeToken;
  38. import lombok.extern.slf4j.Slf4j;
  39. /**
  40. * 获取微信绑定手机号
  41. */
  42. @Slf4j
  43. @Controller
  44. @RequestMapping("/wx")
  45. public class WxController {
  46. @Value("${wx.app_id}")
  47. private String appID;
  48. @Value("${wx.secret}")
  49. private String secret;
  50. @Value("${wx.template_id}")
  51. private String template_id;
  52. private String access_token = "";
  53. InformationReporting reporting = new InformationReporting();
  54. @Autowired
  55. private SubscribeMessagesService subscribeMessagesService;
  56. // 微信开放平台获取openid的接口
  57. // private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
  58. /**
  59. * 通过code换取用户手机号
  60. */
  61. @GetMapping("/getPhone")
  62. @ResponseBody
  63. public CommonResult<String> getPhone(String code, String state) {
  64. if (access_token.equals("")) {
  65. getAccessToken();
  66. }
  67. // System.out.println("access_token ======>>>" + access_token);
  68. try {
  69. RestTemplate restTemplate = new RestTemplate();
  70. HttpHeaders headers = new HttpHeaders();
  71. Map<String, String> paramCardNumber = new HashMap<>();
  72. // paramCardNumber.put("access_token", access_token);
  73. paramCardNumber.put("code", code);
  74. HttpEntity<Map<String, String>> requestM = new HttpEntity<>(paramCardNumber, headers);
  75. String userInfoUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
  76. ResponseEntity<String> responsem = restTemplate.postForEntity(userInfoUrl, requestM, String.class);
  77. JSONObject resPhoneInfo = JSON.parseObject(responsem.getBody());
  78. System.out.println(resPhoneInfo);
  79. JSONObject phoneInfo = resPhoneInfo.getJSONObject("phone_info");
  80. String phoneNumber = phoneInfo.get("phoneNumber").toString();
  81. return CommonResult.ok().setResult(phoneNumber);
  82. } catch (Exception e) {
  83. e.printStackTrace();
  84. throw new RRException(BizCodeEnume.WX_EXCEPTION, "获取用户绑定的手机号失败");
  85. }
  86. }
  87. // 获取access_token
  88. @Scheduled(cron = "0 59 0/1 * * ?") // 每1小时59分,执行一次刷新access_token
  89. public void getAccessToken() {
  90. // Map<String, String> token = new HashMap<>();
  91. // token.put("appid", appID);
  92. // token.put("secret", secret);
  93. // token.put("grant_type", "client_credential");
  94. String url = "https://api.weixin.qq.com/cgi-bin/token?" +
  95. "grant_type=client_credential" +
  96. "&appid=" + appID +
  97. "&secret=" + secret;
  98. RestTemplate restTemplate = new RestTemplate();
  99. // HttpHeaders headers = new HttpHeaders();
  100. // headers.setContentType(MediaType.APPLICATION_JSON);
  101. // HttpEntity<Map<String, String>> request = new HttpEntity<>(token, headers);
  102. ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
  103. JSONObject objParam = JSON.parseObject(responseEntity.getBody());
  104. System.out.println(objParam);
  105. for (Map.Entry<String, Object> entry : objParam.entrySet()) {
  106. Object o = entry.getValue();
  107. if (o instanceof String) {
  108. if (entry.getKey().equals("access_token")) {
  109. access_token = (String) entry.getValue();
  110. }
  111. }
  112. }
  113. // System.out.println(access_token);
  114. // return access_token;
  115. }
  116. /**
  117. * 获取用户在微信中的openid
  118. *
  119. * @param code 用户授权后得到的code
  120. * @return 用户的openid
  121. */
  122. @GetMapping("/getOpenId")
  123. @ResponseBody
  124. public String getOpenId(String code) throws IOException {
  125. // access_token是存在有效期的,过期就刷新
  126. if (access_token.equals("")) {
  127. getAccessToken();
  128. }
  129. // 构造请求URL
  130. //String requestUrl = OPENID_URL + "?appid=" + appID + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
  131. String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appID + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
  132. // 发送请求并获取响应
  133. URL url = new URL(requestUrl);
  134. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  135. connection.setRequestMethod("GET");
  136. connection.setDoOutput(true);
  137. connection.setDoInput(true);
  138. connection.connect();
  139. InputStream inputStream = connection.getInputStream();
  140. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
  141. StringBuilder stringBuilder = new StringBuilder();
  142. String line;
  143. while ((line = reader.readLine()) != null) {
  144. stringBuilder.append(line);
  145. }
  146. reader.close();
  147. connection.disconnect();
  148. // 解析响应结果,提取openid
  149. String response = stringBuilder.toString();
  150. String openid = null;
  151. if (response.contains("openid")) {
  152. int beginIndex = response.indexOf("openid") + 9;
  153. int endIndex = response.indexOf("\"", beginIndex);
  154. openid = response.substring(beginIndex, endIndex);
  155. }
  156. //模拟数据
  157. //System.out.println(code);
  158. //String openid = "1234512345123451234512345123";
  159. System.out.println(openid);
  160. return openid;
  161. /* SubscribeMessages subscribeMessages = new SubscribeMessages();
  162. subscribeMessages.setId(id);
  163. subscribeMessages.setOpenid(openid);*/
  164. /* boolean flag = subscribeMessagesService.save(subscribeMessages);
  165. if (flag) {
  166. log.info("保存openid成功");
  167. return CommonResult.ok();
  168. } else {
  169. log.info("保存openid失败");
  170. return CommonResult.fail();
  171. }*/
  172. }
  173. /*
  174. * 小程序订阅消息
  175. *
  176. * 前端传 openid,审核结果result,备注ps
  177. * */
  178. /* @GetMapping("/send")
  179. public String send(String openid,String ps) throws Exception {
  180. // access_token是存在有效期的,过期就刷新
  181. if (access_token.equals("")) {
  182. getAccessToken();
  183. }
  184. //拿到审核结果
  185. InformationReporting reporting1 = new InformationReporting();
  186. //String title = reporting1.getTitle();
  187. JSONObject message = new JSONObject();
  188. message.put("touser", openid);
  189. message.put("template_id", template_id);
  190. message.put("page", "index");
  191. message.put("miniprogram_state", "formal");
  192. message.put("lang", "zh_CN");
  193. JSONObject data = new JSONObject();
  194. // 审核结果
  195. JSONObject thing1 = new JSONObject();
  196. thing1.put("value", title);//变为title
  197. // 备注
  198. JSONObject thing5 = new JSONObject();
  199. thing5.put("value", ps);
  200. // 审核结果
  201. data.put("thing1",thing1);
  202. // 备注
  203. data.put("thing5",thing5);
  204. message.put("data", data);
  205. System.out.println(message);
  206. return HttpsClient.sendJson("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+access_token, message);
  207. }*/
  208. //发送订阅消息
  209. /*private String push(String openid) throws Exception{
  210. RestTemplate restTemplate = new RestTemplate();
  211. // access_token是存在有效期的,过期就刷新
  212. if (access_token.equals("")) {
  213. getAccessToken();
  214. }
  215. //getAccessToken
  216. // 没有加redis,每次获取最新的sendURL
  217. String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token;
  218. //拼接推送的模版
  219. Message message = new Message();
  220. message.setTouser(openid);//用户的openid
  221. message.setTemplate_id(template_id);//订阅消息模板id
  222. //message.setPage("pages/index/index");
  223. Map<String, TemplateData> m = new HashMap<>();
  224. m.put("thing1", new TemplateData("审核结果"));
  225. m.put("thing5", new TemplateData("备注"));
  226. message.setData(m);
  227. ResponseEntity<String> responseEntity =
  228. restTemplate.postForEntity(url, message, String.class);
  229. return responseEntity.getBody();
  230. }*/
  231. }