@ecomdy/tiktok-sdk
v0.1.0
Published
Ecomdy TikTok Partner SDK for TypeScript/JavaScript - Business & Marketing API Integration
Readme
TikTok SDK for TypeScript/JavaScript
MVP Version - Minimal SDK for partner integration testing and validation
A lightweight TypeScript/JavaScript SDK for integrating with TikTok's API platform. This MVP version focuses on core OAuth2 authentication and essential user/video endpoints for partner validation.
Features
- ✅ OAuth2 authentication flow
- ✅ Token management and refresh
- ✅ User profile information
- ✅ User videos listing
- ✅ TypeScript support with full type definitions
- ✅ Node.js and browser compatibility
- ✅ Minimal dependencies (only axios)
Installation
npm install @ecomdy/tiktok-sdkQuick Start
1. Initialize the SDK
import { TikTokSDK } from '@ecomdy/tiktok-sdk';
const sdk = new TikTokSDK({
clientId: 'your_client_id',
clientSecret: 'your_client_secret',
redirectUri: 'https://your-app.com/callback',
scope: ['user.info.basic', 'video.list']
});2. OAuth2 Authentication
// Generate authorization URL
const authUrl = sdk.oauth.getAuthorizationUrl('optional_state');
console.log('Visit this URL:', authUrl);
// Exchange authorization code for token (in your callback handler)
const tokenInfo = await sdk.oauth.getAccessToken(authorizationCode);
// Set token for API calls
sdk.setTokenInfo(tokenInfo);3. Make API Calls
// Get user information
const userInfo = await sdk.user.getCurrentUser();
console.log('User:', userInfo.display_name);
// Get user's videos
const videos = await sdk.video.getUserVideos({ max_count: 10 });
console.log('Videos:', videos.videos.length);Configuration Options
interface TikTokSDKConfig {
// OAuth2 Configuration
clientId: string; // Your app's client ID
clientSecret: string; // Your app's client secret
redirectUri: string; // OAuth callback URL
scope?: string[]; // Requested permissions
// API Configuration
accessToken?: string; // Pre-existing access token
baseUrl?: string; // API base URL (default: TikTok's API)
timeout?: number; // Request timeout in ms (default: 30000)
}Available Scopes
user.info.basic- Access basic user profile informationvideo.list- Access user's video list and details
API Reference
Authentication (sdk.oauth)
// Generate authorization URL
getAuthorizationUrl(state?: string): string
// Exchange code for access token
getAccessToken(code: string): Promise<TikTokTokenInfo>
// Refresh access token
refreshAccessToken(refreshToken: string): Promise<TikTokTokenInfo>
// Check if token is expired
isTokenExpired(tokenInfo: TikTokTokenInfo): booleanUser API (sdk.user)
// Get current user information
getCurrentUser(fields?: string[]): Promise<TikTokUserInfo>Video API (sdk.video)
// Get user's videos
getUserVideos(params?: TikTokQueryParams): Promise<TikTokVideosResponse>
// Get specific video information
getVideoInfo(videoId: string, fields?: string[]): Promise<TikTokVideoInfo>Examples
Express.js Integration
import express from 'express';
import { TikTokSDK } from '@ecomdy/tiktok-sdk';
const app = express();
const sdk = new TikTokSDK({ /* config */ });
// Start OAuth flow
app.get('/auth', (req, res) => {
const authUrl = sdk.oauth.getAuthorizationUrl();
res.redirect(authUrl);
});
// Handle callback
app.get('/callback', async (req, res) => {
const { code } = req.query;
const tokenInfo = await sdk.oauth.getAccessToken(code);
// Store tokenInfo in session/database
req.session.tokenInfo = tokenInfo;
res.redirect('/profile');
});
// Protected route
app.get('/profile', async (req, res) => {
sdk.setTokenInfo(req.session.tokenInfo);
const userInfo = await sdk.user.getCurrentUser();
res.json(userInfo);
});Next.js API Routes
// pages/api/auth/callback.ts
import { TikTokSDK } from '@ecomdy/tiktok-sdk';
export default async function handler(req, res) {
const sdk = new TikTokSDK({ /* config */ });
const { code } = req.query;
try {
const tokenInfo = await sdk.oauth.getAccessToken(code);
// Store in session or return to client
res.json({ success: true, tokenInfo });
} catch (error) {
res.status(400).json({ error: error.message });
}
}React Hook
import { useState, useEffect } from 'react';
import { TikTokSDK } from '@ecomdy/tiktok-sdk';
export function useTikTokUser(accessToken: string) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const sdk = new TikTokSDK({ accessToken });
sdk.user.getCurrentUser()
.then(setUser)
.finally(() => setLoading(false));
}, [accessToken]);
return { user, loading };
}Error Handling
The SDK throws descriptive errors for common scenarios:
try {
const userInfo = await sdk.user.getCurrentUser();
} catch (error) {
if (error.message.includes('Unauthorized')) {
// Token expired or invalid
// Redirect to re-authentication
} else if (error.message.includes('Rate limit')) {
// Handle rate limiting
} else {
// Handle other API errors
}
}Token Management
// Check if token is expired
if (sdk.oauth.isTokenExpired(tokenInfo)) {
// Refresh token if available
if (tokenInfo.refreshToken) {
const newTokenInfo = await sdk.oauth.refreshAccessToken(tokenInfo.refreshToken);
sdk.setTokenInfo(newTokenInfo);
} else {
// Redirect to re-authentication
}
}Requirements
- Node.js 16+ or modern browser environment
- TikTok Developer App with approved OAuth2 credentials
Getting TikTok API Access
- Create a TikTok Developer account at developers.tiktok.com
- Create a new app and configure OAuth2 settings
- Add your redirect URI to the app configuration
- Get your
client_idandclient_secret
Limitations (MVP Version)
- Limited to basic user info and video listing endpoints
- No file upload or content creation features
- No webhook handling
- No advanced error recovery or retry logic
- No caching or offline support
TypeScript Support
Full TypeScript definitions are included:
import {
TikTokSDK,
TikTokUserInfo,
TikTokVideoInfo,
TikTokTokenInfo,
TikTokOAuthConfig
} from '@ecomdy/tiktok-sdk';Contributing
This is an MVP version for partner validation. For production features and improvements, please contact the TikTok Partners team.
License
MIT
Support
- GitHub Issues: [Report bugs and feature requests]
- Partner Support: Contact your TikTok partner representative
- Documentation: API Documentation
Note: This is an MVP version designed for partner integration testing. Production-ready features, enhanced error handling, and additional endpoints will be added based on partner feedback.
