准备工作:

  1. 配置微信公众号的appId及secret
  2. maven引入binarywang的微信开发包,利用开源代码 weixin-java-tools来开发效率很高,免去了很多繁琐的代码开发量;

appId及secret配置

weixin:
  appId: *************
  secret: *****************
  
@Data
@ConfigurationProperties(prefix = "weixin")
public class WxPayProperties {
  /**
   * 设置微信公众号或者小程序等的appid
   */
  private String appId;
  private String secret;

  @Override
  public String toString() {
    return ToStringBuilder.reflectionToString(this,
        ToStringStyle.MULTI_LINE_STYLE);
  }
}

maven引入

		<dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-mp</artifactId>
            <version>3.1.0</version>
        </dependency>

配置微信操作需要的bean

@Configuration
public class WxConfig {
    private final WxPayProperties wxPayProperties;
    private final CustomWxMpInRedisConfigStorage storage;

    @Autowired
    public WxConfig(WxPayProperties wxPayProperties, CustomWxMpInRedisConfigStorage storage) {
        this.wxPayProperties = wxPayProperties;
        this.storage = storage;
    }

    @Bean
    public WxMpService wxMpService() {
        WxMpService service = new WxMpServiceImpl();
        storage.setAppId(wxPayProperties.getAppId());
        storage.setSecret(wxPayProperties.getSecret());
        service.setWxMpConfigStorage(storage);
        return service;
    }
}

微信控制器


/**
 * @author Chengen
 * @date 2018/8/13
 */
@Controller
public class UserController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private WxMpService wxMpService;

   
    /**
     * 用户登陆(获取token)
     * 微信登陆回调接口
     * @param code
     * @param state 调用时带的参数
     * @return
     * @throws WxErrorException
     */
    @RequestMapping("/user/login")
    public String login(@RequestParam("code") String code, @RequestParam("state") String state) throws WxErrorException {
        logger.info("code-------------------->" + code);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        logger.info("AccessToken-------------------->" + wxMpOAuth2AccessToken.getAccessToken());
		 WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        wxMpOAuth2AccessToken.setAccessToken(wxMpOAuth2AccessToken.getAccessToken());
        // 这里拿到openId 和头像
        WxMpUser wxMpUser = wxConfig.wxMpService().oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        String wxOpenId = wxMpUser.getOpenId();
        String wxHeadImg = wxMpUser.getHeadImgUrl();
        Integer wxSex = wxMpUser.getSex();
        String wxNickName = wxMpUser.getNickname();
		return "redirect:需要重定向的地址" ;
    }
}

最后一步,在微信公众号平台配置自己的域名

前端调用地址:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=填写自己的appid&redirect_uri=

redirect_uri:填写自己的开发环境路径,只能用域名,例如我这里就是http://www.域名.com/user/login (注意该链接一定要使用urlencode转换一下)