var center = { init: function(){ ..... }, enterWxAuthor: function(){ var wxUserInfo = localStorage.getItem("wxUserInfo"); if (!wxUserInfo) { var code = common.getUrlParameter('code'); if (code) { common.getWxUserInfo(); center.init(); }else{ //沒有微信用戶信息,沒有受權-->> 須要受權,跳轉受權頁面 window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+ WX_APPID +'&redirect_uri='+ window.location.href +'&response_type=code&scope=snsapi_userinfo#wechat_redirect'; } }else{ center.init(); } } } $(document).ready(function() { center.enterWxAuthor(); }
/** * 受權後獲取用戶的基本信息 */ getWxUserInfo:function(par){ var code = common.getUrlParameter("code"); if (par) code = par; $.ajax({ async: false, data: {code:code}, type : "GET", url : WX_ROOT + "wechat/authorization", success : function(json) { if (json){ try { //保證寫入的wxUserInfo是正確的 var data = JSON.parse(json); if (data.openid) { localStorage.setItem('wxUserInfo',json);//寫緩存--微信用戶信息 } } catch (e) { // TODO: handle exception } } } }); },
/** * 微信受權 * @param code 使用一次後失效 * * @return 用戶基本信息 * @throws IOException */ @RequestMapping(value = "/authorization", method = RequestMethod.GET) public void authorizationWeixin( @RequestParam String code, HttpServletRequest request, HttpServletResponse response) throws IOException{ request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); LOGGER.info("RestFul of authorization parameters code:{}",code); try { String rs = wechatService.getOauthAccessToken(code); out.write(rs); LOGGER.info("RestFul of authorization is successful.",rs); } catch (Exception e) { LOGGER.error("RestFul of authorization is error.",e); }finally{ out.close(); } }
/** * 根據code 獲取受權的token 僅限受權時使用,與全局的access_token不一樣 * @param code * @return * @throws IOException * @throws ClientProtocolException */ public String getOauthAccessToken(String code) throws ClientProtocolException, IOException{ String data = redisService.get("WEIXIN_SQ_ACCESS_TOKEN"); String rs_access_token = null; String rs_openid = null; String url = WX_OAUTH_ACCESS_TOKEN_URL + "?appid="+WX_APPID+"&secret="+WX_APPSECRET+"&code="+code+"&grant_type=authorization_code"; if (StringUtils.isEmpty(data)) { synchronized (this) { //已過時,須要刷新 String hs = apiService.doGet(url); JSONObject json = JSONObject.parseObject(hs); String refresh_token = json.getString("refresh_token"); String refresh_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+WX_APPID+"&grant_type=refresh_token&refresh_token="+refresh_token; String r_hs = apiService.doGet(refresh_url); JSONObject r_json = JSONObject.parseObject(r_hs); String r_access_token = r_json.getString("access_token"); String r_expires_in = r_json.getString("expires_in"); rs_openid = r_json.getString("openid"); rs_access_token = r_access_token; redisService.set("WEIXIN_SQ_ACCESS_TOKEN", r_access_token, Integer.parseInt(r_expires_in) - 3600); LOGGER.info("Set sq access_token to redis is successful.parameters time:{},realtime",Integer.parseInt(r_expires_in), Integer.parseInt(r_expires_in) - 3600); } }else{ //尚未過時 String hs = apiService.doGet(url); JSONObject json = JSONObject.parseObject(hs); rs_access_token = json.getString("access_token"); rs_openid = json.getString("openid"); LOGGER.info("Get sq access_token from redis is successful.rs_access_token:{},rs_openid:{}",rs_access_token,rs_openid); } return getOauthUserInfo(rs_access_token,rs_openid); } /** * 根據受權token獲取用戶信息 * @param access_token * @param openid * @return */ public String getOauthUserInfo(String access_token,String openid){ String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+ access_token +"&openid="+ openid +"&lang=zh_CN"; try { String hs = apiService.doGet(url); //保存用戶信息 saveWeixinUser(hs); return hs; } catch (IOException e) { LOGGER.error("RestFul of authorization is error.",e); } return null; }
參考連接:前端
微信公衆平臺官方文檔:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842&token=&lang=zh_CNajax
在線接口調試工具:http://mp.weixin.qq.com/debugredis