TikTok Shop PHP SDK

repository·master·Indexed 42 days ago

https://github.com/ecomphp/tiktokshop-php

A PHP SDK for interacting with the TikTok Shop API. It provides simplified access to product management, order processing, and OAuth authentication, including tools for managing access tokens, handling webhooks, and an MCP server for API discovery. Defaults to API version 202309.

Tokens
9.5K
Snippets
36
Records
45
Agent score
52%

What's inside tiktokshop-php

  1. Configure the TiktokShop PHP Client

    master

    Initialize the EcomPHP\TiktokShop\Client by providing your application credentials (app_key and app_secret).

    use EcomPHP\TiktokShop\Client;
    
    $app_key = 'your app key';
    $app_secret = 'your app secret';
    
    $client = new Client($app_key, $app_secret);
  2. Refresh an expired access token

    master

    When an access token expires, use the refreshNewToken($refresh_token) method from the auth object to obtain a new access_token and refresh_token.

    $new_token = $auth->refreshNewToken($refresh_token);
    
    $new_access_token = $new_token['access_token'];
    $new_refresh_token = $new_token['refresh_token'];
  3. Handle incoming Webhooks

    master

    You can handle TikTok Shop webhooks using the Webhook class. You can either use the client's built-in webhook helper or manually instantiate a Webhook object with the client to verify and capture the payload from $_POST.

    use EcomPHP\TiktokShop\Webhook;
    use EcomPHP\TiktokShop\Errors\TiktokShopException;
    
    $webhook = new Webhook($client);
    try {
        $webhook->verify();
        $webhook->capture($_POST);
    } catch (TiktokShopException $e) {
        echo "webhook error: " . $e->getMessage() . "\n";
    }
    
    echo "Type: " . $webhook->getType() . "\n";
    echo "Timestamp: " . $webhook->getTimestamp() . "\n";
    echo "Shop ID: " . $webhook->getShopId() . "\n";
    echo "Data: \n";
    print_r($webhook->getData());
  4. Grant access via OAuth

    master

    Use the auth() method on the client to manage the OAuth flow. This involves three main steps:

    1. Create an authentication request: Generate an authorization URL. You can either let the SDK auto-redirect or pass true as the second argument to createAuthRequest($state, true) to receive the URL string manually.
    2. Exchange code for tokens: After the user is redirected back to your callback URL, capture the code from the query string and pass it to getToken($authorization_code) to receive an array containing access_token and refresh_token.
    3. Retrieve authorized shop details: Set the access token on the client and use getAuthorizedShop() to retrieve the shop_id and cipher required for subsequent API calls.
    // 1. Create request
    $auth = $client->auth();
    $state = str_random(40);
    $_SESSION['state'] = $state;
    $authUrl = $auth->createAuthRequest($state, true);
    header('Location: '.$authUrl);
    
    // 2. Exchange code for tokens (on callback)
    $authorization_code = $_GET['code'];
    $token = $auth->getToken($authorization_code);
    $access_token = $token['access_token'];
    $refresh_token = $token['refresh_token'];
    
    // 3. Get shop details
    $client->setAccessToken($access_token);
    $authorizedShopList = $client->Authorization->getAuthorizedShop();
  5. Access TikTok Shop Resources

    master

    The Client provides access to various TikTok Shop domains (resources) via magic properties. Each resource class is located in the EcomPHP\TiktokShop\Resources namespace.

    Available resources include:

    • Authorization
    • Seller
    • Product
    • Order
    • Fulfillment
    • Logistic
    • Finance
    • GlobalProduct
    • Promotion
    • Supplychain
    • Event
    • ReturnRefund
    • CustomerService
    • AffiliateSeller
    • AffiliateCreator
    • AffiliatePartner
    • Analytics
    • FulfilledByTiktok
    // Example: Accessing the Product resource
    $productResource = $client->Product;
  6. Handle incoming TikTok Shop webhooks with the Webhook class

    master

    The EcomPHP\TiktokShop\Webhook class is used to capture, verify, and parse incoming notification payloads from TikTok Shop.

    To use it, instantiate the class with your existing Client instance, then use capture() to load the payload and verify() to ensure the request is authentic using the HMAC signature.

    Workflow

    1. Initialize: Create a new Webhook($client).
    2. Capture: Call capture() without arguments to automatically read from php://input, or pass an array of parameters manually.
    3. Verify: Call verify() to validate the signature against your AppSecret. By default, it looks for the signature in the HTTP_AUTHORIZATION server variable.
    4. Extract: Use getter methods to access the event type, shop ID, timestamp, and the event data.
    use EcomPHP\TiktokShop\Webhook;
    
    // Assuming $client is already initialized
    $webhook = new Webhook($client);
    
    try {
        // 1. Capture the payload
        $webhook->capture();
    
        // 2. Verify the signature (checks HTTP_AUTHORIZATION by default)
        if ($webhook->verify()) {
            // 3. Process the data
            $type = $webhook->getType();
            $shopId = $webhook->getShopId();
            $data = $webhook->getData();
            
            if ($type === Webhook::ORDER_STATUS_UPDATE) {
                // Handle order status change
            }
        }
    } catch (TiktokShopException $e) {
        // Handle invalid signature or invalid data
        echo 'Webhook error: ' . $e->getMessage();
    }
  7. Initialize the TikTok Shop Client

    master

    To use the SDK, instantiate the EcomPHP\ TiktokShop\ Client class with your app_key and app_secret. You can optionally pass Guzzle HTTP client options as the third argument. By default, the client uses API version 202309.

    use EcomPHP\TiktokShop\Client;
    
    $client = new Client(
        'your_app_key',
        'your_app_secret',
        [] // optional Guzzle options
    );
  8. Use the TikTok Shop MCP Server for API Discovery

    master

    The tiktokshop-mcp-server is a Model Context Protocol (MCP) implementation that allows AI agents to discover and inspect the TikTok Shop API documentation. It provides two primary tools to navigate the API reference: searching for APIs via a list and retrieving detailed implementation specifications for a specific endpoint.

    Recommended Workflow:

    1. Use get_api_list to find the relevant API category or search for a specific keyword (e.g., "order list").
    2. Identify the path or document_id from the list results.
    3. Use get_api_detail with that path to get the full technical specification (endpoints, methods, required headers, and body fields).
    // Example workflow for an AI agent:
    
    // 1. Search for order APIs
    // Tool: get_api_list
    // Arguments: { "search": "order list" }
    
    // 2. Get details for a specific API found in step 1
    // Tool: get_api_detail
    // Arguments: { "path": "get-order-list-202309" }
  9. Use the TiktokShop API for Products and Orders

    master

    To make API calls, you must first set the access_token and shop_cipher on the client instance. Once configured, you can access resource modules like Product and Order.

    $client = new Client($app_key, $app_secret);
    $client->setAccessToken($access_token);
    $client->setShopCipher($shop_cipher);
    
    // Get product list
    $products = $client->Product->getProductList([
        'page_size' => 50,
    ]);
    
    // Get order list
    $orders = $client->Order->getOrderList([
        'order_status' => 100, // Unpaid order
        'page_size' => 50,
    ]);
  10. Change the API version for a specific call

    master

    The SDK defaults to API version 202309. If you need to use a different version for a specific request, use the useVersion() method on the resource module before calling the target method.

    $products = $client->Product->useVersion('202312')->checkListingPrerequisites(); 
  11. Handle TikTok Shop SDK errors with TiktokShopException

    master

    All errors thrown by the TikTok Shop PHP SDK are instances of EcomPHP\TiktokShop\Errors\TiktokShopException. When integrating the SDK, you should catch this specific exception to handle API-related failures, such as authentication issues, invalid parameters, or service errors, separately from general PHP exceptions.

    use EcomPHP\TiktokShop\Errors\TiktokShopException;
    
    try {
        // Your TikTok Shop API calls here
    } catch (TiktokShopException $e) {
        // Handle SDK-specific errors
        echo 'TikTok Shop Error: ' . $e->getMessage();
    } catch (\Exception $e) {
        // Handle other general errors
        echo 'General Error: ' . $e->getMessage();
    }