第一步:用户同意授权,获取code 引导用户进入授权的URL 修改一些参数
在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(服务号获得高级接口后,默认带有scope参数中的snsapi_base和snsapi_userinfo),引导关注者打开如下页面:本作者用菜单的方式引导用户点击进入。
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
我的代码如下:一个Servlet请求 获取code
/**
* 根据code取得openId
*
* @param appid 公众号的唯一标识
* @param secret 公众号的appsecret密钥
* @param code code为换取access_token的票据
* @return
*/public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//参数
String code = request.getParameter("code");
if(null != code && !"".equals(code)){
log.info("==============[OAuthServlet]获取网页授权code不为空,code="+code);
//根据code换取openId
OAuthInfo oa = WeixinUtil.getOAuthOpenId(Constants.appId,Constants.appSecret,code);
UserInfo info = WeixinUtil.getUserInfo(oa.getAccessToken(), oa.getOpenId());
if(!"".equals(oa) && null != oa){
request.setAttribute("openid", oa.getOpenId());
request.setAttribute("nickname", info.getNickname());
request.getRequestDispatcher("/index.jsp").forward(request, response);
}else{
log.info("==============[OAuthServlet]获取网页授权openId失败!");
}
}else{
log.info("==============[OAuthServlet]获取网页授权code失败!");
}
}
替换相应的APPID APPSECRET SCOPE
第二步:通过code换取网页授权access_token 这里的access_token与基础获取的access_token不同
获取code后,请求以下链接获取access_token:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
具体做法与上面基本一致。更换相对应的值。需要注意的是code可以写一个Servlet获取。String code = request.getParameter("code");get/post都可以。
这样子就会返回一下json格式数据
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}
具体代码如下。获取的code换取的access_token
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code;
public static OAuthInfo getOAuthOpenId(String appid, String secret, String code ) {
OAuthInfo oAuthInfo = null;
String o_auth_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code;";
String requestUrl = o_auth_openid_url.replace("APPID", appid).replace("SECRET", secret).replace("CODE", code);
JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
//oAuthInfo是作者自己把那几个属性参数写在一个类里面了。
// 如果请求成功
if (null != jsonObject) {
try {
oAuthInfo = new OAuthInfo();
oAuthInfo.setAccessToken(jsonObject.getString("access_token"));
oAuthInfo.setExpiresIn(jsonObject.getInt("expires_in"));
oAuthInfo.setRefreshToken(jsonObject.getString("refresh_token"));
oAuthInfo.setOpenId(jsonObject.getString("openid"));
oAuthInfo.setScope(jsonObject.getString("scope"));
} catch (JSONException e) {
oAuthInfo = null;
// 获取token失败
log.error("网页授权获取openId失败 errcode:{} errmsg:{}", jsonObject
.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
return oAuthInfo;
}
根据上面代码获取的access_token openid 然后再请求获取userinfo的接口。就能得到微信用户的所有信息了。
这就获取到用户的openid。应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)我自己用的作用域为snsapi_userinfo。用户点击跳转页面为
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
替换链接里面的大写字母的信息为你自己公众号的。state可以不改。
写一个Servlet专门接收传递过来的code。进行相应的操作。
1.OAuthServlet 对code进行access——token的验证
2.一个Servlet的方法调用接口地址。得到相应code。
3.OAuthInfo 返回数据相应的参数的PO类。set/get方法
4.WeiXinUtil添加一个方法 publicOAuth getOAuthInfo(String appid, String secret, String code)得到json格式。并使用JSONObject读取出自己想要的数据。
参考微信文档地址:https://mp.weixin.qq.com/paymch/readtemplate?t=mp/business/course3_tmpl&lang=zh_CN