注意:获取到unionid需要绑定到公众平台否则获取不到
直接代码
1.第一步在application.yml中添加必要配置
#配置微信的信息
wx:
appId: ---------
appSecret: ------------
grantType: authorization_code
requestUrl: https://api.weixin.qq.com/sns/jscode2session
wxToken:
url: https://api.weixin.qq.com/sns/oauth2/access_token
wxUnionId:
url: https://api.weixin.qq.com/sns/userinfo
2.创建compoent将配置文件的属性绑定到方法中
package com.landimc.compoent; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.databind.ObjectMapper; import com.landimc.tools.AES; import com.landimc.tools.HttpUtils; import org.springframework.beans.factory.annotation.ParameterResolutionDelegate; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; /** * 微信工具 * * @auther Yang * @createTime 9:20 * @Version 1.0 */ @Component public class WxConfig { @Value("${wx.appId}") private String appId; @Value("${backedWx.appId}") private String backedAppId; @Value("${backedWx.AppSecret}") private String backedAppSecret; @Value("${wx.appSecret}") private String appSecret; @Value("${wx.grantType}") private String grantType; @Value("${wx.requestUrl}") private String requestUrl; @Value("${wxToken.url}") private String tokenUrl; @Value("${wxUnionId.url}") private String unionUrl; /*获取用户的openid*/ @SuppressWarnings("unchecked") public Map<String, Object> getSessionByCode(String code) { Map<String, Object> json = null; try { String url = requestUrl + "?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=" + grantType; // 发送请求 String data = HttpUtils.get(url); ObjectMapper mapper = new ObjectMapper(); json = mapper.readValue(data, Map.class); } catch (Exception e) { e.printStackTrace(); } return json; } /*获取用户的access_token*/ @SuppressWarnings("unchecked") public Map<String, Object> getUserAccessToken(String code) { Map<String, Object> json = null; try { String url = tokenUrl + "?appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code"; // 发送请求 System.out.println(url); String data = HttpUtils.get(url); ObjectMapper mapper = new ObjectMapper(); json = mapper.readValue(data, Map.class); } catch (Exception e) { e.printStackTrace(); } return json; } /*获取用户的unionId*/ @SuppressWarnings("unchecked") public Map<String, Object> getUnionId(String token, String openId) throws Exception { Map<String, Object> json = null; try { String url = unionUrl + "?access_token=" + token + "&openid=" + openId; // 发送请求 String data = HttpUtils.get(url); ObjectMapper mapper = new ObjectMapper(); json = mapper.readValue(data, Map.class); } catch (Exception e) { e.printStackTrace(); } return json; } }
3.controller层
/** * 根据微信code获取微信信息 * * @param code 微信临时code * @return */ @ApiOperation(value = "微信的code置换微信openid和unionid - 管理员用的") @ResponseBody @RequestMapping(value = "/backedUserLogin", method = {RequestMethod.GET, RequestMethod.POST}) public String backedUserLogin(@RequestParam(value = "code") String code, @RequestParam(value = "iv") String iv, @RequestParam(value = "encryptedData") String encryptedData) { logger.info("根据微信code获取微信信息--后台用户请求"); BackResult backResult = new BackResult(); BizResult bizResult = new BizResult(); try { //获取用户的openId和用于的session_key Map<String, Object> map = wxConfig.getBackedSessionByCode(code); //判断置换的openid是否正确 if (map.isEmpty()) { bizResult.setCode(BizSuccessType.UNSUCCESS); bizResult.setMsg("获取用户微信信息错误!"); bizResult.setDevMsg("微信的code错误!"); } else { String session_key = map.get("session_key").toString(); String openId = map.get("openid").toString(); String decrypt = AES.decrypt(session_key, iv, encryptedData); bizResult.setCode(BizSuccessType.SUCCESS); bizResult.setMsg("获取用户微信信息成功!"); //将json字符串转换为JSON对象 JSONObject jsonObject = JSON.parseObject(decrypt); backResult.setData(jsonObject); //生成token String token = MD5.getMd5(UUID.randomUUID().toString().replace("-", ""), 32); } } catch (Exception ex) { ex.printStackTrace(); bizResult.setCode(BizSuccessType.BIZAPPEX); bizResult.setMsg("获取用户微信信息失败!"); bizResult.setDevMsg(ex.getMessage()); ex.printStackTrace(); } backResult.setBizResult(bizResult); return JSON.toJSONString(backResult); }
前端记得传递三个参数 都可以从微信那边获取到 这个自己看看微信登录的方法
code iv encryptedData