微信OAuth授权获取用户OpenId
https://open.weixin.qq.com/ 这个是授权登陆自己网站的和我的这个是有区别的。
博客最新更改在这里https://my.oschina.net/xshuai/blog/293458 
鉴于老是有人问我。就更新一下了。
更新时间 2016年1月13日
 
http://mp.weixin.qq.com/wiki这个是官网的接口文档
微信授权获取用户openid-JAVA
开发微信测试需要用到的代码和jar包都在里面  包括核心代码 
 上面图片可以扫一扫 支持一下。
链接: http://mobile.qzone.qq.com/l?g=1357&sharekey=e43cb6432868c4b709c5351c3c82d3de
注意:授权把回调域名配置了。(只需要域名就行 例如:www.baidu.com)
没有配置回调域名有问题就别问我了。
拉取用户信息(需scope为 snsapi_userinfo)
本作者是用菜单的方式引导用户进入点击获取信息的。不会创建菜单的自己去看官网API。或者搜索教程。先把官网文档稍微看下。知道自己需要配置的域名。等一些参数。点个赞都不给。就什么问题也问。还有。我工作不是专门做微信这方面的。我也需要忙我自己的工作内容。
如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。
前提设置一个菜单调用授权接口的URL获取code
修改相应的参数后的链接(只是一个例子) 创建一个view类型的菜单。url如下:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2d39c6c31ed5f199&redirect_uri=http://zxshuai.imwork.net/weixin/oauth.do &response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect
截图示意
第一步:用户同意授权,获取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
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
 | 
/**     * 根据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 
| 
 1 
 | 
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code; | 
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
 | 
    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的接口。就能得到微信用户的所有信息了。
具体返回如下。获取用户信息代码不再写。
| 
 1 
 | 
 请求获取用户信息的接口地址 | 
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
 | 
{"sex":1,"nickname":"小帅","privilege":[],"province":"北京","openid":"o2VKNju8JqCeGVoEWJ1S8Ue_up8E","language":"zh_CN","headimgurl":"http://wx.qlogo.cn/mmopen/ribqo6CmxxhyfrokJWjVAedZzl590B4HAbribNVS3CQvplHp8KgmH1kIfqpM4Ek5uTr0lFW8yMDjfZrWLtvjjKLXu1H5icSfRBl/0","country":"中国","city":"海淀"} | 
这就获取到用户的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://open.weixin.qq.com/ 这个是授权登陆自己网站的和我的这个是有区别的。
个人微博 http://weibo.com/u/2205636212
个人博客 http://my.oschina.net/xshuai/blog  
微信/QQ 783021975 请先留言说明您!否则不加!
                    
                








                
            
        
浙公网安备 33010602011771号