1.控制层
@RepeatSubmit
@GetMapping("/wxLogin")
@ApiOperation("微信登录")
public R wxLogin(String code) {
Map result = WeiXinUtil.getAccessToken(code,wechatConfig.getAppid(),wechatConfig.getSecret());
String accessToken = result.get("access_token").toString();
String openid = result.get("openid").toString();
Map userInfo = WeiXinUtil.getUserInfo(accessToken, openid);
//业务处理
return R.ok();
}
2.工具类
package com.dcqq.common.utils;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
/**
* 微信登录工具类
*
* @author
* @date 2023/11/1 15:28
*/
public class WeiXinUtil {
private static final String getAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
private static final String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
private static final String getUserInfo = "https://api.weixin.qq.com/sns/userinfo";
/**
* 获取微信AccessToken
* @param code 用户code
* @return
*/
public static Map<?, ?> getAccessToken(String code,String appid,String secret) {
StringBuffer url = new StringBuffer();
url.append(getAccessTokenUrl)
.append("?appid=")
.append(appid)
.append("&secret=")
.append(secret)
.append("&code=")
.append(code)
.append("&grant_type=authorization_code");
String rs = HttpUtil.get(url.toString());
Map map = JSONObject.parseObject(rs, Map.class);
if (null == map.get("errcode")) {
return map;
} else {
throw new RuntimeException("获取access_token出错");
}
}
/**
* 刷新AccessToken
* @param refreshToken
* @return
*/
public static Map refreshToken(String refreshToken,String appid) {
StringBuffer url = new StringBuffer();
url.append(refreshTokenUrl)
.append("?appid=")
.append(appid)
.append("&grant_type=refresh_token&refresh_token=")
.append(refreshToken);
String rs = HttpUtil.get(url.toString());
Map map = JSONObject.parseObject(rs, Map.class);
if (null == map.get("errcode")) {
return map;
} else {
throw new RuntimeException("刷新access_token出错");
}
}
/**
* 获取用户信息
* @param accessToken
* @param openid
* @return
*/
public static Map getUserInfo(String accessToken, String openid) {
StringBuffer url = new StringBuffer();
url.append(getUserInfo)
.append("?access_token=")
.append(accessToken)
.append("&openid=")
.append(openid)
.append("&lang=zh_CN");
String rs = HttpUtil.get(url.toString());
Map map = JSONObject.parseObject(rs, Map.class);
return map;
}
}
3.引入http请求maven
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.27</version>
</dependency>
4.官方测试
https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index