### Project Setup and Configuration (Bash) Source: https://github.com/gc535/light-tiktok-oauth2-backend/blob/master/README.md Details the initial steps to set up the project, including cloning the repository, installing dependencies using npm, and configuring environment variables by copying an example file. ```bash git clone https://github.com/yourusername/tiktok-oauth2-server.git cd tiktok-oauth2-server npm install cp env.example .env ``` -------------------------------- ### Server Setup: Load Environment Variables and Start Express (JavaScript) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt This JavaScript code snippet demonstrates how to set up an Express server, load environment variables using `dotenv`, and validate critical configuration settings. It includes a fallback for generating an encryption key if none is provided, with a warning to add it to the .env file. ```javascript // Complete server setup example require('dotenv').config(); const express = require('express'); // Validate required environment variables const requiredEnvVars = [ 'TIKTOK_CLIENT_KEY', 'TIKTOK_CLIENT_SECRET', 'TIKTOK_REDIRECT_URI' ]; for (const envVar of requiredEnvVars) { if (!process.env[envVar]) { console.error(`Error: ${envVar} is not set in .env file`); process.exit(1); } } // Optional: Generate encryption key if not provided if (!process.env.ENCRYPTION_KEY) { const crypto = require('crypto'); const key = crypto.randomBytes(32).toString('hex'); console.warn('Warning: ENCRYPTION_KEY not set, using generated key:', key); console.warn('Add this to your .env file: ENCRYPTION_KEY=' + key); process.env.ENCRYPTION_KEY = key; } const app = express(); const PORT = process.env.PORT || 7777; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); }); ``` -------------------------------- ### Start TikTok OAuth2 Server Source: https://github.com/gc535/light-tiktok-oauth2-backend/blob/master/README.md Commands to start the TikTok OAuth2 server in development or production mode using npm. Visit the specified local URL to initiate the OAuth2 flow. ```bash # Development mode npm run dev # Production mode npm start ``` -------------------------------- ### TikTok API Usage Examples (JavaScript) Source: https://github.com/gc535/light-tiktok-oauth2-backend/blob/master/README.md Provides JavaScript code snippets for interacting with the local TikTok OAuth2 server to fetch creator and user information, upload videos, and check video upload status using the Fetch API. ```javascript // Get creator info const response = await fetch('http://localhost:7777/creator-info'); const creatorData = await response.json(); console.log(creatorData); // Get user info with specific fields const userInfoResponse = await fetch('http://localhost:7777/user/info?fields=open_id,union_id,avatar_url,display_name,bio_description'); const userData = await userInfoResponse.json(); console.log(userData); // Upload a video const uploadResponse = await fetch('http://localhost:7777/video/upload', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ file_path: '/path/to/video.mp4', }) }); const uploadData = await uploadResponse.json(); console.log(uploadData); // Check video upload status const statusResponse = await fetch('http://localhost:7777/video/status?publish_id=abc123def456'); const statusData = await statusResponse.json(); console.log(statusData); ``` -------------------------------- ### Environment Configuration: .env file Setup (Bash) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt This is a sample .env file configuration for the TikTok OAuth2 backend. It defines essential environment variables required for TikTok API authentication and server operation, including client keys, redirect URI, encryption key, and port. ```bash # .env configuration file TIKTOK_CLIENT_KEY=your_tiktok_client_key_here TIKTOK_CLIENT_SECRET=your_tiktok_client_secret_here TIKTOK_REDIRECT_URI=http://localhost:7777/auth/callback ENCRYPTION_KEY=your-super-secret-encryption-key-min-32-chars PORT=7777 ``` -------------------------------- ### Retrieve TikTok Creator Information Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Retrieves TikTok creator profile information, including creator settings and publishing capabilities, using the authenticated user's access token. This is typically invoked via a GET request. ```bash # Get creator information curl -X GET http://localhost:7777/creator-info # Response example: # { # "data": { # "creator_avatar_url": "https://...", # "creator_username": "username", # "creator_nickname": "Display Name", # "privacy_level_options": ["PUBLIC_TO_EVERYONE", "MUTUAL_FOLLOW_FRIENDS", "SELF_ONLY"], # "comment_disabled": false, # "duet_disabled": false, # "stitch_disabled": false, # "max_video_post_duration_sec": 600 # }, # "error": { # "code": "ok", # "message": "", # "log_id": "..." # } # } ``` -------------------------------- ### Get Creator Information Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Retrieves TikTok creator profile information, including creator settings and publishing capabilities, using the authenticated user's access token. ```APIDOC ## GET /creator-info ### Description Retrieves TikTok creator profile information including creator settings and publishing capabilities using the authenticated user's access token. ### Method GET ### Endpoint /creator-info ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X GET http://localhost:7777/creator-info ``` ### Response #### Success Response (200 OK) - **data** (object) - Contains creator information. - **creator_avatar_url** (string) - URL of the creator's avatar. - **creator_username** (string) - The creator's username. - **creator_nickname** (string) - The creator's display name. - **privacy_level_options** (array) - Available privacy level options. - **comment_disabled** (boolean) - Whether comments are disabled. - **duet_disabled** (boolean) - Whether duets are disabled. - **stitch_disabled** (boolean) - Whether stitches are disabled. - **max_video_post_duration_sec** (integer) - Maximum video post duration in seconds. - **error** (object) - Error details if any. - **code** (string) - Error code. - **message** (string) - Error message. - **log_id** (string) - Log ID for the error. #### Response Example ```json { "data": { "creator_avatar_url": "https://...", "creator_username": "username", "creator_nickname": "Display Name", "privacy_level_options": ["PUBLIC_TO_EVERYONE", "MUTUAL_FOLLOW_FRIENDS", "SELF_ONLY"], "comment_disabled": false, "duet_disabled": false, "stitch_disabled": false, "max_video_post_duration_sec": 600 }, "error": { "code": "ok", "message": "", "log_id": "..." } } ``` ``` -------------------------------- ### Get User Information Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Fetches specific user information fields as requested by the client, allowing flexible queries for profile data including display name, avatar, bio, and follower statistics. ```APIDOC ## GET /user/info ### Description Fetches specific user information fields as requested by the client, allowing flexible queries for profile data including display name, avatar, bio, and follower statistics. ### Method GET ### Endpoint /user/info ### Parameters #### Query Parameters * **fields** (string) - Required - Comma-separated list of user fields to retrieve (e.g., `open_id,union_id,avatar_url,display_name,bio_description,follower_count,following_count,likes_count,video_count`). ### Request Example ```bash curl -X GET "http://localhost:7777/user/info?fields=open_id,union_id,avatar_url,display_name,bio_description,follower_count,following_count,likes_count,video_count" ``` ### Response #### Success Response (200 OK) - **data** (object) - Contains user information. - **user** (object) - User profile details. - **open_id** (string) - The user's open ID. - **union_id** (string) - The user's union ID. - **avatar_url** (string) - URL of the user's avatar. - **display_name** (string) - The user's display name. - **bio_description** (string) - The user's bio. - **follower_count** (integer) - Number of followers. - **following_count** (integer) - Number of users the user is following. - **likes_count** (integer) - Total likes received on videos. - **video_count** (integer) - Total number of videos posted. - **error** (object) - Error details if any. - **code** (string) - Error code. - **message** (string) - Error message. - **log_id** (string) - Log ID for the error. #### Response Example ```json { "data": { "user": { "open_id": "OPEN_ID_VALUE", "union_id": "UNION_ID_VALUE", "avatar_url": "https://p16-sign-va.tiktokcdn.com/", "display_name": "John Doe", "bio_description": "Content creator", "follower_count": 12500, "following_count": 450, "likes_count": 50000, "video_count": 89 } }, "error": { "code": "ok", "message": "", "log_id": "..." } } ``` ``` -------------------------------- ### Check TikTok Video Upload Status (Bash) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Checks the processing status of a previously uploaded video using its unique publish ID. This GET request allows developers to monitor the progress and state of video uploads. ```bash # Check video upload status curl -X GET "http://localhost:7777/video/status?publish_id=v_pub_12345abcdef" ``` -------------------------------- ### Fetch TikTok User Information Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Fetches specific user information fields as requested by the client, allowing flexible queries for profile data including display name, avatar, bio, and follower statistics. This is invoked via a GET request with query parameters for desired fields. ```bash # Get specific user fields curl -X GET "http://localhost:7777/user/info?fields=open_id,union_id,avatar_url,display_name,bio_description,follower_count,following_count,likes_count,video_count" # Response example: # { # "data": { # "user": { # "open_id": "OPEN_ID_VALUE", # "union_id": "UNION_ID_VALUE", # "avatar_url": "https://p16-sign-va.tiktokcdn.com/…", # "display_name": "John Doe", # "bio_description": "Content creator", # "follower_count": 12500, # "following_count": 450, # "likes_count": 50000, # "video_count": 89 # } # }, # "error": { # "code": "ok", # "message": "", # "log_id": "..." # } # } ``` -------------------------------- ### Check Server Health (Bash) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt This bash command uses curl to perform a health check on the server. It sends a GET request to the /health endpoint and expects a JSON response indicating the server's status, timestamp, and uptime. This is useful for monitoring and integration verification. ```bash # Check server health curl http://localhost:7777/health # Response: # { # "status": "healthy", # "timestamp": "2025-10-31T19:27:45.123Z", # "uptime": 3600.456 # } ``` -------------------------------- ### Get TikTok User Info with Error Handling (JavaScript) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Fetches user information from TikTok's API using the fetch API. Includes comprehensive error handling for network issues, HTTP status codes, and TikTok API specific errors. Returns user data or throws an error. ```javascript async function getUserInfo() { try { const fields = 'open_id,union_id,avatar_url,display_name,bio_description'; const response = await fetch(`http://localhost:7777/user/info?fields=${fields}`); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); if (data.error && data.error.code !== 'ok') { throw new Error(`TikTok API Error: ${data.error.message}`); } console.log('User Info:', data.data.user); return data.data.user; } catch (error) { console.error('Failed to get user info:', error.message); throw error; } } getUserInfo(); ``` -------------------------------- ### TikTok Video Upload Workflow (Bash) Source: https://github.com/gc535/light-tiktok-oauth2-backend/blob/master/README.md Demonstrates the command-line interface steps for authenticating with TikTok, retrieving creator information, uploading a video, and checking its upload status using cURL. ```bash # One-time OAuth2 authentication curl http://localhost:7777/auth/login # Then you can get creator info with: curl -X GET http://localhost:7777/creator-info # Or upload a video with: curl -X POST http://localhost:7777/video/upload \ -H "Content-Type: application/json" \ -d '{ "file_path": "/home/user/videos/my_video.mp4", }' # and check upload status at (replace with actual publish_id): curl "http://localhost:7777/video/status?publish_id=abc123def456" ``` -------------------------------- ### Server Management Source: https://github.com/gc535/light-tiktok-oauth2-backend/blob/master/README.md Endpoints for managing the server's operational status. ```APIDOC ## POST /shutdown ### Description Gracefully shuts down the server. ### Method POST ### Endpoint `/shutdown` ## GET /health ### Description Checks the health status of the server. ### Method GET ### Endpoint `/health` ### Response #### Success Response (200) - **status** (string) - Indicates the server's health (e.g., "ok"). ### Response Example ```json { "status": "ok" } ``` ``` -------------------------------- ### Video Upload Source: https://github.com/gc535/light-tiktok-oauth2-backend/blob/master/README.md Endpoints for uploading videos to TikTok, including direct posting and inbox preparation. ```APIDOC ## POST /video/direct-post ### Description Uploads a video directly to TikTok. Note: This method only supports private posting. ### Method POST ### Endpoint `/video/direct-post` ### Request Body - **file_path** (string) - Required - The local path to the video file to be uploaded. ### Request Example ```json { "file_path": "/home/user/videos/my_private_video.mp4" } ``` ### Response #### Success Response (200) - **(object)** - Details of the direct video upload operation. ## POST /video/upload ### Description Uploads a video to TikTok's inbox, allowing the user to edit before publishing. ### Method POST ### Endpoint `/video/upload` ### Request Body - **file_path** (string) - Required - The local path to the video file to be uploaded. ### Request Example ```json { "file_path": "/home/user/videos/my_video.mp4" } ``` ### Response #### Success Response (200) - **publish_id** (string) - The ID used to track the video upload status. ### Response Example ```json { "publish_id": "abc123def456" } ``` ## GET /video/status ### Description Checks the upload status of a video using its publish ID. ### Method GET ### Endpoint `/video/status` ### Query Parameters - **publish_id** (string) - Required - The ID obtained from the `/video/upload` endpoint. ### Response #### Success Response (200) - **(object)** - The current status of the video upload. ### Response Example ```json { "status": "processing", "progress": 50 } ``` ``` -------------------------------- ### User and Creator Information Source: https://github.com/gc535/light-tiktok-oauth2-backend/blob/master/README.md Endpoints to retrieve information about the authenticated TikTok creator and user. ```APIDOC ## GET /creator-info ### Description Retrieves information about the authenticated TikTok creator. ### Method GET ### Endpoint `/creator-info` ### Response #### Success Response (200) - **(object)** - Creator information details. ### Response Example ```json { "data": { "creator_id": "1234567890", "display_name": "ExampleCreator", "avatar_url": "https://example.com/avatar.jpg" } } ``` ## GET /user/info ### Description Retrieves user information with specified fields. ### Method GET ### Endpoint `/user/info` ### Query Parameters - **fields** (string) - Required - Comma-separated list of fields to retrieve (e.g., `open_id,union_id,avatar_url,display_name,bio_description`). ### Response #### Success Response (200) - **(object)** - User information based on requested fields. ### Response Example ```json { "data": { "open_id": "odtx...", "union_id": "custom_union_id", "avatar_url": "https://example.com/avatar.jpg", "display_name": "ExampleUser", "bio_description": "This is a sample bio." } } ``` ``` -------------------------------- ### OAuth2 Flow Source: https://github.com/gc535/light-tiktok-oauth2-backend/blob/master/README.md Initiates the one-time OAuth2 authentication flow with TikTok and handles the callback. ```APIDOC ## GET /auth/login ### Description Initiates the one-time OAuth2 authentication flow with TikTok. ### Method GET ### Endpoint `/auth/login` ## GET /auth/callback ### Description Handles the callback from TikTok after successful OAuth2 authentication. ### Method GET ### Endpoint `/auth/callback` ``` -------------------------------- ### Initiate TikTok OAuth2 Login Flow Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Initiates the TikTok OAuth2 authentication flow with PKCE support. It generates a code verifier and challenge and redirects the user to TikTok's authorization page. This is typically invoked via a cURL command in a browser. ```bash # Initiate OAuth2 flow in browser curl http://localhost:7777/auth/login # This redirects to TikTok's authorization page # After user approval, TikTok redirects to /auth/callback # Tokens are automatically saved with AES-256 encryption ``` -------------------------------- ### Initiate Graceful Server Shutdown (Bash) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt This bash command uses curl to send a POST request to the /shutdown endpoint for a graceful server termination. It's designed to safely shut down the server and any parent processes, which is beneficial for automated deployments and workflows. The response confirms the shutdown initiation. ```bash # Shutdown server curl -X POST http://localhost:7777/shutdown # Response: # { # "success": true, # "message": "Server shutdown initiated", # "timestamp": "2025-10-31T19:30:00.000Z" # } ``` -------------------------------- ### OAuth2 Login Endpoint Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Initiates the TikTok OAuth2 authentication flow with PKCE support. This endpoint redirects the user to TikTok's authorization page to grant requested scopes. ```APIDOC ## POST /auth/login ### Description Initiates the TikTok OAuth2 authentication flow with PKCE support, generating a secure code verifier and challenge, then redirecting the user to TikTok's authorization page with the required scopes for user info and video publishing. ### Method GET ### Endpoint /auth/login ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://localhost:7777/auth/login ``` ### Response #### Success Response (302 Redirect) Redirects the user to the TikTok authorization URL. #### Response Example Redirects to: `https://open.tiktokapis.com/v2/oauth2/authorize?client_key=...&scope=...&response_type=code&redirect_uri=...&code_challenge=...&code_challenge_method=S256` ``` -------------------------------- ### Upload Video to TikTok Inbox (Bash) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Uploads a video to the TikTok inbox using a POST request. This allows users to edit the video within the TikTok app before publishing. The response includes a publish ID and instructions for the user. ```bash # Upload video to TikTok inbox curl -X POST http://localhost:7777/video/upload \ -H "Content-Type: application/json" \ -d '{ "file_path": "/home/user/videos/raw_video.mp4" }' # Response example: # { # "success": true, # "message": "Video uploaded to TikTok inbox successfully. User must complete editing flow in TikTok app.", # "data": { # "publish_id": "v_inbox_67890xyz", # "file_info": { # "path": "/home/user/videos/raw_video.mp4", # "size": 25165824, # "size_mb": "24.00" # }, # "note": "Video is now in TikTok inbox. User must click on inbox notifications to continue the editing flow in TikTok and complete the post." # } # } ``` -------------------------------- ### Directly Upload Video to TikTok (Bash) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Uploads a video directly to TikTok using a POST request with file path and title. This method is suitable for immediate posting and supports limited privacy settings. The response includes a publish ID and a URL to check the upload status. ```bash # Upload video directly with title curl -X POST http://localhost:7777/video/direct-post \ -H "Content-Type: application/json" \ -d '{ "file_path": "/home/user/videos/my_video.mp4", "title": "My Amazing Video" }' # Response example: # { # "success": true, # "message": "Video upload requested successfully", # "data": { # "publish_id": "v_pub_12345abcdef", # "status_url": "http://localhost:7777/video/status?publish_id=v_pub_12345abcdef", # "file_info": { # "path": "/home/user/videos/my_video.mp4", # "size": 15728640, # "size_mb": "15.00" # } # } # } ``` -------------------------------- ### Manage TikTok OAuth2 Server Shutdown and Health Source: https://github.com/gc535/light-tiktok-oauth2-backend/blob/master/README.md API endpoints for graceful server shutdown and health checks. The shutdown endpoint facilitates integration into workflows like n8n by ensuring processes are terminated cleanly before responding. ```bash # Support graceful shutdown thru API (for easy integration in n8n workflow) curl -X POST http://localhost:7777/shutdown # Health check curl http://localhost:7777/health ``` -------------------------------- ### Direct Video Post API Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Uploads a video directly to TikTok with a title and privacy settings. This is a two-step process involving initialization and file upload. ```APIDOC ## POST /video/direct-post ### Description Uploads a video directly to TikTok with a title and privacy settings using a two-step process: initialization with metadata and file upload to TikTok's designated URL. Note that direct posting only supports certain privacy levels per TikTok's API restrictions. ### Method POST ### Endpoint `/video/direct-post` ### Parameters #### Request Body - **file_path** (string) - Required - The absolute or relative path to the video file on the server. - **title** (string) - Required - The title for the video. ### Request Example ```json { "file_path": "/home/user/videos/my_video.mp4", "title": "My Amazing Video" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **message** (string) - A confirmation message. - **data** (object) - Contains details about the initiated upload. - **publish_id** (string) - A unique identifier for the video publishing process. - **status_url** (string) - URL to check the status of the video upload. - **file_info** (object) - Information about the uploaded file. - **path** (string) - The path of the video file. - **size** (integer) - The size of the file in bytes. - **size_mb** (string) - The size of the file in megabytes, formatted to two decimal places. #### Response Example ```json { "success": true, "message": "Video upload requested successfully", "data": { "publish_id": "v_pub_12345abcdef", "status_url": "http://localhost:7777/video/status?publish_id=v_pub_12345abcdef", "file_info": { "path": "/home/user/videos/my_video.mp4", "size": 15728640, "size_mb": "15.00" } } } ``` ``` -------------------------------- ### OAuth2 Callback Handler Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Handles the redirect from TikTok after user authorization. This endpoint exchanges the authorization code for access and refresh tokens using the PKCE code verifier and stores them securely. ```APIDOC ## POST /auth/callback ### Description Handles the redirect from TikTok after user authorization, exchanges the authorization code for access and refresh tokens using the PKCE code verifier, and stores tokens securely in an encrypted local file. ### Method GET (Automatic redirect from TikTok) ### Endpoint /auth/callback ### Parameters #### Query Parameters * **code** (string) - Required - The authorization code provided by TikTok. * **state** (string) - Required - A secure random state parameter for CSRF protection. ### Request Example (This endpoint is called automatically by TikTok) ### Response #### Success Response (200 OK) Indicates successful token exchange and storage. #### Response Example ```json { "message": "Authentication successful. Tokens stored." } ``` #### Error Response * **400 Bad Request**: If the authorization code is missing or invalid. * **500 Internal Server Error**: If token exchange fails or storage encounters an issue. ``` -------------------------------- ### Handle TikTok OAuth2 Callback and Exchange Code for Tokens Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Handles the redirect from TikTok after user authorization. It exchanges the authorization code for access and refresh tokens using the PKCE code verifier and stores these tokens securely in an encrypted local file. This endpoint is automatically configured as the TIKTOK_REDIRECT_URI and is not manually invoked. ```javascript // This endpoint is called automatically by TikTok // No manual invocation needed - configured as TIKTOK_REDIRECT_URI // Example flow: const express = require('express'); const axios = require('axios'); // After user approves on TikTok: // TikTok redirects to: http://localhost:7777/auth/callback?code=AUTH_CODE&state=secureRandomState123 // Server exchanges code for tokens: const tokenResponse = await axios.post('https://open.tiktokapis.com/v2/oauth/token/', { client_key: 'your_client_key', client_secret: 'your_client_secret', code: 'AUTH_CODE', grant_type: 'authorization_code', redirect_uri: 'http://localhost:7777/auth/callback', code_verifier: 'generated_pkce_verifier' }); // Response includes: // { // access_token: "act.example...", // refresh_token: "rft.example...", // expires_in: 86400, // token_type: "Bearer" // } ``` -------------------------------- ### User Info API Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Retrieves user information from TikTok based on specified fields. Supports open_id, union_id, avatar_url, display_name, and bio_description. ```APIDOC ## GET /user/info ### Description Retrieves user information from TikTok based on specified fields. Supports `open_id`, `union_id`, `avatar_url`, `display_name`, and `bio_description`. ### Method GET ### Endpoint `/user/info` ### Parameters #### Query Parameters - **fields** (string) - Required - Comma-separated list of fields to retrieve (e.g., `open_id,union_id,avatar_url,display_name,bio_description`) ### Request Example ``` GET http://localhost:7777/user/info?fields=open_id,union_id,avatar_url,display_name,bio_description ``` ### Response #### Success Response (200) - **data** (object) - Contains user details. - **user** (object) - User profile information. - **open_id** (string) - TikTok's unique identifier for the user. - **union_id** (string) - Union ID for the user across different apps. - **avatar_url** (string) - URL to the user's profile picture. - **display_name** (string) - User's display name. - **bio_description** (string) - User's biography. #### Response Example ```json { "error": { "code": "ok" }, "data": { "user": { "open_id": "oi_12345abc", "union_id": "ui_67890xyz", "avatar_url": "http://example.com/avatar.jpg", "display_name": "TikTokUser", "bio_description": "Just a TikTok enthusiast!" } } } ``` ``` -------------------------------- ### Video Upload to Inbox API Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Uploads a video to the TikTok inbox for user editing before posting. Creators can add effects, sounds, and captions through the TikTok app interface. ```APIDOC ## POST /video/upload ### Description Uploads a video to the TikTok inbox for user editing before posting, allowing creators to add effects, sounds, and captions through the TikTok app interface before publishing. ### Method POST ### Endpoint `/video/upload` ### Parameters #### Request Body - **file_path** (string) - Required - The absolute or relative path to the video file on the server. ### Request Example ```json { "file_path": "/home/user/videos/raw_video.mp4" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the upload was successful. - **message** (string) - A confirmation message indicating the video is in the inbox. - **data** (object) - Contains details about the uploaded video. - **publish_id** (string) - A unique identifier for the upload process. - **file_info** (object) - Information about the uploaded file. - **path** (string) - The path of the video file. - **size** (integer) - The size of the file in bytes. - **size_mb** (string) - The size of the file in megabytes, formatted to two decimal places. - **note** (string) - Instructions for the user on how to complete the posting flow. #### Response Example ```json { "success": true, "message": "Video uploaded to TikTok inbox successfully. User must complete editing flow in TikTok app.", "data": { "publish_id": "v_inbox_67890xyz", "file_info": { "path": "/home/user/videos/raw_video.mp4", "size": 25165824, "size_mb": "24.00" }, "note": "Video is now in TikTok inbox. User must click on inbox notifications to continue the editing flow in TikTok and complete the post." } } ``` ``` -------------------------------- ### SecureTokenStorage: Encrypt and Manage OAuth2 Tokens (JavaScript) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt The SecureTokenStorage class encrypts OAuth2 tokens using AES-256-CBC and persists them to disk. It supports custom or auto-generated encryption keys, token saving, loading, validation, and clearing. Ensure your encryption key is at least 32 characters long for proper security. ```javascript const SecureTokenStorage = require('./tokenStorage'); // Initialize with custom encryption key const storage = new SecureTokenStorage('my-secret-encryption-key-at-least-32-chars'); // Or use auto-generated key const storageAuto = new SecureTokenStorage(); // Save tokens (automatically encrypted) const tokens = { access_token: 'act.example1234567890abcdef', refresh_token: 'rft.example0987654321fedcba', expires_at: Date.now() + 86400000 // 24 hours from now }; storage.saveTokens(tokens); // Output: "Tokens saved securely" // Load tokens (automatically decrypted) const loadedTokens = storage.loadTokens(); // Output: "Tokens loaded successfully" console.log(loadedTokens); // { // access_token: 'act.example1234567890abcdef', // refresh_token: 'rft.example0987654321fedcba', // expires_at: 1730404065000 // } // Check if valid tokens exist (with 5-minute buffer) const hasValid = storage.hasValidTokens(); console.log('Has valid tokens:', hasValid); // true or false // Clear tokens storage.clearTokens(); // Output: "Tokens cleared" ``` -------------------------------- ### Directly Upload Video to TikTok (Node.js) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Node.js function to upload a video directly to TikTok. It validates the file's existence and size (up to 4GB limit) before sending the POST request. It uses the 'axios' library for HTTP requests and 'fs' for file system operations. ```javascript // Node.js example with file validation const fs = require('fs'); const axios = require('axios'); async function uploadVideo(filePath, title) { // Validate file exists if (!fs.existsSync(filePath)) { throw new Error('Video file not found'); } // Check file size (TikTok max: 4GB) const stats = fs.statSync(filePath); const maxSize = 4 * 1024 * 1024 * 1024; // 4GB if (stats.size > maxSize) { throw new Error('Video file exceeds 4GB limit'); } try { const response = await axios.post('http://localhost:7777/video/direct-post', { file_path: filePath, title: title }); console.log('Upload initiated:', response.data); console.log('Check status at:', response.data.data.status_url); return response.data.data.publish_id; } catch (error) { console.error('Upload failed:', error.response?.data || error.message); throw error; } } // Usage uploadVideo('/path/to/video.mp4', 'My Video Title') .then(publishId => console.log('Publish ID:', publishId)) .catch(err => console.error('Error:', err.message)); ``` -------------------------------- ### Check Video Upload Status API Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Queries the processing status of an uploaded video using its publish_id. ```APIDOC ## GET /video/status ### Description Queries the processing status of an uploaded video using its publish_id, returning information about upload progress, processing state, and any errors encountered. ### Method GET ### Endpoint `/video/status` ### Parameters #### Query Parameters - **publish_id** (string) - Required - The unique identifier for the video upload process. ### Request Example ``` GET http://localhost:7777/video/status?publish_id=v_pub_12345abcdef ``` ### Response #### Success Response (200) - **status** (string) - The current status of the video upload (e.g., "processing", "completed", "failed"). - **progress** (integer) - The percentage of completion for the upload/processing. - **message** (string) - Additional details or error messages if applicable. #### Response Example ```json { "status": "processing", "progress": 50, "message": "Video is currently being processed." } ``` ``` -------------------------------- ### Upload Video to TikTok Inbox (Python) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt Python function to upload a video to the TikTok inbox using the 'requests' library. It first checks if the file exists and then sends a POST request with the file path. The function handles potential request errors and prints the upload status. ```python # Python example with requests import requests import os def upload_to_inbox(file_path): """Upload video to TikTok inbox for editing""" if not os.path.exists(file_path): raise FileNotFoundError(f"Video file not found: {file_path}") url = "http://localhost:7777/video/upload" payload = {"file_path": file_path} try: response = requests.post(url, json=payload) response.raise_for_status() data = response.json() if data.get("success"): print(f"✓ Upload successful!") print(f" Publish ID: {data['data']['publish_id']}") print(f" File size: {data['data']['file_info']['size_mb']} MB") print(f" Note: {data['data']['note']}") return data['data']['publish_id'] else: raise Exception(f"Upload failed: {data}") except requests.exceptions.RequestException as e: print(f"✗ Upload error: {e}") raise # Usage publish_id = upload_to_inbox("/path/to/video.mp4") ``` -------------------------------- ### TikTokAuthManager: Handle OAuth2 Token Refresh (JavaScript) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt The TikTokAuthManager class automates the process of obtaining and refreshing TikTok OAuth2 access tokens. It utilizes SecureTokenStorage for persisting tokens and Axios for making API requests to the TikTok token endpoint. Ensure TikTok API credentials and an encryption key are available as environment variables. ```javascript // Example: Implementing token refresh logic const SecureTokenStorage = require('./tokenStorage'); const axios = require('axios'); class TikTokAuthManager { constructor(clientKey, clientSecret, encryptionKey) { this.clientKey = clientKey; this.clientSecret = clientSecret; this.storage = new SecureTokenStorage(encryptionKey); } async getValidAccessToken() { const tokens = this.storage.loadTokens(); if (!tokens) { throw new Error('No tokens found. Please authenticate first.'); } // Check if token expires within 1 minute if (Date.now() >= tokens.expires_at - 60000) { console.log('Access token expired, refreshing...'); return await this.refreshToken(tokens.refresh_token); } return tokens.access_token; } async refreshToken(refreshToken) { try { const response = await axios.post( 'https://open.tiktokapis.com/v2/oauth/token/', { client_key: this.clientKey, client_secret: this.clientSecret, grant_type: 'refresh_token', refresh_token: refreshToken } ); const { access_token, refresh_token, expires_in } = response.data; // Save new tokens this.storage.saveTokens({ access_token, refresh_token, expires_at: Date.now() + expires_in * 1000 }); console.log('Token refreshed successfully'); return access_token; } catch (error) { console.error('Token refresh failed:', error.response?.data || error.message); throw error; } } } // Usage const authManager = new TikTokAuthManager( process.env.TIKTOK_CLIENT_KEY, process.env.TIKTOK_CLIENT_SECRET, process.env.ENCRYPTION_KEY ); // Automatically uses cached token or refreshes if expired authManager.getValidAccessToken() .then(token => console.log('Valid token:', token)) .catch(err => console.error('Auth error:', err.message)); ``` -------------------------------- ### Poll TikTok Video Upload Status (JavaScript) Source: https://context7.com/gc535/light-tiktok-oauth2-backend/llms.txt This JavaScript function polls the status of a TikTok video upload using its publish ID. It retries up to a maximum number of attempts and checks for terminal states like 'PUBLISH_COMPLETE' or 'FAILED'. Dependencies include the 'fetch' API. ```javascript async function pollUploadStatus(publishId, maxAttempts = 30, interval = 10000) { let attempts = 0; while (attempts < maxAttempts) { try { const response = await fetch( `http://localhost:7777/video/status?publish_id=${publishId}` ); const data = await response.json(); const status = data.data.status; console.log(`[${new Date().toISOString()}] Status: ${status}`); // Terminal states if (status === 'PUBLISH_COMPLETE') { console.log('✓ Video published successfully!'); console.log('Post IDs:', data.data.publicaly_available_post_id); return data; } if (status === 'FAILED') { console.error('✗ Upload failed:', data.data.fail_reason); throw new Error(`Upload failed: ${data.data.fail_reason}`); } // Still processing console.log(` Waiting ${interval/1000}s before next check...`); await new Promise(resolve => setTimeout(resolve, interval)); attempts++; } catch (error) { console.error('Error checking status:', error.message); throw error; } } throw new Error('Timeout: Video processing took too long'); } // Usage pollUploadStatus('v_pub_12345abcdef') .then(result => console.log('Final result:', result)) .catch(err => console.error('Failed:', err.message)); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.