Java--對接微信第五篇之底部選單按鈕url設定(通過按鈕回撥獲取openid)
阿新 • • 發佈:2018-11-09
在上一篇的基礎上,有一個地方是需要去微信公眾平臺設定的(如果你這個url需要獲取使用者openid的話!如果不需要獲取可以無視)
登入微信公眾平臺-->公眾號設定-->選擇功能設定-->設定網頁授權域名(為微信認為安全的地址,不用精確到方法,但是你需要將一個文字金鑰放入對應地址下,微信會在這個地址校驗金鑰。金鑰微信會給你下載)
我放在這裡(這是我op專案下的resources/static/open)對應op/open:
這些做完之後,點選儲存,微信會給你返回結果。我這邊是成功了!如果失敗:會有錯誤資訊,一般是找不到那個金鑰,看看你的位置是否放正確了!
這些事情做完之後,我們回到上一篇:
組裝選單資料方法getMenu()那:
String redirect_uri = "http://www.你的伺服器回撥地址.com/op/open/openArticle";
這個地址:BaseAPI.OPEN_URI+"/connect/oauth2/authorize?appid="+ WeiXinUtil.APPID+"&redirect_uri="+redirect_uri+"?category=1&response_type=code&scope=snsapi_base&state=1#wechat_redirect" 它的完整地址是: https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ WeiXinUtil.APPID+"&redirect_uri="+redirect_uri+"?category=1&response_type=code&scope=snsapi_base&state=1#wechat_redirect 其中appid不用我說了吧。別的東西都不用管,你先看redirect_uri 這個地址能否呼叫你的專案介面 例如我的專案介面有這個方法: /** * 公共文章介面 * @param map * @return */ @RequestMapping(value = "/open/openArticle") public String openArticle(ModelMap map,HttpServletRequest request) throws Exception{ String code = request.getParameter("code");//頁面授權獲取的code用以交換 openid String openId = OAuthGetOpenid(code);//OAuth獲取使用者openid區分是哪個使用者請求登入W3 map.put("title", "公共文章介面"); map.put("path", path); map.put("openId",openId); map.put("category",category); return "openArticle"; } /** * 通過頁面OAuth授權,用code獲取openid * * @param code * @return */ public String OAuthGetOpenid(String code) throws Exception{ JSONObject json = new JSONObject(); String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WeiXinUtil.APPID+"&secret="+WeiXinUtil.APPSECRET+"&code=" + code + "&grant_type=authorization_code"; String outputStr = ""; json = WeiXinUtil.doPostStr(requestUrl, outputStr); String openid = json.getString("openid"); logger.info(json+"---------json--------openid-----------"+openid); return openid; }
到這就完成了。點選選單按鈕之後,我這邊可以成功獲取到使用者的openid,並且成功跳轉到指定url頁面