天天看点

微信公众号中通过菜单事件获得当前用户信息

首先、配置好网页授权:

微信公众号中通过菜单事件获得当前用户信息
自定义菜单的格式:

{
                    "type": "view",
                    "name": "注册账号",
                    "url": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{appid}&redirect_uri=#{register-url}&response_type=code&scope=snsapi_base#wechat_redirect"
                },      

其中需要替换的2个参数:#{appid}和#{register-url},除去这两个参数外其它的部分为微信要求的格式!

当用户点击“注册账户”菜单后,系统会调用上边替换的register—url地址,并且会在这个地址添加一个code参数,通过这个code可以从微信平台拿到用户的openid,拿到openid后通过我们系统记录的绑定关系,就可以拿到userid了。

代码如下:

String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Const.appid + "&secret=" + Const.secret + "&code=" + code
                + "&grant_type=authorization_code";
        String content = NetworkUtils.doGetByHttps(url);