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

# Pay Invoice

> Pay an invoice using ssUSD stablecoin on the StateSet Commerce Network

### Overview

This endpoint processes ssUSD (StateSet USD) stablecoin payments for invoices. Supports instant settlement, partial payments, and automated reconciliation.

### Body

<ParamField body="invoice_id" type="string" required>
  The unique identifier of the invoice to be paid
</ParamField>

<ParamField body="payment_method" type="object" required>
  Payment method details

  <Expandable title="properties">
    <ParamField body="type" type="string" required>
      Payment type. Supported values: "ssusd", "usdc" (legacy)
    </ParamField>

    <ParamField body="wallet_address" type="string" required>
      The payer's wallet address
    </ParamField>

    <ParamField body="amount" type="object" required>
      Payment amount

      <Expandable title="properties">
        <ParamField body="value" type="string" required>
          Amount to pay (can be partial payment)
        </ParamField>

        <ParamField body="denom" type="string" required>
          Denomination: "ssusd" or "usdc" (legacy)
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="chain" type="string">
      Blockchain for payment: "stateset" (default), "base", "solana", "cosmos"
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="payment_details" type="object">
  Additional payment details

  <Expandable title="properties">
    <ParamField body="full_payment" type="boolean">
      Whether this is intended as full payment (true) or partial (false)
    </ParamField>

    <ParamField body="early_payment_discount" type="boolean">
      Apply early payment discount if eligible
    </ParamField>

    <ParamField body="reference" type="string">
      Payment reference number
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="metadata" type="object">
  Additional metadata

  <Expandable title="properties">
    <ParamField body="memo" type="string">
      Payment memo
    </ParamField>

    <ParamField body="idempotency_key" type="string">
      Unique key to prevent duplicate payments
    </ParamField>

    <ParamField body="accounting_code" type="string">
      Accounting code for reconciliation
    </ParamField>
  </Expandable>
</ParamField>

### Response

<ResponseField name="success" type="boolean">
  Whether the payment was successful
</ResponseField>

