1. 依赖
<properties><weixin-java.version>4.2.0</weixin-java.version></properties><dependencies><dependency><groupId>com.github.binarywang</groupId><artifactId>weixin-java-mp</artifactId><version>${weixin-java.version}</version></dependency>
</dependencies>
2. 方法
package com.gblfy.wx.h5.controller;import com.gblfy.wx.h5.vo.ResponseDto;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.io.IOException;/*** 登录获取用户信息入口** @author gblfy* @date 2021-12-28*/
@RestController
@AllArgsConstructor
public class LoginController {private static final Logger logger = LoggerFactory.getLogger(LoginController.class);private final WxMpService wxMpService;/*** 获取用户信息* <p>* 1.接收前端code参数* 2.通过code、Appid、Secret参数获取 access_token和openid* 3.通过access_token和openid获取用户基本信息* </p>*/@PostMapping("/login")public ResponseDto getCode(@RequestParam(value = "code", required = true) String code) throws IOException, WxErrorException {logger.info("接收前端code-> 【{}】", code);WxOAuth2AccessToken wxOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);logger.info("access_token-> 【{}】", wxOAuth2AccessToken.getAccessToken());logger.info("openid-> 【{}】", wxOAuth2AccessToken.getOpenId());WxOAuth2UserInfo userInfo = wxMpService.getOAuth2Service().getUserInfo(wxOAuth2AccessToken, null);logger.info("nickname-> 【{}】", userInfo.getNickname());logger.info("headimgurl-> 【{}】", userInfo.getHeadImgUrl());logger.info("openid-> 【{}】", userInfo.getOpenid());ResponseDto responseDto = new ResponseDto();responseDto.setContent(userInfo);return responseDto;}
}