天天看點

微信公衆号中通過菜單事件獲得目前使用者資訊

首先、配置好網頁授權:

微信公衆号中通過菜單事件獲得目前使用者資訊
自定義菜單的格式:

{
                    "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);