一、准备工作
1、准备需要的配置参数(APPID、APPSecret)
2、网页授权域名(位置:公众号设置->功能设置)
二、代码实现
#微信公众号
wechat:
appid: 123455667878
appSecret: aabcdsrdsfdgdfrgtr466446
#snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid)
# snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地
scope: snsapi_base
authUrl: https://open.weixin.qq.com/connect/oauth2/authorize
public Result<?> weChatCallback(String code) {
if (StringUtils.isBlank(code)) {
return Result.error("");
}
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid +
"&secret=" + appSecret +
"&code=" + code +
"&grant_type=authorization_code";
//进行网络请求,访问微信服务器接口
CmLwcsePaymentUser user = null;
com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(NetUtil.get(url));
try {
if (null != jsonObject) {
System.out.println("==========================jsonObject" + jsonObject);
//从返回的JSON数据中取出access_token和openid,拉取用户信息时用
//网页授权接口调用凭证
String accessToken = jsonObject.getString("access_token");
//用户刷新access_token
String refresh_token = jsonObject.getString("refresh_token");
//access_token接口调用凭证超时时间
String expires_in = jsonObject.getString("expires_in");
//用户授权的作用域
String scope = jsonObject.getString("scope");
//用户唯一标识
String openid = jsonObject.getString("openid");
if (StringUtils.isBlank(openid)) {
return Result.error("信息有误");
}
//业务逻辑
}
} catch (Exception e) {
int errorCode = jsonObject.getInteger("errcode");
String errorMsg = jsonObject.getString("errmsg");
log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
e.printStackTrace();
}
return Result.OK(user);
}
//获取用户信息
public static CmLwcsePaymentUser getUserInfo(String accessToken, String openId, CmLwcsePaymentUser snsUserInfo) {
// 拼接请求地址
String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
// 通过网页授权获取用户信息
com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(NetUtil.get(requestUrl));
if (null != jsonObject) {
try {
snsUserInfo = new CmLwcsePaymentUser();
// 用户的标识
snsUserInfo.setOpenId(jsonObject.getString("openid"));
// 昵称
snsUserInfo.setNickName(jsonObject.getString("nickname"));
// 性别(1是男性,2是女性,0是未知)
snsUserInfo.setSex(jsonObject.getInteger("sex"));
// 用户所在国家
snsUserInfo.setCountry(jsonObject.getString("country"));
// 用户所在省份
snsUserInfo.setProvince(jsonObject.getString("province"));
// 用户所在城市
snsUserInfo.setCity(jsonObject.getString("city"));
// 用户头像
snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
//与开放平台共用的唯一标识,只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
snsUserInfo.setUnionId(jsonObject.getString("unionid"));
} catch (Exception e) {
snsUserInfo = null;
int errorCode = jsonObject.getInteger("errcode");
String errorMsg = jsonObject.getString("errmsg");
log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
}
}
return snsUserInfo;
}
工具类:
public final class NetUtil {
public static CloseableHttpClient httpClient = HttpClientBuilder.create().build();
/**
* get请求获取String类型数据
* @param url 请求链接
* @return
*/
public static String get(String url){
StringBuffer sb = new StringBuffer();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpGet); //1
HttpEntity entity = response.getEntity();
InputStreamReader reader = new InputStreamReader(entity.getContent(),"utf-8");
char [] charbufer;
while (0<reader.read(charbufer=new char[10])){
sb.append(charbufer);
}
}catch (IOException e){//1
e.printStackTrace();
}finally {
httpGet.releaseConnection();
}
return sb.toString();
}
参考微信公众号开发文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
注意事项: