TikTok API

Hi! I’ve got a problem using TikTok API. I get an error about access token which says that is invalid. Here is the method used for getting the token:

private static String getAccessTokenWithClientCredentials() throws Exception {
        HttpClient client = HttpClient.newHttpClient();

        // The body for the Client Credentials grant is simpler.
        // You only need to identify your client and specify the grant type.
        String form = "client_key=" + URLEncoder.encode(CLIENT_KEY, StandardCharsets.UTF_8)
                + "&client_secret=" + URLEncoder.encode(CLIENT_SECRET, StandardCharsets.UTF_8)
                + "&grant_type=client_credentials";

        HttpRequest req = HttpRequest.newBuilder()
                .uri(URI.create(TOKEN_URL))
                .timeout(Duration.ofSeconds(20))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .POST(HttpRequest.BodyPublishers.ofString(form))
                .build();

        System.out.println("Requesting access token from TikTok API...");
        HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());

        if (resp.statusCode() != 200) {
            throw new RuntimeException("Token exchange failed: " + resp.statusCode() + " -> " + resp.body());
        }

        JsonNode root = JSON.readTree(resp.body());
        // Note: The response for this grant type also includes other fields like
        // 'scope', 'expires_in', and 'token_type', which you might want to parse.
        return root.get("access_token").asText();
    }

Then I used the token when calling the API but get the error:

> {"error":{"code":"access_token_invalid","message":"The access token is invalid or not found in the request.","log_id":"202509101626444C67AFEEA729D40D3834"},"data":{}}

Did you have this problem?

Similar Posts