微信授权第三方平台

小程序或者公众号授权给第三方平台的技术实现流程

简介 | 微信开放文档微信开发者平台文档icon-default.png?t=N7T8https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/Official_Accounts/official_account_website_authorization.html

 @PostMapping({ "/weixin/weixinbind/tobind", "/weixin/weixinbind/tobind.json",
        "/moduleenterprisepartner/partner/wx/temp/login", "/moduleenterprisepartner/partner/wx/temp/login.json" })
    public ResultModel toBind(@RequestBody WeixinBindParam param) {
        LOGGER.info("参数{}", JSON.toJSONString(param));
        String code = param.getCode();
        String referer = RequestContext.getCurrentContext().getReqHead().getReferer();
        LOGGER.info("从ReqHead中获取:{}", referer);
        PlatformExtDO platformExt = platformExtManager.getPlatformExtByDomain(referer);
        if (Objects.isNull(platformExt) || StringUtils.isBlank(platformExt.getClientKey())) {
            LOGGER.info("域名配置错误{},{}", referer, JSON.toJSONString(platformExt));
            return ResultModel.error(PartnerCode.ERROR_TOKEN.code(), i18nService.getMessage("param.check.fail"));
        }
        Integer sourceId = getSourceId();
        ExtOauthUserInfo extOauthUserInfo = partnerProcess.getWeiXinUserInfo(code, platformExt.getClientKey(),
            platformExt.getSecretKey(),referer);
        LOGGER.info("外部用户信息{},{}", referer, JSON.toJSONString(extOauthUserInfo));
        if (Objects.isNull(extOauthUserInfo) || StringUtils.isBlank(extOauthUserInfo.getUnionid())) {
            return ResultModel.error(PartnerCode.BIND_ERROR_EXT_INVALID.code(),
                i18nService.getMessage("bind.fail.infomation.error"));
        }
        extOauthUserInfo.setNickname(EmojiUtils.removeEmoji(extOauthUserInfo.getNickname()));
        if (StringUtils.isNotBlank(extOauthUserInfo.getHeadimgurl())) {
            String kanoId = kanoFileManager.uploadHeadImg(extOauthUserInfo.getHeadimgurl());
            extOauthUserInfo.setHeadImgKano(kanoId);
        }
        LOGGER.info(JSON.toJSONString(extOauthUserInfo));
        OAuthTokenDTO oAuthTokenDTO = userManager.extTempLogin(getAppId(), platformExt.getExtAppId(),
            platformExt.getClientKey(), extOauthUserInfo.getUnionid(), extOauthUserInfo.getOpenid(),
            extOauthUserInfo.getNickname(), extOauthUserInfo.getHeadImgKano(), extOauthUserInfo.getSex(), sourceId);
        LOGGER.info("临时登录结果{}", JSON.toJSONString(oAuthTokenDTO));
        if (Objects.isNull(oAuthTokenDTO)) {
            return ResultModel.error(PartnerCode.ERROR_TOKEN.code(),
                i18nService.getMessage("loginStatus.enum.not_user"));
        }

        UserDO userDO = userManager.getUserInfoByToken(oAuthTokenDTO.getAccessToken(), sourceId);
        LOGGER.info("查询用户结果{}", JSON.toJSONString(userDO));
        if (Objects.isNull(userDO)) {
            return ResultModel.error(PartnerCode.ERROR_TOKEN.code(),
                i18nService.getMessage("loginStatus.enum.not_user"));
        }
        commonWeiXinBindProcess.appDeviceOnline(userDO, platformExt.getClientKey(), extOauthUserInfo.getOpenid(),
            sourceId);
        TobindItem item = new TobindItem();
        item.setUserToken(oAuthTokenDTO.getAccessToken());
        item.setTempFlag(userDO.getIsTemp());
        item.setOpenId(extOauthUserInfo.getOpenid());
        item.setUnionId(extOauthUserInfo.getUnionid());
        TobindItem data = new TobindItem();
        data.setUserToken(oAuthTokenDTO.getAccessToken());
        data.setTempFlag(userDO.getIsTemp());
        data.setOpenId(extOauthUserInfo.getOpenid());
        data.setUnionId(extOauthUserInfo.getUnionid());
        TobindModel result = new TobindModel();
        result.setItem(item);
        result.setData(data);
        LOGGER.info(JSON.toJSONString(result));
        return result;
    }
    public ExtOauthUserInfo getWeiXinUserInfo(String code, String weixinAppId, String weixinAppSecret,String referer) {
        ExtOauthUserInfo accessTokenResp = new ExtOauthUserInfo();

        String title = "获取访问令牌";
        String unionMsg = "获取用户唯一标识";
        String componentAppid = "wxc8261f8532597824";
//        String componentAppid = "wx61ee3441556b8421";
//        String SliAppid = "wx337d738cfc96e0a2";

        if (StringUtils.isBlank(weixinAppId) || StringUtils.isBlank(weixinAppSecret) || StringUtils.isBlank(code)) {
            LOGGER.error("getUserInfo fail. param check null. weixinAppId:{}, weixinAppSecret:{}, code:{}", weixinAppId,
                    weixinAppSecret, code);
            return accessTokenResp;
        }

        try {
            // 获取access_token
            HttpClient client = httpClientManager.getHttpClient();
            LocalResponseDO<Object> lrd = new LocalResponseDO<>();
            List<NameValuePair> getAccessParam = buildParamsForGetAccessToken(code, weixinAppId, weixinAppSecret);
            /**
             * 所有的非空系统参数和请求参数(签名sign和图片参数除外)放入Map中
             */
            Map<String, Object> map = new HashMap<>();
            map.put("method", method);
            map.put("appkey", appkey);
            String timestamp = DateUtils.getDateFormat(new Date(), DateUtils.FORMATYYYYMMDDHHMMSS);
            map.put("timestamp", timestamp);
//            String allAppid = componentAppid+ "," +SliAppid;
            // 测试可通
//            String allAppid33 = "wx7137dfbb632d086d,wx61ee3441556b8421";
            map.put("appId", componentAppid);
            map.put("type", "wx");
            String sign = SignUtil.getInstance().getSign(map, appsecret);
            // 请求第三方开放平台
            HttpPost httpPost = new HttpPost(host);  // host 请求地址

            // 系统参数(放入请求头中)
            httpPost.addHeader("appkey", appkey);
            httpPost.addHeader("method", method);
            httpPost.addHeader("timestamp", timestamp);
            httpPost.addHeader("sign", sign);   // 客户端签名

            //业务参数(请求参数)
            List<NameValuePair> urlParameters = new ArrayList<>();
            urlParameters.add(new BasicNameValuePair("type", "wx"));
            urlParameters.add(new BasicNameValuePair("appId", componentAppid));
            HttpEntity stringEntity = new UrlEncodedFormEntity(urlParameters, CHARSET);  // 字符编码 UTF-8
            httpPost.setEntity(stringEntity);

            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            String tokenResult = EntityUtils.toString(httpResponse.getEntity(), CHARSET);

            LOGGER.info("开放平台极验证返回参数{}", tokenResult);

            JSONObject jsonObject = JSONObject.parseObject(tokenResult);
            String dataResult = jsonObject.getString("dataResult");

            // 微信授权公众号
            List<NameValuePair> getAccessNewParam = buildParamsForGetAccessNewToken(code, weixinAppId, dataResult);

            String resp =null;
            if (referer.equals("https://m-sdsldsyy.95169000.com")){
                LOGGER.info("进入第二步");
                resp = HttpClientUtil
                        .httpSendByGet(lrd, TencentConstants.URL_COMPONENT_ACCESS_TOKEN, getAccessNewParam, title, client);
                LOGGER.info("resp:{}", resp);
            }else {

                resp = HttpClientUtil
                        .httpSendByGet(lrd, TencentConstants.URL_ACCESS_TOKEN, getAccessParam, title, client);
            }
            accessTokenResp = JSON.parseObject(this.parseResp(resp), ExtOauthUserInfo.class);
            LOGGER.info("accessTokenResp-----》打印",JSON.toJSONString(accessTokenResp));


            if (!lrd.isSuccess() || Objects.isNull(accessTokenResp) || StringUtils
                    .isBlank(accessTokenResp.getAccess_token()) || StringUtils.isBlank(accessTokenResp.getOpenid())) {
                LOGGER.error("getUserInfo fail. get accessToken fail. param:{}, result:{}",
                        JSON.toJSONString(getAccessParam), JSON.toJSONString(accessTokenResp));
                return accessTokenResp;
            }

            //静默授权,无法获取用户信息,直接返回
            if ("snsapi_base".equals(accessTokenResp.getScope())) {
                LOGGER.info("静默授权. param:{}, result:{}",
                        JSON.toJSONString(getAccessParam), JSON.toJSONString(accessTokenResp));
                accessTokenResp.setUnionid(accessTokenResp.getOpenid());
                return accessTokenResp;
            }

            // 获取微信用户信息
            HttpClient client1 = httpClientManager.getHttpClient();
            List<NameValuePair> getUserInfoParam = buildParamsForUnionId(accessTokenResp.getAccess_token(),
                    accessTokenResp.getOpenid());
            String unionResp = HttpClientUtil
                    .httpSendByGet(lrd, TencentConstants.URL_USER_INFO, getUserInfoParam, unionMsg, client1);
            accessTokenResp = JSON.parseObject(unionResp, ExtOauthUserInfo.class);
            //暂时添加查询用户昵称为null的问题 查出后删除
            LOGGER.error("获取微信用户信息. param:{}, resp:{},unionResp:{}", JSON.toJSONString(getUserInfoParam), resp,
                    unionResp);
            if (!lrd.isSuccess() || Objects.isNull(accessTokenResp) || StringUtils
                    .isBlank(accessTokenResp.getUnionid())) {
                LOGGER.error("getUserInfo fail. get userInfo fail. param:{}, result:{}",
                        JSON.toJSONString(getUserInfoParam), resp);
                return accessTokenResp;
            }
        } catch (Exception e) {
            LOGGER.error("getUserInfo exception. appId:{}, error:{}", weixinAppId, e.getMessage());
            return accessTokenResp;
        }

        return accessTokenResp;
    }
 private List<NameValuePair> buildParamsForGetAccessNewToken(String code, String appId, String dataResult) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("grant_type", TencentConstants.GRANT_TYPE_CODE));
        params.add(new BasicNameValuePair("appid", appId));
        params.add(new BasicNameValuePair("component_appid", "wxc8261f8532597824"));
        params.add(new BasicNameValuePair("code", code));
        params.add(new BasicNameValuePair("component_access_token", dataResult));
        return params;
    }

批注一个优雅的方法:就是当你获取的是String 类型的 json 的时候,获取json  想取json 里边的某个key 的时候,怎么个取法:

有两种取法: 笨办法  ,字符串截取,但是会有隐患 

// //从开始截取到指定字符, (该字符出现的第一次)
// String midChar = ",";
// String substring1 = tokenResult.substring(0,tokenResult.indexOf(midChar)+ midChar.length());
// //截取:之后字符串
// String str1 = substring1.substring(0, substring1.indexOf(":"));
// String token = substring1.substring(str1.length()+1, substring1.length());
// //截取,之前字符串
// String allTocken = token.substring(0, token.indexOf(","));
// System.out.println("截取,之后字符串:"+allTocken);

方法二:

JSONObject jsonObject = JSONObject.parseObject(tokenResult);
            String dataResult = jsonObject.getString("dataResult");

  这种方法比较优雅

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值