### Install TiktokShop PHP Client with Composer Source: https://github.com/ecomphp/tiktokshop-php/blob/master/README.md Install the library using Composer. This is the first step to integrate the TiktokShop API into your PHP project. ```shell composer require ecomphp/tiktokshop-php ``` -------------------------------- ### Get Product List Source: https://github.com/ecomphp/tiktokshop-php/blob/master/README.md Retrieve a list of products associated with the shop. You can specify parameters like page size to control the results. ```php $products = $client->Product->getProductList([ 'page_size' => 50, ]); ``` -------------------------------- ### Search and Get Coupon Details Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Retrieve information about available coupons. Specify status and pagination parameters for searching. ```php // Search coupons $coupons = $client->Promotion->searchCoupons( ['page_size' => 20], ['status' => 'ACTIVE'] ); // Get coupon detail $coupon = $client->Promotion->getCoupon('COUPON_ID'); ``` -------------------------------- ### Get Order List Source: https://github.com/ecomphp/tiktokshop-php/blob/master/README.md Fetch a list of orders for the shop, with options to filter by order status and page size. For example, retrieve unpaid orders. ```php $orders = $client->Order->getOrderList([ 'order_status' => 100, // Unpaid order 'page_size' => 50, ]); ``` -------------------------------- ### Get Seller Shop Info and Permissions Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Access the Seller resource to retrieve a list of all active shops for the seller and check their granted API permissions. ```php $client->setAccessToken($accessToken); $client->setShopCipher($shopCipher); // Get all active shops for this seller $activeShops = $client->Seller->getActiveShopList(); // Get seller permissions (what API scopes are granted) $permissions = $client->Seller->getSellerPermissions(); print_r($permissions); // Output: ['permissions' => ['PRODUCT_READ', 'ORDER_READ', ...]] ``` -------------------------------- ### Get Video Performance Metrics Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Retrieve performance data for shoppable videos, including overview and per-video metrics. Requires API version 202405 or higher. ```php // Video performance overview $videoOverview = $client->Analytics->getShopVideoPerformanceOverview([ 'start_date' => '20240101', 'end_date' => '20240131', ]); // Per-video performance $videoPerf = $client->Analytics->getShopVideoPerformance('VIDEO_ID', [ 'start_date' => '20240101', 'end_date' => '20240131', ]); ``` -------------------------------- ### Get Product-Level Performance Metrics Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Fetch performance metrics for a specific product or a list of products within a given date range. Requires API version 202405 or higher. ```php // Product-level performance $productPerf = $client->Analytics->getShopProductPerformance('PRODUCT_ID', [ 'data_granularity' => 'DAY', 'start_date' => '20240101', 'end_date' => '20240131', ]); // List performance for all products $allProductPerf = $client->Analytics->getShopProductPerformanceList([ 'data_granularity' => 'DAY', 'start_date' => '20240101', 'end_date' => '20240131', 'page_size' => 20, ]); ``` -------------------------------- ### Auth — OAuth Flow Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Provides a guide to implementing the three-step OAuth authorization flow using the `Auth` instance obtained from the client. This includes creating the authorization URL, exchanging codes for tokens, and refreshing expired tokens. ```APIDOC ## Auth — OAuth Flow `$client->auth()` returns an `Auth` instance for driving the three-step OAuth authorization flow: redirect the seller to TikTok's consent page, exchange the authorization code for tokens, and refresh expired tokens. ```php use EcomPHP\TiktokShop\Errors\AuthorizationException; $auth = $client->auth(); // Step 1 — Generate auth URL and redirect seller $_SESSION['state'] = $state = bin2hex(random_bytes(20)); $authUrl = $auth->createAuthRequest($state, true); // true = return URL instead of redirect header('Location: ' . $authUrl); exit; // Step 2 — On callback: exchange code for tokens try { $token = $auth->getToken($_GET['code']); $accessToken = $token['access_token']; $refreshToken = $token['refresh_token']; // Persist $refreshToken for later renewal } catch (AuthorizationException $e) { echo "Auth failed [{$e->getCode()}]: " . $e->getMessage(); } // Step 3 — Refresh an expiring access token try { $newToken = $auth->refreshNewToken($refreshToken); $newAccessToken = $newToken['access_token']; $newRefreshToken = $newToken['refresh_token']; } catch (AuthorizationException $e) { echo "Refresh failed: " . $e->getMessage(); } ``` ``` -------------------------------- ### List Warehouses and Get Delivery Options Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Retrieve warehouse information and available delivery options for a specific warehouse. The first warehouse ID is used for subsequent calls. ```php // List all warehouses $warehouses = $client->Logistic->getWarehouseList(); $warehouseId = $warehouses['warehouses'][0]['id']; // Get delivery options for a warehouse $deliveryOptions = $client->Logistic->getWarehouseDeliveryOptions($warehouseId); $deliveryOptionId = $deliveryOptions['delivery_options'][0]['id']; ``` -------------------------------- ### Authorization Resource — Shop & Category Assets Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Details how to use the `Authorization` resource to discover shops and retrieve category assets. It explains how to get the `shop_cipher` needed for subsequent API calls. ```APIDOC ## Authorization Resource — Shop & Category Assets `$client->Authorization` provides shop discovery after the seller grants access. Call `getAuthorizedShop()` to obtain the `shop_cipher` required for all subsequent shop-scoped API calls. ```php $client->setAccessToken($accessToken); // List all authorized shops $shops = $client->Authorization->getAuthorizedShop(); // $shops['list'][0]['cipher'] => shop cipher to use in setShopCipher() // $shops['list'][0]['name'] => shop name foreach ($shops['list'] as $shop) { echo "Shop: {$shop['name']}, Cipher: {$shop['cipher']}\n"; } // Fetch category assets for the authorized seller $categoryAssets = $client->Authorization->getAuthorizedCategoryAssets(); ``` ``` -------------------------------- ### Get Shipping Providers for a Delivery Option Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Fetch available shipping providers based on a given delivery option ID. ```php // Get shipping providers for a delivery option $shippingProviders = $client->Logistic->getShippingProvider($deliveryOptionId); ``` -------------------------------- ### Get Shop-Level Performance Metrics Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Retrieve shop performance metrics such as GMV, orders, and page views for a specified date range and granularity. Requires API version 202405 or higher. ```php // Shop-level performance metrics $shopPerf = $client->Analytics->getShopPerformance([ 'data_granularity' => 'DAY', 'start_date' => '20240101', 'end_date' => '20240131', 'metrics' => ['GMV', 'ORDERS', 'PAGE_VIEWS'], ]); ``` -------------------------------- ### Get Authorized Shop Cipher Source: https://github.com/ecomphp/tiktokshop-php/blob/master/README.md Retrieve a list of shops authorized by the user and extract the necessary shop ID and cipher for subsequent API calls. ```php $access_token = $token['access_token']; $client->setAccessToken($access_token); $authorizedShopList = $client->Authorization->getAuthorizedShop(); // extract shop_id & cipher from $authorizedShopList for use later ``` -------------------------------- ### Retrieve Authorized Shop Information Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Use the Authorization resource to get shop details after seller authorization. Obtain the shop cipher required for subsequent shop-scoped API calls. ```php $client->setAccessToken($accessToken); // List all authorized shops $shops = $client->Authorization->getAuthorizedShop(); // $shops['list'][0]['cipher'] => shop cipher to use in setShopCipher() // $shops['list'][0]['name'] => shop name foreach ($shops['list'] as $shop) { echo "Shop: {$shop['name']}, Cipher: {$shop['cipher']}\n"; } // Fetch category assets for the authorized seller $categoryAssets = $client->Authorization->getAuthorizedCategoryAssets(); ``` -------------------------------- ### Manage Orders with TikTok Shop API Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt The Order resource facilitates order management, including searching orders by status with pagination, retrieving specific order details, getting price breakdowns (API 202407+), adding external order references (API 202406+), and searching orders by external references. ```php // Search orders by status with pagination $orders = $client->Order->getOrderList([ 'order_status' => 'AWAITING_SHIPMENT', 'page_size' => 50, 'sort_field' => 'create_time', 'sort_order' => 'DESC', 'create_time_ge' => strtotime('-7 days'), 'create_time_lt' => time(), ]); // $orders['orders'] => array of order objects // $orders['next_page_token'] => pagination cursor // Get specific order details $detail = $client->Order->getOrderDetail(['ORDER_ID_1', 'ORDER_ID_2']); // Get price breakdown for a single order (API 202407+) $priceDetail = $client->Order->getPriceDetail('ORDER_ID_1'); // Add external order reference (API 202406+) $client->Order->addExternalOrderReferences([ ['order_id' => 'TIKTOK_ORDER_ID', 'platform' => 'SHOPIFY', 'external_order_id' => 'SHOPIFY_ORDER_123'], ]); // Search by external order reference $found = $client->Order->searchOrderByExternalOrderReferences('SHOPIFY', 'SHOPIFY_ORDER_123'); ``` -------------------------------- ### Client Initialization and Configuration Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Demonstrates how to initialize the `Client` class and configure it with access tokens, shop ciphers, and optional Guzzle client options. It also shows how to set a default API version. ```APIDOC ## Client — Initialize and Configure `new Client($app_key, $app_secret, $options = [])` creates the main entry point. Call `setAccessToken()` and `setShopCipher()` before making authenticated API calls. The optional `$options` array is merged directly into the underlying Guzzle client configuration. ```php use EcomPHP\TiktokShop\Client; $client = new Client('your_app_key', 'your_app_secret'); // After obtaining OAuth tokens: $client->setAccessToken('ACCESS_TOKEN_HERE'); $client->setShopCipher('SHOP_CIPHER_HERE'); // Override default API version (202309) globally: $client->useVersion('202312'); ``` ``` -------------------------------- ### Initialize and Configure the Client Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Initialize the main client with your app credentials. Set the access token and shop cipher after obtaining OAuth tokens. You can also override the default API version. ```php use EcomPHP\TiktokShop\Client; $client = new Client('your_app_key', 'your_app_secret'); // After obtaining OAuth tokens: $client->setAccessToken('ACCESS_TOKEN_HERE'); $client->setShopCipher('SHOP_CIPHER_HERE'); // Override default API version (202309) globally: $client->useVersion('202312'); ``` -------------------------------- ### Initialize Client for API Usage Source: https://github.com/ecomphp/tiktokshop-php/blob/master/README.md Set the access token and shop cipher on the client instance to prepare for making authenticated API requests. ```php $client = new Client($app_key, $app_secret); $client->setAccessToken($access_token); $client->setShopCipher($shop_cipher); ``` -------------------------------- ### Create, Update, and Search Promotional Activities Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Manage promotional activities like sales and discounts. Ensure correct timestamps and product/SKU details when adding products. ```php // Create a promotional activity $activity = $client->Promotion->createActivity( 'Summer Sale', // title 'FIXED_PRICE', // activity_type strtotime('+1 day'), // begin_time (Unix timestamp) strtotime('+7 days'), // end_time 'SKU' // product_level: 'PRODUCT' or 'SKU' ); $activityId = $activity['activity_id']; // Add products to the activity $client->Promotion->updateActivityProduct($activityId, [ [ 'product_id' => 'PRODUCT_ID', 'skus' => [['id' => 'SKU_ID', 'activity_price' => ['amount' => '19.99', 'currency' => 'USD']]], ], ]); // Search activities $activities = $client->Promotion->searchActivities([ 'status' => 'ONGOING', 'page_size' => 20, ]); // Get a specific activity $detail = $client->Promotion->getActivity($activityId); // Deactivate an activity $client->Promotion->deactivateActivity($activityId); ``` -------------------------------- ### Configure TiktokShop PHP Client Source: https://github.com/ecomphp/tiktokshop-php/blob/master/README.md Initialize the client with your application's key and secret. Ensure you have these credentials from your Tiktok Shop developer account. ```php use EcomPHP\TiktokShop\Client; $app_key = 'your app key'; $app_secret = 'your app secret'; $client = new Client($app_key, $app_secret); ``` -------------------------------- ### Seller Resource — Shop Info & Permissions Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Explains how to use the `Seller` resource to retrieve shop-level information, such as active shop lists and seller permissions granted via API scopes. ```APIDOC ## Seller Resource — Shop Info & Permissions `$client->Seller` exposes shop-level information and permission checks. ```php $client->setAccessToken($accessToken); $client->setShopCipher($shopCipher); // Get all active shops for this seller $activeShops = $client->Seller->getActiveShopList(); // Get seller permissions (what API scopes are granted) $permissions = $client->Seller->getSellerPermissions(); print_r($permissions); // Output: ['permissions' => ['PRODUCT_READ', 'ORDER_READ', ...]] ``` ``` -------------------------------- ### Handle Returns and Cancellations Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Manages buyer cancellation requests, return initiation, approval/rejection, and refund calculations. Use for processing post-sale adjustments. ```php use EcomPHP\TiktokShop\Errors\ResponseException; // Search pending cancellations $cancellations = $client->ReturnRefund->searchCancellations([ 'page_size' => 20, 'status' => 'SELLER_PENDING', ]); // Approve a cancellation $client->ReturnRefund->approveCancellation('CANCEL_ID'); // Reject a cancellation with reason $client->ReturnRefund->rejectCancellation('CANCEL_ID', [ 'reject_reason_key' => 'ITEM_ALREADY_SHIPPED', 'reject_reason' => 'The item has already been shipped out.', ]); // Search returns $returns = $client->ReturnRefund->searchReturns([ 'page_size' => 20, 'status' => 'SELLER_PENDING', ]); // Approve a return $client->ReturnRefund->approveReturn('RETURN_ID', [ 'refund_amount' => '29.99', ]); // Calculate refund amount before approving $refundCalc = $client->ReturnRefund->calculateRefund([ 'order_id' => 'ORDER_ID', 'order_line_item_ids' => ['LINE_ITEM_ID'], 'return_type' => 'RETURN_AND_REFUND', ]); // Initiate a return on behalf of buyer $client->ReturnRefund->createReturn([ 'order_id' => 'ORDER_ID', 'order_line_item_ids' => ['LINE_ITEM_ID'], 'return_type' => 'RETURN_AND_REFUND', 'return_reason' => 'NOT_AS_DESCRIBED', 'images' => [], ]); // Get after-sale eligibility for an order $eligibility = $client->ReturnRefund->getAftersaleEligibility('ORDER_ID'); ``` -------------------------------- ### Get Access Token from Authorization Code Source: https://github.com/ecomphp/tiktokshop-php/blob/master/README.md Exchange the authorization code received after user consent for an access token and refresh token. This is a crucial step in the OAuth 2.0 flow. ```php $authorization_code = $_GET['code']; $token = $auth->getToken($authorization_code); $access_token = $token['access_token']; $refresh_token = $token['refresh_token']; ``` -------------------------------- ### Manually Configure Webhook Receiver Source: https://github.com/ecomphp/tiktokshop-php/blob/master/README.md Manually set up the webhook receiver, including verification and capturing incoming data. This requires handling potential exceptions during the process. ```php 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"; } ``` -------------------------------- ### Promotion Resource Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Manage promotional activities like flash sales and discounts, as well as coupon programs. ```APIDOC ## Promotion Resource — Activities & Coupons `$client->Promotion` manages promotional activities (flash sales, discounts) and coupon programs. ```php // Create a promotional activity $activity = $client->Promotion->createActivity( 'Summer Sale', // title 'FIXED_PRICE', // activity_type strtotime('+1 day'), // begin_time (Unix timestamp) strtotime('+7 days'), // end_time 'SKU' // product_level: 'PRODUCT' or 'SKU' ); $activityId = $activity['activity_id']; // Add products to the activity $client->Promotion->updateActivityProduct($activityId, [ [ 'product_id' => 'PRODUCT_ID', 'skus' => [['id' => 'SKU_ID', 'activity_price' => ['amount' => '19.99', 'currency' => 'USD']]], ], ]); // Search activities $activities = $client->Promotion->searchActivities([ 'status' => 'ONGOING', 'page_size' => 20, ]); // Get a specific activity $detail = $client->Promotion->getActivity($activityId); // Deactivate an activity $client->Promotion->deactivateActivity($activityId); // Search coupons $coupons = $client->Promotion->searchCoupons( ['page_size' => 20], ['status' => 'ACTIVE'] ); // Get coupon detail $coupon = $client->Promotion->getCoupon('COUPON_ID'); ``` ``` -------------------------------- ### CustomerService Resource Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Enable sellers to read and respond to buyer support conversations. ```APIDOC ## CustomerService Resource — Buyer Conversations `$client->CustomerService` enables sellers to read and respond to buyer support conversations. ```php // List all conversations $conversations = $client->CustomerService->getConversations(['page_size' => 20]); // Get messages in a conversation $messages = $client->CustomerService->getConversationMessages('CONVERSATION_ID', [ 'page_size' => 20, 'next_page_token' => '', ]); // Send a text message to a buyer $client->CustomerService->sendMessage( 'CONVERSATION_ID', 'TEXT', 'Thank you for your order! It will ship within 24 hours.' ); // Send an image message (upload first) $uploadResult = $client->CustomerService->uploadBuyerMessagesImage('/path/to/image.jpg'); $client->CustomerService->sendMessage( 'CONVERSATION_ID', 'IMAGE', json_encode(['url' => $uploadResult['url']]) ); // Mark conversation as read $client->CustomerService->readMessage('CONVERSATION_ID'); // Create a new conversation with a buyer $newConversation = $client->CustomerService->createConversation('BUYER_USER_ID'); ``` ``` -------------------------------- ### Initialize Webhook Receiver Source: https://github.com/ecomphp/tiktokshop-php/blob/master/README.md Instantiate the webhook handler using the configured client. This is used to process incoming notifications from Tiktok Shop. ```php $webhook = $client->webhook(); ``` -------------------------------- ### Manage Products with TikTok Shop API Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Use the Product resource to manage the full product lifecycle, including creation, retrieval, updates, deletion, activation/deactivation, image uploads, category lookups, and inventory management. Ensure access tokens and shop ciphers are set before making calls. ```php use EcomPHP\TiktokShop\Errors\ResponseException; $client->setAccessToken($accessToken); $client->setShopCipher($shopCipher); // Search products with filters $result = $client->Product->searchProducts([ 'page_size' => 20, 'page_token' => '', 'status' => 'ACTIVE', ]); // $result['products'] => array of product summaries // $result['next_page_token'] => cursor for next page // Get full product details $product = $client->Product->getProduct('7123456789012345678'); // Create a product $newProduct = $client->Product->createProduct([ 'title' => 'Wireless Earbuds Pro', 'description' => 'High quality wireless earbuds.', 'category_id' => '600001', 'brand_id' => '7001234567890', 'main_images' => [['uri' => 'tos-alisg-i-abc123/image.jpg']], 'skus' => [[ 'price' => ['amount' => '29.99', 'currency' => 'USD'], 'stock_infos' => [['warehouse_id' => 'WAREHOUSE_ID', 'available_stock' => 100]], ]], 'package_weight' => ['value' => '0.5', 'unit' => 'KILOGRAM'], ]); // Update inventory for a product $client->Product->updateInventory('7123456789012345678', [ 'skus' => [[ 'id' => 'SKU_ID', 'stock_infos' => [['warehouse_id' => 'WAREHOUSE_ID', 'available_stock' => 50]], ]], ]); // Activate / deactivate products $client->Product->activateProducts(['7111111111111111111', '7222222222222222222']); $client->Product->deactivateProducts(['7333333333333333333']); // Delete products $client->Product->deleteProducts(['7444444444444444444']); // Upload a product image (returns URI for use in createProduct) $uploadResult = $client->Product->uploadProductImage('/path/to/image.jpg', 'MAIN_IMAGE'); echo $uploadResult['uri']; // e.g. "tos-alisg-i-abc123/image.jpg" // Get categories (locale-specific) $categories = $client->Product->getCategories(['locale' => 'en-US']); // Recommend a category based on product title $recommended = $client->Product->recommendCategory( 'Wireless Earbuds Pro', 'Bluetooth 5.3 earbuds with noise cancellation', [['uri' => 'tos-alisg-i-abc123/image.jpg']] ); // Use a newer API version for a single call $prerequisites = $client->Product->useVersion('202312')->checkListingPrerequisites(); ``` -------------------------------- ### Receiving and Processing Webhooks Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt This snippet demonstrates how to use the Webhook class to verify incoming webhook requests, parse their payloads, and access the data. It covers both simple usage via the client and manual usage with custom input sources. ```APIDOC ## Webhook — Receiving Real-Time Notifications `$client->webhook()` (or the standalone `Webhook` class) verifies the HMAC-SHA256 signature of incoming TikTok Shop webhook requests and parses the payload into typed fields. ### Simple usage via client This method automatically verifies the signature and captures the payload from `php://input`. ```php use EcomPHP\TiktokShop\Webhook; use EcomPHP\TiktokShop\Errors\TiktokShopException; try { $webhook = $client->webhook(); } catch (TiktokShopException $e) { http_response_code(401); exit("Webhook error: " . $e->getMessage()); } ``` ### Manual usage for custom input sources This allows for more control over the input source and signature verification. ```php use EcomPHP\TiktokShop\Webhook; use EcomPHP\TiktokShop\Errors\TiktokShopException; $webhook = new Webhook($client); try { $rawBody = file_get_contents('php://input'); $signature = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; $webhook->verify($signature, $rawBody); // throws on invalid signature $webhook->capture(json_decode($rawBody, true)); // throws on invalid payload } catch (TiktokShopException $e) { http_response_code(400); exit($e->getMessage()); } ``` ### Accessing Webhook Data After successful verification and capture, you can access various details about the webhook event. ```php // Access webhook data $type = $webhook->getType(); // int: Webhook::ORDER_STATUS_UPDATE, etc. $shopId = $webhook->getShopId(); $timestamp = $webhook->getTimestamp(); $data = $webhook->getData(); // associative array, structure varies by type switch ($type) { case Webhook::ORDER_STATUS_UPDATE: // 1 echo "Order {" . $data['order_id'] . "} changed to status {" . $data['order_status'] . "}\n"; break; case Webhook::PRODUCT_STATUS_UPDATE: // 5 echo "Product {" . $data['product_id'] . "} status updated\n"; break; case Webhook::SELLER_DEAUTHORIZATION: // 6 echo "Seller deauthorized shop: {" . $shopId . "}\n"; break; case Webhook::RETURN_STATUS_UPDATE: // 12 echo "Return {" . $data['return_id'] . "} status updated\n"; break; } http_response_code(200); echo json_encode(['code' => 0]); ``` ### Webhook Type Constants | Constant | Value | Event | |---|---|---| | `ORDER_STATUS_UPDATE` | 1 | Order status changed | | `REVERSE_ORDER_STATUS_UPDATE` | 2 | Reverse order status changed | | `RECIPIENT_ADDRESS_UPDATE` | 3 | Recipient address changed | | `PACKAGE_UPDATE` | 4 | Package status changed | | `PRODUCT_STATUS_UPDATE` | 5 | Product status changed | | `SELLER_DEAUTHORIZATION` | 6 | Seller deauthorized the app | | `UPCOMING_AUTHORIZATION_EXPIRATION` | 7 | Authorization expiring soon | | `RETURN_STATUS_UPDATE` | 12 | Return status changed | ``` -------------------------------- ### ReturnRefund Resource Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Covers buyer cancellation requests, return initiation, approval/rejection, and refund calculation. ```APIDOC ## ReturnRefund Resource — Cancellations & Returns `$client->ReturnRefund` covers buyer cancellation requests, return initiation, approval/rejection, and refund calculation. ### Search pending cancellations ```php use EcomPHP\TiktokShop\Errors\ResponseException; // Search pending cancellations $cancellations = $client->ReturnRefund->searchCancellations([ 'page_size' => 20, 'status' => 'SELLER_PENDING', ]); ``` ### Approve a cancellation ```php // Approve a cancellation $client->ReturnRefund->approveCancellation('CANCEL_ID'); ``` ### Reject a cancellation with reason ```php // Reject a cancellation with reason $client->ReturnRefund->rejectCancellation('CANCEL_ID', [ 'reject_reason_key' => 'ITEM_ALREADY_SHIPPED', 'reject_reason' => 'The item has already been shipped out.', ]); ``` ### Search returns ```php // Search returns $returns = $client->ReturnRefund->searchReturns([ 'page_size' => 20, 'status' => 'SELLER_PENDING', ]); ``` ### Approve a return ```php // Approve a return $client->ReturnRefund->approveReturn('RETURN_ID', [ 'refund_amount' => '29.99', ]); ``` ### Calculate refund amount before approving ```php // Calculate refund amount before approving $refundCalc = $client->ReturnRefund->calculateRefund([ 'order_id' => 'ORDER_ID', 'order_line_item_ids' => ['LINE_ITEM_ID'], 'return_type' => 'RETURN_AND_REFUND', ]); ``` ### Initiate a return on behalf of buyer ```php // Initiate a return on behalf of buyer $client->ReturnRefund->createReturn([ 'order_id' => 'ORDER_ID', 'order_line_item_ids' => ['LINE_ITEM_ID'], 'return_type' => 'RETURN_AND_REFUND', 'return_reason' => 'NOT_AS_DESCRIBED', 'images' => [], ]); ``` ### Get after-sale eligibility for an order ```php // Get after-sale eligibility for an order $eligibility = $client->ReturnRefund->getAftersaleEligibility('ORDER_ID'); ``` ``` -------------------------------- ### Fulfillment Resource Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Handles the full post-purchase flow: package creation, shipping info updates, shipment marking, tracking retrieval, and order splitting/combining. ```APIDOC ## Fulfillment Resource — Shipping & Package Management `$client->Fulfillment` handles the full post-purchase flow: package creation, shipping info updates, shipment marking, tracking retrieval, and order splitting/combining. ### Search packages awaiting shipment ```php // Search packages awaiting shipment $packages = $client->Fulfillment->searchPackage( ['page_size' => 20], ['status' => 'AWAITING_SHIPMENT'] ); ``` ### Get package shipping document (label) ```php // Get package shipping document (label) $label = $client->Fulfillment->getPackageShippingDocument( 'PACKAGE_ID', 'SHIPPING_LABEL', // document_type 0 // document_size (0 = default) ); ``` ### Ship a package via pickup ```php // Ship a package via pickup $client->Fulfillment->shipPackage( 'PACKAGE_ID', 'PICKUP', ['pickup_timeslot' => ['start_time' => 1700000000, 'end_time' => 1700003600, 'timezone' => 'UTC']] ); ``` ### Update tracking number (self-ship) ```php // Update tracking number (self-ship) $client->Fulfillment->updatePackageShippingInfo( 'PACKAGE_ID', 'TRACKING_1234567890', 'SHIPPING_PROVIDER_ID' ); ``` ### Get order tracking info ```php // Get order tracking info $tracking = $client->Fulfillment->getTracking('ORDER_ID'); ``` ### Mark an order as shipped (manual) ```php // Mark an order as shipped (manual) $client->Fulfillment->markPackageAsShipped( 'ORDER_ID', 'TRACKING_1234567890', 'SHIPPING_PROVIDER_ID', ['LINE_ITEM_ID_1', 'LINE_ITEM_ID_2'] ); ``` ### Split an order ```php // Split an order $splitAttrs = $client->Fulfillment->getOrderSplitAttributes(['ORDER_ID_1']); $client->Fulfillment->splitOrders('ORDER_ID_1', $splitAttrs['splittable_groups']); ``` ### Batch ship packages ```php // Batch ship packages $client->Fulfillment->batchShipPackages([ ['id' => 'PACKAGE_ID_1', 'handover_method' => 'PICKUP'], ['id' => 'PACKAGE_ID_2', 'handover_method' => 'DROP_OFF'], ]); ``` ``` -------------------------------- ### Product Resource - Catalog Management Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Manage the full product lifecycle including creation, retrieval, updates, deletion, activation/deactivation, image uploads, category lookups, and inventory management. ```APIDOC ## Product Resource — Catalog Management `$client->Product` covers the full product lifecycle: create, read, update, delete, activate/deactivate, image/file upload, category lookup, and inventory management. It inherits global-product methods from `GlobalProduct` and adds locale-shop specific endpoints. ### Search Products Searches for products with specified filters. ```php $result = $client->Product->searchProducts([ 'page_size' => 20, 'page_token' => '', 'status' => 'ACTIVE', ]); // $result['products'] => array of product summaries // $result['next_page_token'] => cursor for next page ``` ### Get Product Details Retrieves the full details for a specific product. ```php $product = $client->Product->getProduct('7123456789012345678'); ``` ### Create Product Creates a new product with specified details. ```php $newProduct = $client->Product->createProduct([ 'title' => 'Wireless Earbuds Pro', 'description' => 'High quality wireless earbuds.', 'category_id' => '600001', 'brand_id' => '7001234567890', 'main_images' => [['uri' => 'tos-alisg-i-abc123/image.jpg']], 'skus' => [[ 'price' => ['amount' => '29.99', 'currency' => 'USD'], 'stock_infos' => [['warehouse_id' => 'WAREHOUSE_ID', 'available_stock' => 100]], ]], 'package_weight' => ['value' => '0.5', 'unit' => 'KILOGRAM'], ]); ``` ### Update Inventory Updates the inventory for a specific product. ```php $client->Product->updateInventory('7123456789012345678', [ 'skus' => [[ 'id' => 'SKU_ID', 'stock_infos' => [['warehouse_id' => 'WAREHOUSE_ID', 'available_stock' => 50]], ]], ]); ``` ### Activate Products Activates a list of products. ```php $client->Product->activateProducts(['7111111111111111111', '7222222222222222222']); ``` ### Deactivate Products Deactivates a list of products. ```php $client->Product->deactivateProducts(['7333333333333333333']); ``` ### Delete Products Deletes a list of products. ```php $client->Product->deleteProducts(['7444444444444444444']); ``` ### Upload Product Image Uploads a product image and returns its URI. ```php $uploadResult = $client->Product->uploadProductImage('/path/to/image.jpg', 'MAIN_IMAGE'); echo $uploadResult['uri']; // e.g. "tos-alisg-i-abc123/image.jpg" ``` ### Get Categories Retrieves a list of categories for a given locale. ```php $categories = $client->Product->getCategories(['locale' => 'en-US']); ``` ### Recommend Category Recommends a category based on product title, description, and images. ```php $recommended = $client->Product->recommendCategory( 'Wireless Earbuds Pro', 'Bluetooth 5.3 earbuds with noise cancellation', [['uri' => 'tos-alisg-i-abc123/image.jpg']] ); ``` ### Check Listing Prerequisites (Specific Version) Checks listing prerequisites using a specific API version. ```php $prerequisites = $client->Product->useVersion('202312')->checkListingPrerequisites(); ``` ``` -------------------------------- ### Methods Pinned to Minimum API Versions Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Some methods automatically use a minimum API version, ensuring compatibility with features available in newer versions. Check the documentation for specific method version requirements. ```php // Order::addExternalOrderReferences() -> pinned to 202406 // Order::getPriceDetail() -> pinned to 202407 // Analytics (all methods) -> minimum 202405 // FulfilledByTiktok (all methods) -> minimum 202408 // AffiliateSeller::searchSampleApplications() -> minimum 202409 ``` -------------------------------- ### List and Manage Buyer Conversations Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Access and respond to buyer support conversations. Includes listing conversations, retrieving messages, sending text/image messages, and marking as read. ```php // List all conversations $conversations = $client->CustomerService->getConversations(['page_size' => 20]); // Get messages in a conversation $messages = $client->CustomerService->getConversationMessages('CONVERSATION_ID', [ 'page_size' => 20, 'next_page_token' => '', ]); // Send a text message to a buyer $client->CustomerService->sendMessage( 'CONVERSATION_ID', 'TEXT', 'Thank you for your order! It will ship within 24 hours.' ); // Send an image message (upload first) $uploadResult = $client->CustomerService->uploadBuyerMessagesImage('/path/to/image.jpg'); $client->CustomerService->sendMessage( 'CONVERSATION_ID', 'IMAGE', json_encode(['url' => $uploadResult['url']]) ); // Mark conversation as read $client->CustomerService->readMessage('CONVERSATION_ID'); // Create a new conversation with a buyer $newConversation = $client->CustomerService->createConversation('BUYER_USER_ID'); ``` -------------------------------- ### List Global Warehouses for Cross-Border Sellers Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Retrieve a list of global warehouses specifically for sellers operating cross-border. ```php // For cross-border sellers: list global warehouses $globalWarehouses = $client->Logistic->getGlobalSellerWarehouse(); ``` -------------------------------- ### Manage Global Products with TikTok Shop API Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Utilize the GlobalProduct resource for managing cross-border catalog entries that can be published to multiple regional shops from a single listing. This includes creating, publishing, searching, and updating inventory for global products. ```php // Create a global product $global = $client->GlobalProduct->createGlobalProduct([ 'title' => 'Global Wireless Earbuds', 'category_id' => 'GLOBAL_CATEGORY_ID', 'skus' => [['price' => ['amount' => '25.00', 'currency' => 'USD']]], ]); $globalProductId = $global['global_product_id']; // Publish global product to a regional shop $client->GlobalProduct->publishGlobalProduct($globalProductId, [ 'shop_region' => 'US', ]); // Search global products $results = $client->GlobalProduct->searchGlobalProducts( ['title' => 'Earbuds'], 20, // page_size '' // page_token ); // Update global inventory $client->GlobalProduct->updateGlobalInventory($globalProductId, [ 'skus' => [['id' => 'GLOBAL_SKU_ID', 'stock_infos' => [['warehouse_id' => 'WH_ID', 'available_stock' => 200]]]], ]); ``` -------------------------------- ### Error Handling with Exceptions Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt This section details how to handle various exceptions thrown by the TikTok Shop PHP SDK, including token-related errors, general API response errors, and network failures. ```APIDOC ## Error Handling All resource calls throw typed exceptions from `EcomPHP\TiktokShop\Errors`. Token errors (error group `105`, `360`) throw `TokenException`; all other API errors throw `ResponseException`. Network-level failures throw `ResponseException` wrapping a Guzzle exception. ### Handling Token Expiration Catch `TokenException` to detect expired or invalid access tokens and refresh them. ```php use EcomPHP\TiktokShop\Errors\TokenException; use EcomPHP\TiktokShop\Errors\ResponseException; use EcomPHP\TiktokShop\Errors\AuthorizationException; use EcomPHP\TiktokShop\Errors\TiktokShopException; try { $orders = $client->Order->getOrderList(['page_size' => 50]); } catch (TokenException $e) { // Access token expired or invalid — refresh it $newToken = $auth->refreshNewToken($storedRefreshToken); $client->setAccessToken($newToken['access_token']); // Retry the call... } catch (ResponseException $e) { echo "API error [{$e->getCode()}]: " . $e->getMessage() . "\n"; } catch (TiktokShopException $e) { echo "SDK error: " . $e->getMessage() . "\n"; } ``` ### Handling General API and Network Errors Catch `ResponseException` for general API errors or network-level failures. ```php // ... (previous catch blocks) catch (ResponseException $e) { echo "API error [{$e->getCode()}]: " . $e->getMessage() . "\n"; } // ... ``` ### Inspecting Last Response Metadata After making a resource call, you can inspect metadata from the last request. ```php // Inspect last response metadata on any resource $resource = $client->Order; $resource->getOrderList(['page_size' => 10]); echo "Request ID: " . $resource->getLastRequestId() . "\n"; echo "Message: " . $resource->getLastMessage() . "\n"; ``` ``` -------------------------------- ### AffiliateSeller Resource Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Manages collaborations with content creators, sample programs, and affiliate order tracking. Requires API version 202405 or higher. ```APIDOC ## AffiliateSeller Resource — Creator Collaborations & Affiliate Orders `$client->AffiliateSeller` manages open and target collaborations with content creators, sample programs, and affiliate order tracking. Requires API version `202405` or higher. ### Create Open Collaboration Creates an open collaboration for a product. ```php $client->AffiliateSeller->createOpenCollaboration( 'PRODUCT_ID', 0.1, // commission_rate (10%) false // require_seller_approve_creator ); ``` ### Search Creators on Marketplace Searches creators on the marketplace. Requires API version 202406 or higher. ```php $client->AffiliateSeller->searchCreatorOnMarketplace( ['page_size' => 12], ['category_ids' => ['CATEGORY_ID'], 'min_followers' => 10000] ); ``` ### Get Creator Performance Retrieves performance statistics for a specific creator. ```php $client->AffiliateSeller->getMarketplaceCreatorPerformance('CREATOR_USER_ID'); ``` ### Search Seller Affiliate Orders Searches for affiliate orders placed by sellers. ```php $client->AffiliateSeller->searchSellerAffiliateOrders([ 'page_size' => 10, ]); ``` ### Generate Affiliate Product Promotion Link Generates a promotion link for a specific product. ```php $link = $client->AffiliateSeller->generateAffiliateProductPromotionLink('PRODUCT_ID'); echo $link['promotion_link']; ``` ### Search Sample Applications Searches for sample applications. Requires API version 202409 or higher. ```php $client->AffiliateSeller->searchSampleApplications( ['page_size' => 20], ['status' => 'PENDING_REVIEW'] ); ``` ### Review Sample Applications Reviews a sample application. Requires API version 202409 or higher. ```php $client->AffiliateSeller->reviewSampleApplications( $applications['sample_applications'][0]['id'], 'APPROVED' ); ``` ### Create Conversation with Creator Initiates a direct message conversation with a creator. Requires API version 202412 or higher. ```php $client->AffiliateSeller->createConversationWithCreator('CREATOR_ID'); ``` ### Send IM Message Sends an instant message to a creator within an existing conversation. Requires API version 202412 or higher. ```php $client->AffiliateSeller->sendImMessage( $conversation['conversation_id'], 'TEXT', 'Hi, we would love to collaborate with you on our new product!' ); ``` ``` -------------------------------- ### Analytics Resource Source: https://context7.com/ecomphp/tiktokshop-php/llms.txt Surface sales and traffic metrics for the shop, individual products, SKUs, and shoppable videos. ```APIDOC ## Analytics Resource — Shop & Product Performance `$client->Analytics` surfaces sales and traffic metrics for the shop, individual products, SKUs, and shoppable videos. Requires API version `202405` or higher. ```php // Shop-level performance metrics $shopPerf = $client->Analytics->getShopPerformance([ 'data_granularity' => 'DAY', 'start_date' => '20240101', 'end_date' => '20240131', 'metrics' => ['GMV', 'ORDERS', 'PAGE_VIEWS'], ]); // Product-level performance $productPerf = $client->Analytics->getShopProductPerformance('PRODUCT_ID', [ 'data_granularity' => 'DAY', 'start_date' => '20240101', 'end_date' => '20240131', ]); // List performance for all products $allProductPerf = $client->Analytics->getShopProductPerformanceList([ 'data_granularity' => 'DAY', 'start_date' => '20240101', 'end_date' => '20240131', 'page_size' => 20, ]); // Video performance overview $videoOverview = $client->Analytics->getShopVideoPerformanceOverview([ 'start_date' => '20240101', 'end_date' => '20240131', ]); // Per-video performance $videoPerf = $client->Analytics->getShopVideoPerformance('VIDEO_ID', [ 'start_date' => '20240101', 'end_date' => '20240131', ]); ``` ```