<ResponseField name="transaction" type="object">
  Blockchain transaction details

  <Expandable title="properties">
    <ResponseField name="tx_hash" type="string">
      Transaction hash
    </ResponseField>

    <ResponseField name="block_height" type="number">
      Block height
    </ResponseField>

    <ResponseField name="timestamp" type="string">
      Transaction timestamp
    </ResponseField>

    <ResponseField name="gas_used" type="string">
      Gas consumed
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="payment" type="object">
  Payment details

  <Expandable title="properties">
    <ResponseField name="payment_id" type="string">
      Unique payment identifier
    </ResponseField>

    <ResponseField name="invoice_id" type="string">
      Invoice that was paid
    </ResponseField>

    <ResponseField name="amount_paid" type="object">
      Amount paid in this transaction
    </ResponseField>

    <ResponseField name="discount_applied" type="object">
      Any discounts applied
    </ResponseField>

    <ResponseField name="status" type="string">
      Payment status
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="invoice" type="object">
  Updated invoice details

  <Expandable title="properties">
    <ResponseField name="invoice_id" type="string">
      Invoice identifier
    </ResponseField>

    <ResponseField name="status" type="string">
      Invoice status: "paid", "partially\_paid", "unpaid"
    </ResponseField>

    <ResponseField name="total_amount" type="object">
      Total invoice amount
    </ResponseField>

    <ResponseField name="amount_paid" type="object">
      Total amount paid to date
    </ResponseField>

    <ResponseField name="balance_due" type="object">
      Remaining balance
    </ResponseField>

    <ResponseField name="payments" type="array">
      List of all payments made
    </ResponseField>
  </Expandable>
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl --location --request POST 'https://api.stateset.network/v1/invoice/pay' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "invoice_id": "inv_1234567890",
    "payment_method": {
      "type": "ssusd",
      "wallet_address": "stateset1qypqxpq9qcrsszg2pvxq6rs0zqg3yyc5lzv7xu",
      "amount": {
        "value": "5000.00",
        "denom": "ssusd"
      },
      "chain": "stateset"
    },
    "payment_details": {
      "full_payment": true,
      "early_payment_discount": true,
      "reference": "PMT-2024-001"
    },
    "metadata": {
      "memo": "Invoice payment for January services",
      "idempotency_key": "pay_inv_1234567890_001",
      "accounting_code": "REV-001"
    }
  }'
  ```

  ```javascript Node.js theme={null}
  const axios = require('axios');

  async function payInvoiceWithSSUSD(invoiceId, amount, walletAddress, isFullPayment = true) {
    try {
      const response = await axios.post(
        'https://api.stateset.network/v1/invoice/pay',
        {
          invoice_id: invoiceId,
          payment_method: {
            type: 'ssusd',
            wallet_address: walletAddress,
            amount: {
              value: amount,
              denom: 'ssusd'
            },
            chain: 'stateset'
          },
          payment_details: {
            full_payment: isFullPayment,
            early_payment_discount: true,
            reference: `PMT-${Date.now()}`
          },
          metadata: {
            memo: `Payment for invoice ${invoiceId}`,
            idempotency_key: `pay_inv_${invoiceId}_${Date.now()}`
          }
        },
        {
          headers: {
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json'
          }
        }
      );

      console.log('Invoice payment successful:', response.data);
      
      // Check if invoice is fully paid
      if (response.data.invoice.status === 'paid') {
        console.log('Invoice fully paid!');
      } else if (response.data.invoice.status === 'partially_paid') {
        console.log(`Partial payment applied. Balance due: ${response.data.invoice.balance_due.value} ${response.data.invoice.balance_due.denom}`);
      }
      
      return response.data;
    } catch (error) {
      console.error('Invoice payment failed:', error.response?.data || error.message);
      throw error;
    }
  }

  // Example: Partial payment
  async function makePartialPayment(invoiceId, partialAmount, walletAddress) {
    return payInvoiceWithSSUSD(invoiceId, partialAmount, walletAddress, false);
  }
  ```

  ```python Python theme={null}
  import requests
  from datetime import datetime

  def pay_invoice_with_ssusd(invoice_id, amount, wallet_address, full_payment=True):
      """Pay an invoice using ssUSD stablecoin"""
      url = "https://api.stateset.network/v1/invoice/pay"
      
      headers = {
          "Authorization": "Bearer YOUR_API_KEY",
          "Content-Type": "application/json"
      }
      
      payload = {
          "invoice_id": invoice_id,
          "payment_method": {
              "type": "ssusd",
              "wallet_address": wallet_address,
              "amount": {
                  "value": str(amount),
                  "denom": "ssusd"
              },
              "chain": "stateset"
          },
          "payment_details": {
              "full_payment": full_payment,
              "early_payment_discount": True,
              "reference": f"PMT-{datetime.now().strftime('%Y%m%d%H%M%S')}"
          },
          "metadata": {
              "memo": f"Payment for invoice {invoice_id}",
              "idempotency_key": f"pay_inv_{invoice_id}_{int(datetime.now().timestamp())}"
          }
      }
      
      try:
          response = requests.post(url, json=payload, headers=headers)
          response.raise_for_status()
          
          result = response.json()
          print(f"Payment successful! Transaction: {result['transaction']['tx_hash']}")
          
          # Check payment status
          invoice_status = result['invoice']['status']
          if invoice_status == 'paid':
              print("Invoice fully paid!")
          elif invoice_status == 'partially_paid':
              balance = result['invoice']['balance_due']
              print(f"Partial payment applied. Balance due: {balance['value']} {balance['denom']}")
              
          return result
      except requests.exceptions.RequestException as e:
          print(f"Invoice payment failed: {e}")
          if hasattr(e, 'response') and e.response:
              print(f"Error details: {e.response.json()}")
          raise

  # Example: Apply early payment discount
  def pay_invoice_with_discount(invoice_id, wallet_address):
      """Pay invoice in full to get early payment discount"""
      
      # First, get invoice details to see discount terms
      # Then pay the discounted amount
      
      return pay_invoice_with_ssusd(
          invoice_id=invoice_id,
          amount="4750.00",  # Example: 5% discount on $5000
          wallet_address=wallet_address,
          full_payment=True
      )
  ```
</RequestExample>

<ResponseExample>
  ```json Full Payment Response theme={null}
  {
    "success": true,
    "transaction": {
      "tx_hash": "E8F1B4C7D0A3E6F9C2B5E8F1D4C7A0B3E6F9C2B5",
      "block_height": 1234568,
      "timestamp": "2024-01-15T11:00:00Z",
      "gas_used": "80000"
    },
    "payment": {
      "payment_id": "pmt_abc123def456",
      "invoice_id": "inv_1234567890",
      "amount_paid": {
        "value": "4750.00",
        "denom": "ssusd",
        "usd_value": "4750.00"
      },
      "discount_applied": {
        "type": "early_payment",
        "amount": "250.00",
        "percentage": "5.0"
      },
      "status": "completed"
    },
    "invoice": {
      "invoice_id": "inv_1234567890",
      "status": "paid",
      "total_amount": {
        "value": "5000.00",
        "denom": "ssusd"
      },
      "amount_paid": {
        "value": "4750.00",
        "denom": "ssusd"
      },
      "balance_due": {
        "value": "0.00",
        "denom": "ssusd"
      },
      "payments": [
        {
          "payment_id": "pmt_abc123def456",
          "amount": "4750.00",
          "paid_at": "2024-01-15T11:00:00Z",
          "discount": "250.00"
        }
      ]
    }
  }
  ```

  ```json Partial Payment Response theme={null}
  {
    "success": true,
    "transaction": {
      "tx_hash": "F9G2C5D8E1B4F7A0D3F6G9C2E5B8F1D4",
      "block_height": 1234569,
      "timestamp": "2024-01-15T11:05:00Z",
      "gas_used": "75000"
    },
    "payment": {
      "payment_id": "pmt_xyz789uvw012",
      "invoice_id": "inv_1234567890",
      "amount_paid": {
        "value": "2000.00",
        "denom": "ssusd",
        "usd_value": "2000.00"
      },
      "discount_applied": null,
      "status": "completed"
    },
    "invoice": {
      "invoice_id": "inv_1234567890",
      "status": "partially_paid",
      "total_amount": {
        "value": "5000.00",
        "denom": "ssusd"
      },
      "amount_paid": {
        "value": "2000.00",
        "denom": "ssusd"
      },
      "balance_due": {
        "value": "3000.00",
        "denom": "ssusd"
      },
      "payments": [
        {
          "payment_id": "pmt_xyz789uvw012",
          "amount": "2000.00",
          "paid_at": "2024-01-15T11:05:00Z",
          "discount": "0.00"
        }
      ]
    }
  }
  ```
</ResponseExample>
