xujunwei 2 gadi atpakaļ
vecāks
revīzija
06abb317be

+ 43 - 0
framework-common/src/main/java/com/mrxu/framework/common/weixin/api/WxAuth2Api.java

@@ -13,8 +13,51 @@ public class WxAuth2Api {
 
     private static String authorizeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize";
 
+    private static String getComponentUserUrl = "https://api.weixin.qq.com/sns/oauth2/component/access_token?grant_type=authorization_code";
+
     private static String getUserUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code";
 
+    /**
+     * 开放平台认证
+     * @param componentAppid 服务方的 appid,在申请创建公众号服务成功后,可在公众号服务详情页找到
+     * @param appId 众号的 appid
+     * @param redirectUri 重定向地址,需要 urlencode,这里填写的是第三方平台的【公众号开发域名】,注意这个配置需要勾选公众号相关全权限集才可以看到
+     * @return
+     */
+    @SneakyThrows
+    public static String getComponentAuth2Url(String componentAppid,String appId,String redirectUri) {
+        StringBuilder redirectUrl = new StringBuilder();
+        redirectUrl.append(authorizeUrl);
+        redirectUrl.append("?appid=").append(appId);
+        redirectUrl.append("&component_appid=").append(componentAppid);
+        redirectUrl.append("&redirect_uri=").append(URLEncoder.encode(redirectUri, "UTF-8"));
+        redirectUrl.append("&response_type=code&scope=snsapi_base&state=wx#wechat_redirect");
+        return redirectUrl.toString();
+    }
+
+    /**
+     * 通过 code 换取 access_token
+     * @param componentAppid 服务开发方的 appid
+     * @param componentAccessToken 服务开发方的 access_token
+     * @param appId 公众号的 appid
+     * @param code 填写第一步获取的 code 参数
+     * @return
+     */
+    public static String getComponentOpenId(String componentAppid,String componentAccessToken,String appId,String code) {
+        StringBuilder sb = new StringBuilder(getComponentUserUrl);
+        sb.append("&appid="+appId);
+        sb.append("&component_appid="+componentAppid);
+        sb.append("&component_access_token="+componentAccessToken);
+        sb.append("&code="+code);
+        String queryUrl = sb.toString();
+        log.info("auth2认证获取微信用户信息url:{}",queryUrl);
+        String rs = HttpUtil.get(queryUrl);
+        log.info("auth2认证返回结果:{}",rs);
+        JSONObject rsJson = JSONObject.parseObject(rs);
+        MrxuAssert.isEmpty(rsJson.getString("errmsg"),rsJson.getString("errmsg"));
+        return rsJson.getString("openid");
+    }
+
     @SneakyThrows
     public static String getAuth2Url(String appId,String redirectUri) {
         StringBuilder redirectUrl = new StringBuilder();