justauth/JustAuth · error · AuthException

企业微信获取token失败

Error message

企业微信获取token失败

What it means

AuthWeChatEnterpriseThirdQrcodeRequest.getAccessToken wraps the whole provider-token flow in try/catch and rethrows AuthException("企业微信获取token失败", e) — Chinese message 'WeChat Work failed to get token' — with the original exception as cause. It fires when fetching the provider_access_token via POST /cgi-bin/service/get_provider_token with corpid + provider_secret, for third-party (服务商) QR login.

Source

Thrown at src/main/java/me/zhyd/oauth/request/AuthWeChatEnterpriseThirdQrcodeRequest.java:70

        } catch (Exception e) {
            Log.error("Failed to login with oauth authorization.", e);
            return this.responseError(e);
        }
    }

    @Override
    public AuthToken getAccessToken(AuthCallback authCallback) {
        try {
            String response = doGetAuthorizationCode(accessTokenUrl());
            JSONObject object = this.checkResponse(response);
            AuthToken authToken = AuthToken.builder()
                .accessToken(object.getString("provider_access_token"))
                .expireIn(object.getIntValue("expires_in"))
                .code(authCallback.getCode())
                .build();
            return authToken;
        } catch (Exception e) {
            throw new AuthException("企业微信获取token失败", e);
        }
    }

    @Override
    protected String doGetAuthorizationCode(String code) {
        JSONObject data = new JSONObject();
        data.put("corpid", config.getClientId());
        data.put("provider_secret", config.getClientSecret());
        return new HttpUtils(config.getHttpConfig()).post(accessTokenUrl(code), data.toJSONString()).getBody();
    }

    /**
     * 获取token的URL
     *
     * @return accessTokenUrl
     */
    protected String accessTokenUrl() {
        return UrlBuilder.fromBaseUrl(source.accessToken())

View on GitHub (pinned to 694bbf1b01)

Solutions

  1. Inspect the nested cause (`e.getCause()`) — the real reason (errcode/errmsg from WeChat or an IOException) is inside the wrapper.
  2. Verify clientId = provider's corpid and clientSecret = provider_secret from the 服务商 console, not the target enterprise's credentials.
  3. Add your server's egress IP to the provider's IP whitelist and verify connectivity to https://qyapi.weixin.qq.com.
  4. If cause shows errcode 40001/42001, the provider token logic is fine but credentials/whitelist are wrong — fix config, not code.

Example fix

// surfacing the real cause for diagnosis
try {
    AuthToken t = request.getAccessToken(callback);
} catch (AuthException e) {
    Throwable root = e.getCause();
    log.error("provider token failed: {}", root == null ? e.getMessage() : root.getMessage(), root);
}
Defensive patterns

Strategy: try-catch

Validate before calling

// pre-flight connectivity + credentials presence
if (StringUtils.isAnyEmpty(config.getClientId(), config.getClientSecret())) {
    throw new IllegalArgumentException("WeChat Work third-party: corpid/provider_secret required");
}
// optional: cheap reachability probe
// new HttpUtils(config.getHttpConfig()).get("https://qyapi.weixin.qq.com/cgi-bin/gettoken") ...

Try / catch

try {
    AuthToken t = request.getAccessToken(callback);
} catch (AuthException e) {
    Throwable cause = e.getCause();
    log.error("provider token failure, root: {}", cause == null ? "none" : cause.getMessage(), e);
    if (cause instanceof AuthException) {
        String m = String.valueOf(cause.getMessage());
        if (m.contains("40001") || m.contains("invalid")) refreshProviderTokenAndRetry();
    }
}

Prevention

When it happens

Trigger: Any exception during getProviderToken: HTTP failure (network/DNS/timeout), non-JSON response, or the nested checkResponse throwing because the WeChat server returned errcode != 0 (e.g. 40001 invalid credential, 40056 invalid corpid/provider_secret).

Common situations: provider_secret of the service provider mismatched or rotated; corpid (clientId) wrong — using the corp's id instead of the provider's; server IP not in the trusted/IP-whitelist config of WeChat Work; egress firewall blocking qyapi.weixin.qq.com.

Related errors


AI-assisted analysis of justauth/JustAuth@694bbf1b01 (2026-08-14). Data as JSON: /api/errors/5814ee847b82609c. Report an issue: GitHub.