DEV Community

Ehtesham Ali
Ehtesham Ali

Posted on

Integrating TikTok API with Laravel: A Comprehensive Guide

Integrating TikTok API into your Laravel application enables you to access a wide range of TikTok features, such as fetching user profiles, analyzing video data, and managing accounts. This blog will guide you step-by-step through the process of integrating TikTok into your Laravel application, using a practical example.

Prerequisites

TikTok Developer Account: Register your application on the TikTok Developer Portal.
Laravel Application: Ensure you have a Laravel application set up.
TikTok API PHP SDK: Install the SDK (jstolpe/tiktok-api-php-sdk) via Composer:

composer require jstolpe/tiktok-api-php-sdk
Enter fullscreen mode Exit fullscreen mode

Step 1: TikTok API Configuration

Add your TikTok client_key and client_secret to the .env file:

TIK_TOK_CLIENT_KEY=your-client-key
TIK_TOK_SECRET=your-client-secret
NGROK_REDIRECT_URI=https://your-ngrok-url/tiktok/callback
Enter fullscreen mode Exit fullscreen mode

Note: Use Ngrok for local development to expose your Laravel application to the internet.

Step 2: Create the TikTok Controller

In the App\Http\Controllers namespace, create a TikTokController. This controller handles TikTok API calls, authentication, and user information retrieval. Below is the core functionality:

Redirect to TikTok for Authentication:

public function redirectToTikTok()
{
    $authentication = new Authentication([
        'client_key' => env('TIK_TOK_CLIENT_KEY'),
        'client_secret' => env('TIK_TOK_SECRET')
    ]);

    $redirectUri = env('NGROK_REDIRECT_URI');
    $scopes = ['user.info.basic', 'user.info.profile', 'user.info.stats', 'video.list'];

    try {
        $authenticationUrl = $authentication->getAuthenticationUrl($redirectUri, $scopes);
        return redirect($authenticationUrl);
    } catch (\Exception $e) {
        return response()->json(['error' => $e->getMessage()]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Handle the TikTok Callback:

public function handleCallback(Request $request)
{
    $authentication = new Authentication([
        'client_key' => env('TIK_TOK_CLIENT_KEY'),
        'client_secret' => env('TIK_TOK_SECRET')
    ]);

    $authCode = $request->get('code');
    $redirectUri = env('NGROK_REDIRECT_URI');

    if (!$authCode) {
        return response()->json(['error' => 'Authorization code is missing']);
    }

    try {
        $tokenFromCode = $authentication->getAccessTokenFromCode($authCode, $redirectUri);
        $accessToken = $tokenFromCode['access_token'];

        Token::updateOrCreate(['id' => 1], ['access_token' => $accessToken]);

        return response()->json(['access_token' => $accessToken]);
    } catch (\Exception $e) {
        return response()->json(['error' => $e->getMessage()]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Retrieve User Information:

public function getUserInfo()
{
    $tokenRecord = Token::find(1);

    if (!$tokenRecord || !$tokenRecord->access_token) {
        return response()->json(['error' => 'Access token is missing'], 404);
    }

    $config = ['access_token' => $tokenRecord->access_token];
    $user = new User($config);

    $params = Params::getFieldsParam([
        'open_id', 'union_id', 'avatar_url', 'display_name', 'follower_count'
    ]);

    try {
        $userInfo = $user->getSelf($params);
        return response()->json($userInfo);
    } catch (\Exception $e) {
        return response()->json(['error' => $e->getMessage()], 500);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a Model for Storing Tokens

Create a Token model to store the TikTok access token:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Token extends Model
{
    use HasFactory;

    protected $fillable = ['access_token'];
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Define Routes

Add the following routes to handle TikTok authentication and API calls:

use App\Http\Controllers\TikTokController;

Route::get('tiktok/redirect', [TikTokController::class, 'redirectToTikTok']);
Route::get('tiktok/callback', [TikTokController::class, 'handleCallback'])->name('tiktok.callback');
Route::get('tiktok/user-info', [TikTokController::class, 'getUserInfo'])->name('tiktok.user-info');
Enter fullscreen mode Exit fullscreen mode

Step 5: Test Your Integration

  • Visit /tiktok/redirect to initiate TikTok authentication.
  • Upon successful authentication, you will be redirected to /tiktok/callback where the access token is stored.
  • Fetch user details by visiting /tiktok/user-info.

Conclusion

This integration allows your Laravel application to interact with TikTok's API, enabling access to user data, video information, and more. By following this guide, you can build TikTok-powered features tailored to your applicationโ€™s needs.

Feel free to extend this example to include video management, analytics, or other TikTok features!

Top comments (0)