> ## 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.

# Getting Started

> Start building on StateSet Commerce Network in minutes

<Info>
  **New to StateSet?** This guide will walk you through everything from account creation to your first transaction.
</Info>

# Getting Started with StateSet

Welcome to StateSet Commerce Network! This guide will help you get up and running quickly, whether you're building an e-commerce platform, financial application, or autonomous agent system.

## 🎯 Choose Your Path

<CardGroup cols={3}>
  <Card title="E-Commerce" icon="shopping-cart" href="#e-commerce-quickstart">
    Accept payments and manage orders
  </Card>

  <Card title="Finance" icon="chart-line" href="#finance-quickstart">
    Invoice factoring and trade finance
  </Card>

  <Card title="Developer" icon="code" href="#developer-quickstart">
    API integration and automation
  </Card>
</CardGroup>

## 📋 Prerequisites

Before you begin, make sure you have:

* A modern web browser
* Basic understanding of REST APIs
* Node.js 16+ (for SDK usage)
* A business email address

## 🚀 5-Minute Setup

<Steps>
  <Step title="Create Your Account">
    Visit [dashboard.stateset.com](https://dashboard.stateset.com) and sign up:

    1. Click "Get Started"
    2. Enter your business details
    3. Verify your email
    4. Complete KYC (takes \~2 minutes)

    <Note>
      KYC is required for mainnet access. Use testnet for immediate development.
    </Note>
  </Step>

  <Step title="Get Your API Keys">
    Once logged in, navigate to the API section:

    1. Go to Settings → API Keys
    2. Click "Create New Key"
    3. Name your key (e.g., "Development")
    4. Select permissions
    5. Copy your secret key immediately

    <Warning>
      Your secret key is shown only once. Store it securely!
    </Warning>

    ```bash theme={null}
    # Add to your .env file
    STATESET_API_KEY=sk_test_your_actual_key_here
    STATESET_WEBHOOK_SECRET=whsec_your_webhook_secret_here
    ```
  </Step>

  <Step title="Install the SDK">
    Choose your preferred language and install the SDK:

    <CodeGroup>
      ```bash Node.js theme={null}
      npm install @stateset/sdk
      ```

      ```bash Python theme={null}
      pip install stateset
      ```

      ```bash Go theme={null}
      go get github.com/stateset/stateset-go
      ```
    </CodeGroup>
  </Step>

  <Step title="Make Your First API Call">
    Test your setup with a simple balance check:

    ```javascript theme={null}
    import { StateSet } from '@stateset/sdk';

    // Replace with a structured logger (Winston, Pino, etc) in production
    const logger = console;

    const stateset = new StateSet({
      apiKey: process.env.STATESET_API_KEY
    });

    async function checkBalance() {
      const balance = await stateset.account.balance();
      logger.info('Your balance', { balance });
    }

    checkBalance();
    ```
  </Step>
</Steps>

## 💸 E-Commerce Quickstart

Build a complete payment flow in minutes:

### 1. Create a Product Catalog

```javascript theme={null}
// Create your first product
const product = await stateset.products.create({
  name: 'Premium Widget',
  price: 99.99,
  currency: 'ssusd',
  inventory: 100,
  description: 'Our best-selling widget',
  images: ['https://example.com/widget.jpg']
});
```

### 2. Accept Payments

```javascript theme={null}
// Create a checkout session
const checkout = await stateset.checkout.create({
  items: [{
    product_id: product.id,
    quantity: 2
  }],
  success_url: 'https://yoursite.com/success',
  cancel_url: 'https://yoursite.com/cancel',
  customer_email: 'customer@example.com'
});

// Redirect customer to checkout
window.location.href = checkout.url;
```

### 3. Handle Order Fulfillment

```javascript theme={null}
// Listen for successful payments
stateset.webhooks.on('checkout.completed', async (event) => {
  const order = event.data;
  
  // Create shipping label
  const shipping = await stateset.shipping.create({
    order_id: order.id,
    carrier: 'fedex',
    service: 'ground',
    address: order.shipping_address
  });
  
  // Update order status
  await stateset.orders.update(order.id, {
    status: 'shipped',
    tracking_number: shipping.tracking_number
  });
});
```

### Complete E-Commerce Example

<CodeGroup>
  ```javascript Next.js theme={null}
  // pages/api/create-checkout.js
  import { StateSet } from '@stateset/sdk';

  const stateset = new StateSet({
    apiKey: process.env.STATESET_API_KEY
  });

  export default async function handler(req, res) {
    if (req.method === 'POST') {
      const { items } = req.body;
      
      try {
        const checkout = await stateset.checkout.create({
          items,
          success_url: `${req.headers.origin}/success`,
          cancel_url: `${req.headers.origin}/cart`
        });
        
        res.status(200).json({ url: checkout.url });
      } catch (error) {
        res.status(400).json({ error: error.message });
      }
    }
  }
  ```

  ```python Flask theme={null}
  from flask import Flask, request, jsonify
  from stateset import StateSet
  import os

  app = Flask(__name__)
  stateset = StateSet(api_key=os.getenv('STATESET_API_KEY'))

  @app.route('/api/create-checkout', methods=['POST'])
  def create_checkout():
      data = request.json
      
      try:
          checkout = stateset.checkout.create(
              items=data['items'],
              success_url=f"{request.host_url}success",
              cancel_url=f"{request.host_url}cart"
          )
          
          return jsonify({'url': checkout.url})
      except Exception as e:
          return jsonify({'error': str(e)}), 400
  ```
</CodeGroup>

## 💰 Finance Quickstart

Set up invoice factoring for instant liquidity:

### 1. Connect Your Accounting System

```javascript theme={null}
// Connect QuickBooks, Xero, or upload invoices
const connection = await stateset.integrations.create({
  provider: 'quickbooks',
  credentials: {
    client_id: process.env.QB_CLIENT_ID,
    client_secret: process.env.QB_CLIENT_SECRET
  }
});

// Sync invoices automatically
const invoices = await stateset.invoices.sync({
  integration_id: connection.id,
  sync_unpaid: true
});
```

### 2. Factor an Invoice

```javascript theme={null}
// Replace with a structured logger (Winston, Pino, etc) in production
const logger = console;

// Get factoring options
const options = await stateset.finance.getFactoringOptions({
  invoice_id: 'inv_123',
  amount: '50000.00'
});

// Choose best option and factor
const factoring = await stateset.finance.factorInvoice({
invoice_id: 'inv_123',
option_id: options[0].id, // Best rate
  advance_percentage: 0.95  // 95% advance
});

logger.info('Invoice factored', { advanceAmount: factoring.advance_amount });
```

## 🤖 Developer Quickstart

Build powerful integrations with StateSet:

### WebSocket Subscriptions

```javascript theme={null}
// Replace with a structured logger (Winston, Pino, etc) in production
const logger = console;

// Real-time event streaming
const ws = stateset.subscriptions.connect();

// Subscribe to all order events
ws.subscribe('orders.*', (event) => {
  logger.info('Order event received', { type: event.type, data: event.data });
});

// Subscribe to specific payment events
ws.subscribe('payments.succeeded', async (event) => {
await processSuccessfulPayment(event.data);
});
```

### Batch Operations

```javascript theme={null}
// Batch create orders
const orders = await stateset.orders.batchCreate([
  { customer: 'cust_123', items: [...], total: 100.00 },
  { customer: 'cust_456', items: [...], total: 200.00 },
  { customer: 'cust_789', items: [...], total: 300.00 }
]);

// Batch transfer stablecoins
const transfers = await stateset.stablecoin.batchTransfer({
  transfers: [
    { to: 'address1', amount: '100.00', memo: 'Refund' },
    { to: 'address2', amount: '200.00', memo: 'Payment' },
    { to: 'address3', amount: '300.00', memo: 'Salary' }
  ]
});
```

### GraphQL API

```graphql theme={null}
# Advanced querying with GraphQL
query GetOrderAnalytics($startDate: Date!, $endDate: Date!) {
  orders(
    where: { 
      created_at: { _gte: $startDate, _lte: $endDate },
      status: "completed"
    }
  ) {
    aggregate {
      count
      sum {
        total
      }
      avg {
        total
      }
    }
    nodes {
      id
      customer {
        email
        total_spent
      }
      items {
        product {
          name
          category
        }
        quantity
        subtotal
      }
    }
  }
}
```

## 🧪 Testing Your Integration

### Use Test Mode

All API keys have test mode equivalents:

```javascript theme={null}
// Test mode - no real money moves
const testClient = new StateSet({
  apiKey: 'sk_test_...' // Test key
});

// Create test payments
const payment = await testClient.payments.create({
  amount: 100.00,
  currency: 'ssusd',
  // Use test card numbers
  source: 'card_test_success'
});
```

### Test Card Numbers

| Card Number           | Scenario           |
| --------------------- | ------------------ |
| `4242 4242 4242 4242` | Success            |
| `4000 0000 0000 0002` | Decline            |
| `4000 0000 0000 9995` | Insufficient funds |

### Webhook Testing

```javascript theme={null}
// Use ngrok for local testing
// 1. Install ngrok: brew install ngrok
// 2. Start tunnel: ngrok http 3000
// 3. Use ngrok URL for webhooks

const webhook = await stateset.webhooks.create({
  url: 'https://abc123.ngrok.io/webhooks',
  events: ['*'], // All events
  description: 'Local development'
});
```

## 🚢 Going to Production

### Pre-launch Checklist

<Tabs>
  <Tab title="Security">
    * [ ] Use environment variables for API keys
    * [ ] Implement webhook signature verification
    * [ ] Enable HTTPS on all endpoints
    * [ ] Set up error monitoring (Sentry, etc.)
    * [ ] Implement rate limiting
    * [ ] Add request/response logging
  </Tab>

  <Tab title="Performance">
    * [ ] Implement caching where appropriate
    * [ ] Use pagination for large datasets
    * [ ] Optimize database queries
    * [ ] Set up CDN for static assets
    * [ ] Enable gzip compression
    * [ ] Monitor API response times
  </Tab>

  <Tab title="Business Logic">
    * [ ] Handle all error scenarios
    * [ ] Implement retry logic
    * [ ] Set up automated testing
    * [ ] Create admin dashboards
    * [ ] Document API integrations
    * [ ] Train support team
  </Tab>
</Tabs>

### Switch to Production

```javascript theme={null}
// Update your configuration
const stateset = new StateSet({
  apiKey: process.env.STATESET_LIVE_KEY, // Live key
  network: 'mainnet',
  options: {
    timeout: 30000,
    retries: 3
  }
});

// Verify production access
const account = await stateset.account.retrieve();
// Replace with a structured logger (Winston, Pino, etc) in production
const logger = console;
logger.info('Production account', { accountId: account.id });
logger.info('Live mode', { liveMode: account.live_mode }); // Should be true
```

## 🆘 Getting Help

<CardGroup cols={2}>
  <Card title="Documentation" icon="book" href="/docs">
    Comprehensive guides and references
  </Card>

  <Card title="API Status" icon="signal" href="https://status.stateset.com">
    Check system status and uptime
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/stateset">
    Chat with developers and get help
  </Card>

  <Card title="Support" icon="headset" href="mailto:support@stateset.com">
    Contact our support team
  </Card>
</CardGroup>

## 🎉 Next Steps

Now that you're set up, explore these resources:

* [Build a complete e-commerce site](/tutorials/ecommerce)
* [Implement invoice factoring](/tutorials/invoice-factoring)
* [Deploy AI agents](/tutorials/ai-agents)
* [Integrate with existing systems](/guides/integrations)

***

**Ready to build?** You now have everything needed to start building on StateSet. If you have questions, our community is here to help!

<Card title="Join our Discord" icon="discord" href="https://discord.gg/stateset">
  Connect with thousands of developers building the future of commerce
</Card>
