Order Settlements Quickstart Guide

Table of Contents

  1. Introduction
  2. Core Concepts
  3. Setting Up Your Environment
  4. Stateset API Integration
  5. TikTok Shop Integration
  6. Amazon Integration
  7. Shopify Integration
  8. Consolidating Settlement Data
  9. Reporting and Analytics
  10. Automated Reconciliation
  11. Error Handling and Logging
  12. Best Practices and Optimization

Introduction

This guide demonstrates how to use Stateset’s API to manage order settlements across multiple e-commerce platforms: TikTok Shop, Amazon, Shopify, and Stateset’s own system. By following this guide, you’ll learn how to consolidate settlement data, process it efficiently, and gain insights into your multi-channel e-commerce operations.

Core Concepts

Before diving into the implementation, let’s review some core concepts related to order settlements:

  • Settlement: A financial report that summarizes transactions over a specific period, including order revenue, fees, refunds, and adjustments.
  • Payout: The actual transfer of funds from the e-commerce platform to the seller’s bank account.
  • Reconciliation: The process of matching settlement data with actual received payments and internal order records.
  • Fees: Charges applied by e-commerce platforms for their services (e.g., referral fees, fulfillment fees).
  • Adjustments: Corrections or changes to settlement amounts due to various factors (e.g., customer claims, charge backs).

Setting Up Your Environment

  1. Sign up for Stateset at stateset.io/signup
  2. Generate an API Key in the Stateset Cloud Console
  3. Install the Stateset Node.js SDK:
npm install stateset-node
  1. Set up environment variables:
export STATESET_API_KEY=your_api_key_here
export TIKTOK_SHOP_API_KEY=your_tiktok_api_key_here
export AMAZON_SP_API_KEY=your_amazon_api_key_here
export SHOPIFY_API_KEY=your_shopify_api_key_here
  1. Initialize the Stateset client:
import { stateset } from 'stateset-node';

const client = new stateset(process.env.STATESET_API_KEY);

Stateset API Integration

First, let’s set up the core functionality using Stateset’s API:


// Create a new settlement record
async function createSettlement(platformName, settlementData) {
  const settlement = await client.settlements.create({
    platform: platformName,
    settlement_date: settlementData.settlementDate,
    payout_amount: settlementData.payoutAmount,
    currency: settlementData.currency,
    status: 'pending',
    raw_data: JSON.stringify(settlementData)
  });
  return settlement;
}

// Update a settlement record
async function updateSettlement(settlementId, updateData) {
  const updatedSettlement = await client.settlements.update(settlementId, updateData);
  return updatedSettlement;
}

// Get settlement details
async function getSettlement(settlementId) {
  const settlement = await client.settlements.get(settlementId);
  return settlement;
}

// List settlements with filtering
async function listSettlements(filters) {
  const settlements = await client.settlements.list(filters);
  return settlements;
}

TikTok Shop Integration

Now, let’s integrate TikTok Shop settlements:


async function fetchTikTokSettlements(startDate, endDate) {

  const response = await stateset.tiktokshop.settlements({
    start_date: startDate,
    end_date: endDate
  });
  
  for (const settlement of response.data.settlements) {
    await createSettlement('TikTok Shop', {
      settlementDate: settlement.settlement_date,
      payoutAmount: settlement.payout_amount,
      currency: settlement.currency
    });
  }
}

Amazon Integration

Integrate Amazon Seller Central settlements:


async function fetchAmazonSettlements(startDate, endDate) {
  const response = await stateset.amazon.reports({
    operation: 'getReportDocument',
    endpoint: 'reports',
    query: {
      reportTypes: ['GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE'],
      startDate,
      endDate
    }
  });
  
  for (const settlement of response.reportDocuments) {
    const settlementDetails = await spApi.download(settlement);
    await createSettlement('Amazon', {
      settlementDate: settlementDetails.settlementDate,
      payoutAmount: settlementDetails.totalAmount,
      currency: settlementDetails.currency
    });
  }
}

Shopify Integration

Integrate Shopify settlements:


async function fetchShopifyPayouts(startDate, endDate) {
  const payouts = await stateset.shopify.payouts.list({ date_min: startDate, date_max: endDate });
  
  for (const payout of payouts) {
    await createSettlement('Shopify', {
      settlementDate: payout.date,
      payoutAmount: payout.amount,
      currency: payout.currency
    });
  }
}

Consolidating Settlement Data

Now that we have integrations for each platform, let’s create a function to consolidate all settlement data:


async function consolidateSettlements(startDate, endDate) {
  await fetchTikTokSettlements(startDate, endDate);
  await fetchAmazonSettlements(startDate, endDate);
  await fetchShopifyPayouts(startDate, endDate);
  
  const consolidatedData = await listSettlements({
    start_date: startDate,
    end_date: endDate
  });
  
  return consolidatedData;
}

Reporting and Analytics

Create summary reports and analytics based on the consolidated data:

async function generateSettlementSummary(startDate, endDate) {
  const settlements = await consolidateSettlements(startDate, endDate);
  
  const summary = {
    totalPayout: 0,
    byCurrency: {},
    byPlatform: {}
  };
  
  for (const settlement of settlements) {
    summary.totalPayout += settlement.payout_amount;
    
    if (!summary.byCurrency[settlement.currency]) {
      summary.byCurrency[settlement.currency] = 0;
    }
    summary.byCurrency[settlement.currency] += settlement.payout_amount;
    
    if (!summary.byPlatform[settlement.platform]) {
      summary.byPlatform[settlement.platform] = 0;
    }
    summary.byPlatform[settlement.platform] += settlement.payout_amount;
  }
  
  return summary;
}

Automated Reconciliation

Implement an automated reconciliation process to match settlements with internal order data:

async function reconcileSettlements(startDate, endDate) {
  const settlements = await consolidateSettlements(startDate, endDate);
  const internalOrders = await client.orders.list({ start_date: startDate, end_date: endDate });
  
  const reconciliationResults = [];
  
  for (const settlement of settlements) {
    const matchingOrders = internalOrders.filter(order => 
      order.platform === settlement.platform &&
      order.currency === settlement.currency &&
      new Date(order.created_at) <= new Date(settlement.settlement_date)
    );
    
    const totalOrderAmount = matchingOrders.reduce((sum, order) => sum + order.total_amount, 0);
    const discrepancy = settlement.payout_amount - totalOrderAmount;
    
    reconciliationResults.push({
      settlement_id: settlement.id,
      expected_amount: totalOrderAmount,
      actual_amount: settlement.payout_amount,
      discrepancy,
      status: Math.abs(discrepancy) < 0.01 ? 'matched' : 'discrepancy_detected'
    });
  }
  
  return reconciliationResults;
}

Error Handling and Logging

Implement robust error handling and logging:

async function safeApiCall(apiFunction, ...args) {
  try {
    return await apiFunction(...args);
  } catch (error) {
    console.error(`API call failed: ${error.message}`);
    await client.logs.create({
      level: 'error',
      message: `API call to ${apiFunction.name} failed: ${error.message}`,
      stacktrace: error.stack
    });
    throw error;
  }
}

// Usage
const settlements = await safeApiCall(consolidateSettlements, startDate, endDate);