微信第三方平台公众号授权流程7-代公众号发起网页授权

简介

在公众号授权托管给第三方平台后,第三方平台可以根据本文档相关说明,代替授权公众号发起网页授权。关于OAuth2.0的详细介绍,可以参考OAuth2.0协议标准

作为第三方平台开发商,需要拥有自己的appid以及secret(在创建第三方平台并获得审核成功后可以获取),以及确保授权的公众号具备授权作用域的权限,以及用于回调的域名。

授权流程

微信目前支持Authorization code授权模式,主要流程分为两步:

  1. 获取code
  2. 通过code换取accesstoken

流程图:
微信第三方平台公众号授权流程7-代公众号发起网页授权

第一步:请求CODE

请求第三方后台,然后重定向微信请求code,代码如下:

/**
	 * 跳转微信
	 * @throws IOException 
	 */
	@RequestMapping("/redirectWx")
	@ResponseBody
	public void redirectWx(HttpServletRequest req, HttpServletResponse rsp) throws IOException{
		String actMpAppId = "xxx";//公众号appid(前面授权时已存到数据库)
		String param = "xxxx";//要传的参数
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
				+ "appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s"
				+"&component_appid=wxd1ba5af13e637b5c#wechat_redirect";
		url = String.format(url, actMpAppId,
				URLEncoder.encode(UrlUtil.getDomainWithContextHttps(req)+"wechat/mp/queryUser", "utf-8"),param);
		rsp.sendRedirect(url);
	}

第二步:通过code换取access_token(和openid)

代码如下:

/**
	 * 根据公众号auth_code查询人员信息
	 * @param authCode
	 * @param appId
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping(value = "/wechat/mp/queryUser")
	public void queryUser(@RequestParam("code")String authCode, @RequestParam("appid")String appId,
			@RequestParam("state")String state,HttpServletRequest req,HttpServletResponse rsp) throws IOException{
		String resultStr = WxThirdPartyAuthUtil.getUserInfo(authCode,appId);
		JSONObject json = JSONObject.parseObject(resultStr);
	    
	}

注意这里的@RequestMapping(value = “/wechat/mp/queryUser”)地址和第一步中重定向url中的redirect_uri保持一致。

WxThirdPartyAuthUtil相关代码:

/**
	 * 获取授权用户信息
	 * @param authCode
	 * @param appId
	 * @return
	 */
	public static String getUserInfo(String authCode, String appId) {
		JSONObject json = new JSONObject();
		json.put("component_appid", component_appid);
		json.put("authorization_code", authCode);
		String url = "https://api.weixin.qq.com/sns/oauth2/component/access_token?"
				+ "appid=%s&code=%s&grant_type=authorization_code&"
				+ "component_appid=%s&component_access_token=%s";
		url = String.format(url, appId,authCode,component_appid,getComponentAccessToken());
		/** 发送Https请求到微信 */
		String resultJson = "";
		try {
			resultJson = HttpClientUtil.send(url);
		} catch (HttpProcessException e) {
			LOGGER.error(e.toString());
		}
		return resultJson;
		
	}

注意如需通过网页授权access_token获取用户基本信息,则第一步中授权作用域为snsapi_userinfo,然后调用https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN接口即可(别问为啥没代码,没需求就没有代码。。。)。

结语

代公众号发起网页授权流程和公众号网页授权流程基本一致,唯一的不同的是前者发起网页授权的授权方appid是在第三方公众号授权时取得的(此收钱操作可以获取第三方平台所配置的所有微信公众号(或小程序)权限,这也是为啥采用第三平台的一个重要原因),后者直接根据公众号appid和**获取发起网页授权。