| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273 |
- package com.chuanghai.h3c_reporting.controller;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import com.baomidou.mybatisplus.core.conditions.interfaces.Func;
- import com.chuanghai.h3c_reporting.common.exception.BizCodeEnume;
- import com.chuanghai.h3c_reporting.common.exception.RRException;
- import com.chuanghai.h3c_reporting.common.http.HttpsClient;
- import com.chuanghai.h3c_reporting.common.utils.CommonResult;
- import com.chuanghai.h3c_reporting.entity.InformationReporting;
- import com.chuanghai.h3c_reporting.entity.Message;
- import com.chuanghai.h3c_reporting.entity.SubscribeMessages;
- import com.chuanghai.h3c_reporting.entity.TemplateData;
- import com.chuanghai.h3c_reporting.service.SubscribeMessagesService;
- import org.springframework.beans.BeanUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.http.HttpEntity;
- import org.springframework.http.HttpHeaders;
- import org.springframework.http.ResponseEntity;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.client.RestTemplate;
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.time.LocalDateTime;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Objects;
- import java.util.Set;
- import java.util.stream.Collectors;
- import com.google.gson.Gson;
- import com.google.gson.reflect.TypeToken;
- import lombok.extern.slf4j.Slf4j;
- /**
- * 获取微信绑定手机号
- */
- @Slf4j
- @Controller
- @RequestMapping("/wx")
- public class WxController {
- @Value("${wx.app_id}")
- private String appID;
- @Value("${wx.secret}")
- private String secret;
- @Value("${wx.template_id}")
- private String template_id;
- private String access_token = "";
- InformationReporting reporting = new InformationReporting();
- @Autowired
- private SubscribeMessagesService subscribeMessagesService;
- // 微信开放平台获取openid的接口
- // private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
- /**
- * 通过code换取用户手机号
- */
- @GetMapping("/getPhone")
- @ResponseBody
- public CommonResult<String> getPhone(String code, String state) {
- if (access_token.equals("")) {
- getAccessToken();
- }
- // System.out.println("access_token ======>>>" + access_token);
- try {
- RestTemplate restTemplate = new RestTemplate();
- HttpHeaders headers = new HttpHeaders();
- Map<String, String> paramCardNumber = new HashMap<>();
- // paramCardNumber.put("access_token", access_token);
- paramCardNumber.put("code", code);
- HttpEntity<Map<String, String>> requestM = new HttpEntity<>(paramCardNumber, headers);
- String userInfoUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
- ResponseEntity<String> responsem = restTemplate.postForEntity(userInfoUrl, requestM, String.class);
- JSONObject resPhoneInfo = JSON.parseObject(responsem.getBody());
- System.out.println(resPhoneInfo);
- JSONObject phoneInfo = resPhoneInfo.getJSONObject("phone_info");
- String phoneNumber = phoneInfo.get("phoneNumber").toString();
- return CommonResult.ok().setResult(phoneNumber);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RRException(BizCodeEnume.WX_EXCEPTION, "获取用户绑定的手机号失败");
- }
- }
- // 获取access_token
- @Scheduled(cron = "0 59 0/1 * * ?") // 每1小时59分,执行一次刷新access_token
- public void getAccessToken() {
- // Map<String, String> token = new HashMap<>();
- // token.put("appid", appID);
- // token.put("secret", secret);
- // token.put("grant_type", "client_credential");
- String url = "https://api.weixin.qq.com/cgi-bin/token?" +
- "grant_type=client_credential" +
- "&appid=" + appID +
- "&secret=" + secret;
- RestTemplate restTemplate = new RestTemplate();
- // HttpHeaders headers = new HttpHeaders();
- // headers.setContentType(MediaType.APPLICATION_JSON);
- // HttpEntity<Map<String, String>> request = new HttpEntity<>(token, headers);
- ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
- JSONObject objParam = JSON.parseObject(responseEntity.getBody());
- System.out.println(objParam);
- for (Map.Entry<String, Object> entry : objParam.entrySet()) {
- Object o = entry.getValue();
- if (o instanceof String) {
- if (entry.getKey().equals("access_token")) {
- access_token = (String) entry.getValue();
- }
- }
- }
- // System.out.println(access_token);
- // return access_token;
- }
- /**
- * 获取用户在微信中的openid
- *
- * @param code 用户授权后得到的code
- * @return 用户的openid
- */
- @GetMapping("/getOpenId")
- @ResponseBody
- public String getOpenId(String code) throws IOException {
- // access_token是存在有效期的,过期就刷新
- if (access_token.equals("")) {
- getAccessToken();
- }
- // 构造请求URL
- //String requestUrl = OPENID_URL + "?appid=" + appID + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
- String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appID + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
- // 发送请求并获取响应
- URL url = new URL(requestUrl);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setRequestMethod("GET");
- connection.setDoOutput(true);
- connection.setDoInput(true);
- connection.connect();
- InputStream inputStream = connection.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
- StringBuilder stringBuilder = new StringBuilder();
- String line;
- while ((line = reader.readLine()) != null) {
- stringBuilder.append(line);
- }
- reader.close();
- connection.disconnect();
- // 解析响应结果,提取openid
- String response = stringBuilder.toString();
- String openid = null;
- if (response.contains("openid")) {
- int beginIndex = response.indexOf("openid") + 9;
- int endIndex = response.indexOf("\"", beginIndex);
- openid = response.substring(beginIndex, endIndex);
- }
- //模拟数据
- //System.out.println(code);
- //String openid = "1234512345123451234512345123";
- System.out.println(openid);
- return openid;
- /* SubscribeMessages subscribeMessages = new SubscribeMessages();
- subscribeMessages.setId(id);
- subscribeMessages.setOpenid(openid);*/
- /* boolean flag = subscribeMessagesService.save(subscribeMessages);
- if (flag) {
- log.info("保存openid成功");
- return CommonResult.ok();
- } else {
- log.info("保存openid失败");
- return CommonResult.fail();
- }*/
- }
- /*
- * 小程序订阅消息
- *
- * 前端传 openid,审核结果result,备注ps
- * */
- /* @GetMapping("/send")
- public String send(String openid,String ps) throws Exception {
- // access_token是存在有效期的,过期就刷新
- if (access_token.equals("")) {
- getAccessToken();
- }
- //拿到审核结果
- InformationReporting reporting1 = new InformationReporting();
- //String title = reporting1.getTitle();
- JSONObject message = new JSONObject();
- message.put("touser", openid);
- message.put("template_id", template_id);
- message.put("page", "index");
- message.put("miniprogram_state", "formal");
- message.put("lang", "zh_CN");
- JSONObject data = new JSONObject();
- // 审核结果
- JSONObject thing1 = new JSONObject();
- thing1.put("value", title);//变为title
- // 备注
- JSONObject thing5 = new JSONObject();
- thing5.put("value", ps);
- // 审核结果
- data.put("thing1",thing1);
- // 备注
- data.put("thing5",thing5);
- message.put("data", data);
- System.out.println(message);
- return HttpsClient.sendJson("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+access_token, message);
- }*/
- //发送订阅消息
- /*private String push(String openid) throws Exception{
- RestTemplate restTemplate = new RestTemplate();
- // access_token是存在有效期的,过期就刷新
- if (access_token.equals("")) {
- getAccessToken();
- }
- //getAccessToken
- // 没有加redis,每次获取最新的sendURL
- String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token;
- //拼接推送的模版
- Message message = new Message();
- message.setTouser(openid);//用户的openid
- message.setTemplate_id(template_id);//订阅消息模板id
- //message.setPage("pages/index/index");
- Map<String, TemplateData> m = new HashMap<>();
- m.put("thing1", new TemplateData("审核结果"));
- m.put("thing5", new TemplateData("备注"));
- message.setData(m);
- ResponseEntity<String> responseEntity =
- restTemplate.postForEntity(url, message, String.class);
- return responseEntity.getBody();
- }*/
- }
|