> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stateset.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Order Settlements Quickstart

> Getting started with Order Settlements

# Order Settlements Quickstart Guide

## Table of Contents

1. [Introduction](#introduction)
2. [Core Concepts](#core-concepts)
3. [Setting Up Your Environment](#setting-up-your-environment)
4. [StateSet API Integration](#StateSet-api-integration)
5. [TikTok Shop Integration](#tiktok-shop-integration)
6. [Amazon Integration](#amazon-integration)
7. [Shopify Integration](#shopify-integration)
8. [Consolidating Settlement Data](#consolidating-settlement-data)
9. [Reporting and Analytics](#reporting-and-analytics)
10. [Automated Reconciliation](#automated-reconciliation)
11. [Error Handling and Logging](#error-handling-and-logging)
12. [Best Practices and Optimization](#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.com/sign-up](https://StateSet.com/sign-up)
2. Generate an API key in the [StateSet Cloud Console](https://cloud.StateSet.com/api-keys)
3. Install the StateSet Node.js SDK:

```bash theme={null}
npm install StateSet-node
```

4. Set up environment variables:

```bash theme={null}
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
```

5. Initialize the StateSet client:

```javascript theme={null}
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:

```javascript theme={null}

// 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:

```javascript theme={null}

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:

```javascript theme={null}

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:

```javascript theme={null}

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:

```javascript theme={null}

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:

```javascript theme={null}
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:

```javascript theme={null}
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:

```javascript theme={null}
async function safeApiCall(apiFunction, ...args) {
  try {
    return await apiFunction(...args);
  } catch (error) {
    logger.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);
```
