1、配置回调域名(注意必须腾讯能够访问到的外网,也就是回调URL的IP或者域名)
1、通过code换取access_token
/**
* 获取网页授权凭证
*
* @param appId 公众账号的唯一标识
* @param appSecret 公众账号的密钥
* @param code
* @return WeixinAouth2Token
*/
public static WeixinOauth2Token getOauth2AccessToken(String appId, String appSecret, String code) {
WeixinOauth2Token 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);
// 获取网页授权凭证
JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
if (null != jsonObject) {
try {
wat = new WeixinOauth2Token();
wat.setAccessToken(jsonObject.getString("access_token"));
wat.setExpiresIn(jsonObject.getInt("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 = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
}
}
return wat;
}
2、拉去用户信息(注意:现在有uniond)
/**
* 通过网页授权获取用户信息
*
* @param accessToken 网页授权接口调用凭证
* @param openId 用户标识
* @return SNSUserInfo
*/
@SuppressWarnings( { "deprecation", "unchecked" })
public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
SNSUserInfo snsUserInfo = null;
// 拼接请求地址
String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
// 通过网页授权获取用户信息
JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
if (null != jsonObject) {
try {
snsUserInfo = new SNSUserInfo();
// 用户的标识
snsUserInfo.setOpenId(jsonObject.getString("openid"));
// 昵称
snsUserInfo.setNickname(jsonObject.getString("nickname"));
// 性别(1是男性,2是女性,0是未知)
snsUserInfo.setSex(jsonObject.getInt("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"));
// 用户特权信息
snsUserInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
} catch (Exception e) {
snsUserInfo = null;
int errorCode = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
}
}
return snsUserInfo;
}
3、Servlet验证回调
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("gb2312");
response.setCharacterEncoding("gb2312");
// 用户同意授权后,能获取到code
String code = request.getParameter("code");
// 用户同意授权
if (!"authdeny".equals(code)) {
// 获取网页授权access_token
WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken("appId", "appSecret", code);
// 网页授权接口访问凭证
String accessToken = weixinOauth2Token.getAccessToken();
// 用户标识
String openId = weixinOauth2Token.getOpenId();
// 获取用户信息
SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openId);
// 设置要传递的参数
request.setAttribute("snsUserInfo", snsUserInfo);
}
// 跳转到index.jsp
request.getRequestDispatcher("wechat.jsp").forward(request, response);
}
4、jsp回调效果页面
<%
// 获取由OAuthServlet中传入的参数
SNSUserInfo user = (SNSUserInfo)request.getAttribute("snsUserInfo");
if(null != user) {
%>
<table width="100%" cellspacing="0" cellpadding="0">
<tr><td width="20%">属性</td><td width="80%">值</td></tr>
<tr><td>OpenID</td><td><%=user.getOpenId()%></td></tr>
<tr><td>昵称</td><td><%=user.getNickname()%></td></tr>
<tr><td>性别</td><td><%=user.getSex()%></td></tr>
<tr><td>国家</td><td><%=user.getCountry()%></td></tr>
<tr><td>省份</td><td><%=user.getProvince()%></td></tr>
<tr><td>城市</td><td><%=user.getCity()%></td></tr>
<tr><td>头像</td><td><%=user.getHeadImgUrl()%></td></tr>
<tr><td>特权</td><td><%=user.getPrivilegeList()%></td></tr>
</table>
<%
}
else
out.print("用户不同意授权,未获取到用户信息!");
%>
5、发送URL到微信(加密回调的URL)
https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=你加密后的回调URL&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
/**
* 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;
}
注意:
1、这里是先讲解代码,再登录请求
2、这个博客中的微信机器人中包括的登录不是OAuth2.0,我觉得应该是通过微信开放平台的接口(这个登录应该是网站登录,这个OAuth2.0是授权登录(微信客户端))(http://my.oschina.net/biezhi/blog/618493?fromerr=vy6WIPOx)
3、最后一步发送的URL必须在微信中打开
4、Demo: http://yunpan.cn/cLTssBMDMmmBB 访问密码 b34b(我的博客中的微信开放第一步中也有)