天天看點

微信第三方平台公衆号授權流程5-授權資訊

該API用于使用授權碼換取授權公衆号或小程式的授權資訊,并換取authorizer_access_token和authorizer_refresh_token。 授權碼的擷取,需要在使用者在第三方平台授權頁中完成授權流程後,在回調URI中通過URL參數提供給第三方平台方。請注意,由于現在公衆号或小程式可以自定義選擇部分權限授權給第三方平台,是以第三方平台開發者需要通過該接口來擷取公衆号或小程式具體授權了哪些權限,而不是簡單地認為自己聲明的權限就是公衆号或小程式授權的權限。

web層代碼:

/**
	* 根據第三方平台auth_code查詢授權資訊
	* @param authCode 授權成功時獲得的授權碼
	* @param expiresIn 存活時間
	* @return
	 * @throws IOException 
	*/
	@ResponseBody
	@RequestMapping(value = "/wechat/$APPID$/callback")
	public void queryAuth(@RequestParam("auth_code")String authCode, @RequestParam("expires_in")String expiresIn,
			HttpServletRequest request, HttpServletResponse response) throws IOException{
		LOGGER.error("auth_code={},expires_in={}",authCode,expiresIn);
		JSONObject jsonObject = WxThirdPartyAuthUtil.getAuthInfo(authCode,expiresIn);
		//将授權資訊儲存到資料庫
		authorizerFacade.save(AuthorizerInfoDTO.copyFromJson(jsonObject));
		String url = UrlUtil.getDomainWithContext(request)+"hd/mp/index";
		response.sendRedirect(url);
	}
           

這裡的@RequestMapping(value = “/wechat/ A P P I D APPID APPID/callback”)與上一篇提及的消息與事件接收URL保持一緻,請求源于微信公衆号授權成功後的回調。

WxThirdPartyAuthUtil類相關代碼:

/**
	 * 擷取授權公衆号資訊
	 * @param authCode
	 * @param expiresIn
	 */
	public static JSONObject getAuthInfo(String authCode, String expiresIn) {
		JSONObject json = new JSONObject();
		json.put("component_appid", component_appid);
		json.put("authorization_code", authCode);
		LOGGER.info("ThirdPartyServiceImpl:getComponentAccessToken:json={}", json);
		/** 發送Https請求到微信 */
		JSONObject resultJson = new JSONObject();
		try {
			resultJson = HttpClientUtil.postJson(
					"https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token="
					+getComponentAccessToken(), json);
		} catch (Exception e) {
			LOGGER.error(e.toString());
		}
		return resultJson;
		
	}
           

繼續閱讀