一、用戶同意授權(quán)懊亡,獲取code
https://open.weixin.qq.com/connect/oauth2/authorize?appid=****&redirect_uri=uriLink&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
其中uriLink為urlEncode后的獲取code之后的跳轉(zhuǎn)鏈接
appid為自己公眾號的appid
scope為snsapi_userinfo罚舱,以便直接獲取用戶信息
URL編碼代碼如下:
/**
* URL編碼(utf-8)
*
* @param source
* @return
*/
public static String urlEncodeUTF8(String source) {
String result = source;
try {
result = java.net.URLEncoder.encode(source, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
二、通過code換取網(wǎng)頁授權(quán)access_token
/**
* 獲取網(wǎng)頁授權(quán)憑證
*
* appId 公眾賬號的唯一標(biāo)識
* appSecret 公眾賬號的密鑰
* code
* @return WeixinAouth2Token
* @throws JSONException
*/
public static Oauth2Token getOauth2AccessToken(String appId, String appSecret, String code) throws JSONException {
Oauth2Token wat = null;
// 拼接請求地址
String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
requestUrl = requestUrl.replace("APPID", appId);
requestUrl = requestUrl.replace("SECRET", appSecret);
requestUrl = requestUrl.replace("CODE", code);
// 獲取網(wǎng)頁授權(quán)憑證
JSONObject jsonObject = new JSONObject(NetUtil.get(requestUrl));
if (null != jsonObject) {
try {
wat = new Oauth2Token();
wat.setAccessToken(jsonObject.getString("access_token"));
wat.setExpiresIn( (Integer) jsonObject.get("expires_in"));
wat.setRefreshToken(jsonObject.getString("refresh_token"));
wat.setOpenId(jsonObject.getString("openid"));
wat.setScope(jsonObject.getString("scope"));
} catch (Exception e) {
wat = null;
int errorCode = (Integer) jsonObject.get("errcode");
String errorMsg = jsonObject.getString("errmsg");
log.info("獲取網(wǎng)頁授權(quán)憑證失敗 errcode:"+errorCode+" errmsg:"+errorMsg);
}
}
return wat;
}
三伦腐、獲取用戶信息
/**
* 通過網(wǎng)頁授權(quán)獲取用戶信息
*
* accessToken 網(wǎng)頁授權(quán)接口調(diào)用憑證
* openId 用戶標(biāo)識
* @return SNSUserInfo
* @throws JSONException
*/
public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) throws JSONException {
// 拼接請求地址
String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
// 通過網(wǎng)頁授權(quán)獲取用戶信息
JSONObject jsonObject = new JSONObject(NetUtil.get(requestUrl)) ;
log.info("userinfo:"+jsonObject.toString());
if (null != jsonObject) {
try {
snsUserInfo = new SNSUserInfo();
// 用戶的標(biāo)識
snsUserInfo.setOpenId(jsonObject.getString("openid"));
// 昵稱
snsUserInfo.setNickname(jsonObject.getString("nickname"));
// 性別(1是男性灾搏,2是女性泄伪,0是未知)
snsUserInfo.setSex((Integer) jsonObject.get("sex"));
// 用戶所在國家
snsUserInfo.setCountry(jsonObject.getString("country"));
// 用戶所在省份
snsUserInfo.setProvince(jsonObject.getString("province"));
// 用戶所在城市
snsUserInfo.setCity(jsonObject.getString("city"));
// 用戶頭像
snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
// 用戶特權(quán)信息
List<String> list = JSON.parseArray(jsonObject.getString("privilege"),String.class);
snsUserInfo.setPrivilegeList(list);
//與開放平臺共用的唯一標(biāo)識忽你,只有在用戶將公眾號綁定到微信開放平臺帳號后,才會出現(xiàn)該字段臂容。
//snsUserInfo.setUnionid(jsonObject.getString("unionid"));
} catch (Exception e) {
log.info("ex:"+e);
snsUserInfo = null;
int errorCode = (Integer)jsonObject.get("errcode");
String errorMsg = jsonObject.getString("errmsg");
log.info("獲取用戶信息失敗 errcode:"+errorCode+" errmsg:"+errorMsg);
}
}
return snsUserInfo;
}
四科雳、獲取code,獲取網(wǎng)頁授權(quán)access_token并獲取用戶信息
// 用戶同意授權(quán)后脓杉,能獲取到code
Map<String, String[]> params = request.getParameterMap();//針對get獲取get參數(shù)
String[] codes = params.get("code");//拿到code的值
String code = codes[0];//code
log.info("用戶同意授權(quán)獲取到的code:"+code);
// 用戶同意授權(quán)
if (!"authdeny".equals(code)) {
// 獲取網(wǎng)頁授權(quán)access_token
Oauth2Token oauth2Token = getOauth2AccessToken(appid, appSecret, code);
log.info("oauth2Token信息:"+JSON.toJSONString(oauth2Token));
// 網(wǎng)頁授權(quán)接口訪問憑證
String accessToken = oauth2Token.getAccessToken();
log.info("weixinIn-accessToken="+accessToken);
// 用戶標(biāo)識
String openId = oauth2Token.getOpenId();
log.info("weixinIn-openId="+openId);
// 獲取用戶信息
SNSUserInfo snsUserInfo = getSNSUserInfo(accessToken, openId);
snsUserInfo.setNickname(EmojiStringUtil.replaceEmoji(snsUserInfo.getNickname()));
log.info("用戶信息openId:"+snsUserInfo.getOpenId()+", 用戶微信昵稱:"+snsUserInfo.getNickname());
//添加用戶信息到數(shù)據(jù)庫中
return "redirect:****"; //重定向到自己的業(yè)務(wù)邏輯頁面
}else{
log.info("獲取微信用戶信息失敗");
return null;
}
}else{
log.info("當(dāng)前code為:" + code + ", 用戶授權(quán)失斣忝亍!");
return null;
}
五球散、相關(guān)實體類
網(wǎng)頁授權(quán)信息
/**
網(wǎng)頁授權(quán)信息
**/
public class Oauth2Token {
// 網(wǎng)頁授權(quán)接口調(diào)用憑證
private String accessToken;
// 憑證有效時長
private int expiresIn;
// 用于刷新憑證
private String refreshToken;
// 用戶標(biāo)識
private String openId;
// 用戶授權(quán)作用域
private String scope;
//省略getset方法
}
微信用戶信息
/**
微信用戶信息
**/
public class SNSUserInfo {
// 用戶標(biāo)識
private String openId;
// 用戶昵稱
private String nickname;
// 性別(1是男性尿赚,2是女性,0是未知)
private int sex;
// 國家
private String country;
// 省份
private String province;
// 城市
private String city;
// 用戶頭像鏈接
private String headImgUrl;
// 用戶特權(quán)信息
private List<String> privilegeList;
//unionid
private String unionid;
//省略getset方法
}