springboot实现用户信息授权获取用户的id

时间:2024-05-20 22:57:27

 

最近用微信公众号做第三方登录,看着网上的教程,真是有苦难言,写得乱七八糟。不过也发现了比较好的文章。我这里记录一下我实现的过程。

pom.xml是这个

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

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

	</dependencies>

 

application.yml

wechat:
  mpAppId: wx53f2d3edfbc962aa
  mpAppSecret: 8494b0d33acb6573d37e1616e6c86775
server:
  #端口号
  port: 80

wechatController

package com.wechat.controller;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;

import java.net.URLEncoder;

@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

    @Autowired
    private WxMpService wxMpService;

    @GetMapping("/authorize")
    public String authorize(){
        String url = "http:example.com/wechat/userInfo";
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE, null);
        log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        return "redirect:" + redirectURL;
    }

    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                         @RequestParam("state") String returnUrl) throws Exception {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("【微信网页授权】openId={}", openId);
        return "redirect:" + returnUrl + "?openid=" + openId;
    }
}

有的人会问example.com怎么来的,这里我用到了natapp (https://natapp.cn/),这个要自己掏钱买了,然后跟着教程配置内网穿透,然后就可以运行了。

第一个方法会产生一个url,把这个url放到你的手机端,注意url不是localhost的url,是example.com/...这个url,然后点击,第二个方法就接收到你的点击操作了,会打印出openid之类的值。

微信公众号要配置一***意添加的时候把http://去掉,不然会报错哈:

springboot实现用户信息授权获取用户的id

参考文献

[1].基于Springboot的微信公众号接入、通过网页授权机制获取用户信息. https://blog.****.net/qq_32347235/article/details/53931822