微信公众号网页OAuth2.0授权登录并获取用户信息(SpringBoot实现)
文章目录
准备工作
如果是正式公众号只能填已经备案的域名且使用80端口,测试号可以填ip,ip:端口,或者域名:端口,本地ip(127.0.0.1)也是可以调通的
正式公众号还需要将下面这个文件放到服务器上 ,放在一个可以用 xxx.fun/文件名访问的地方
开发思路
- 开发一个接口,使用户点击这个接口的链接之后重定向到微信给定的授权页面【https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect】(注意里面的参数redirect_uri)
- 用户来到这个页面点击同意
- 用户同意授权,微信服务器将会以参数的形式给你返回一个code到上面重定向链接的参数redirect_uri
- 所以我们还要开发一个接口用来接收这个code,接口的链接就是上面重定向链接的参数redirect_uri
具体代码
编写一个WxConstant.java常量类用来存放公众号的一些信息,也可以在application.yml里面配置
//服务号
//APPID
public static final String SERVICE_APPID = "wxc***";
//授权成功后重定向的前端页面
public static final String BASE_URL = "http://xxx.fun/home";
//APPSECRET
public static final String SERVICE_APPSECRET = "c7c***";
//授权URL
public static final String AUTH_BASE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?";
//获取token
public static final String ACCESS_TOKEN_BASE_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?";
//获取用户信息
public static final String INFO_BASE_URL = "https://api.weixin.qq.com/sns/userinfo?";
//授权回调
public static final String REDIRECT_URL = "http://xxx.fun/weixin/auth";
//授权允许的范围
public static final String SCOPE = "snsapi_userinfo";
编写重定向到微信要求用户授权页面的接口
/**
* create by: Antares
* description: 服务号授权登录(引导用户授权)
* create time: 2020/5/25 14:13
* return
**/
@GetMapping ("/login")
public void doWxLogin (HttpServletRequest request, HttpServletResponse response) {
try {
loginService.doWxLogin (request, response)