# Treasury

Stripe Treasury enables platforms to offer embedded financial services including bank-like accounts, money movement, and financial management tools. This comprehensive financial infrastructure supports everything from simple balance management to complex multi-party financial workflows.

## Financial Accounts

### Treasury.FinancialAccounts

Create and manage financial accounts with banking capabilities:

```typescript { .api }
interface TreasuryFinancialAccount {
  id: string;
  object: 'treasury.financial_account';
  supported_currencies: string[];
  features: {
    card_issuing?: { requested: boolean; status: 'active' | 'pending' | 'restricted' };
    deposit_insurance?: { requested: boolean; status: 'active' | 'pending' | 'restricted' };
    financial_addresses?: { 
      aba?: { requested: boolean; status: 'active' | 'pending' | 'restricted' };
    };
    inbound_transfers?: {
      ach?: { requested: boolean; status: 'active' | 'pending' | 'restricted' };
    };
    intra_stripe_flows?: { requested: boolean; status: 'active' | 'pending' | 'restricted' };
    outbound_payments?: {
      ach?: { requested: boolean; status: 'active' | 'pending' | 'restricted' };
      us_domestic_wire?: { requested: boolean; status: 'active' | 'pending' | 'restricted' };
    };
    outbound_transfers?: {
      ach?: { requested: boolean; status: 'active' | 'pending' | 'restricted' };
      us_domestic_wire?: { requested: boolean; status: 'active' | 'pending' | 'restricted' };
    };
  };
  balance: {
    [currency: string]: {
      available: number;
      pending: number;
    };
  };
  financial_addresses: FinancialAddress[];
  status: 'open' | 'closed';
}

// Create financial account with basic features
const financialAccount = await stripe.treasury.financialAccounts.create({
  supported_currencies: ['usd'],
  features: {
    card_issuing: { requested: true },
    deposit_insurance: { requested: true },
    financial_addresses: {
      aba: { requested: true }
    },
    inbound_transfers: {
      ach: { requested: true }
    },
    outbound_transfers: {
      ach: { requested: true },
      us_domestic_wire: { requested: true }
    }
  }
});

// Create financial account for marketplace
const marketplaceAccount = await stripe.treasury.financialAccounts.create({
  supported_currencies: ['usd', 'eur'],
  features: {
    card_issuing: { requested: true },
    deposit_insurance: { requested: true },
    intra_stripe_flows: { requested: true },
    outbound_payments: {
      ach: { requested: true }
    }
  },
  metadata: {
    account_type: 'marketplace_settlement',
    business_id: 'biz_123'
  }
});

// Retrieve financial account
const retrieved = await stripe.treasury.financialAccounts.retrieve('fa_123', {
  expand: ['financial_addresses']
});

// Update financial account
const updated = await stripe.treasury.financialAccounts.update('fa_123', {
  metadata: {
    updated_features: 'added_wire_transfers',
    updated_at: new Date().toISOString()
  }
});

// List financial accounts
const accounts = await stripe.treasury.financialAccounts.list({
  limit: 10
});

// Retrieve account features
const features = await stripe.treasury.financialAccounts.retrieveFeatures('fa_123');

// Update account features
const updatedFeatures = await stripe.treasury.financialAccounts.updateFeatures(
  'fa_123',
  {
    card_issuing: { requested: false }, // Disable card issuing
    outbound_payments: {
      us_domestic_wire: { requested: true } // Enable wire payments
    }
  }
);
```

## Money Movement - Inbound

### Treasury.InboundTransfers

Handle incoming money transfers:

```typescript { .api }
interface TreasuryInboundTransfer {
  id: string;
  object: 'treasury.inbound_transfer';
  financial_account: string;
  amount: number;
  currency: string;
  status: 'processing' | 'succeeded' | 'failed' | 'canceled';
  origin_payment_method: string;
  origin_payment_method_details?: {
    type: 'us_bank_account';
    us_bank_account?: {
      account_holder_type?: 'individual' | 'company';
      account_type?: 'checking' | 'savings';
      bank_name?: string;
      fingerprint?: string;
      last4?: string;
      routing_number?: string;
    };
  };
  failure_details?: {
    code?: string;
    description?: string;
  };
}

// Create inbound transfer from bank account
const inboundTransfer = await stripe.treasury.inboundTransfers.create({
  financial_account: 'fa_123',
  amount: 10000, // $100.00
  currency: 'usd',
  origin_payment_method: 'pm_bank_account_123',
  description: 'Initial funding from business bank account'
});

// Create inbound transfer with metadata
const fundingTransfer = await stripe.treasury.inboundTransfers.create({
  financial_account: 'fa_456',
  amount: 50000, // $500.00
  currency: 'usd',
  origin_payment_method: 'pm_bank_account_456',
  statement_descriptor: 'ACME FUNDING',
  metadata: {
    source: 'business_bank_account',
    purpose: 'operational_funding',
    reference_id: 'funding_789'
  }
});

// Retrieve inbound transfer
const retrieved = await stripe.treasury.inboundTransfers.retrieve('ibt_123');

// List inbound transfers
const inboundTransfers = await stripe.treasury.inboundTransfers.list({
  financial_account: 'fa_123',
  limit: 20
});

// List transfers by status
const succeededTransfers = await stripe.treasury.inboundTransfers.list({
  financial_account: 'fa_123',
  status: 'succeeded'
});

// Cancel pending inbound transfer
const canceled = await stripe.treasury.inboundTransfers.cancel('ibt_123');
```

## Money Movement - Outbound

### Treasury.OutboundTransfers

Send money to external bank accounts:

```typescript { .api }
interface TreasuryOutboundTransfer {
  id: string;
  object: 'treasury.outbound_transfer';
  financial_account: string;
  amount: number;
  currency: string;
  status: 'processing' | 'posted' | 'failed' | 'canceled' | 'returned';
  destination_payment_method: string;
  destination_payment_method_details?: {
    type: 'us_bank_account';
    us_bank_account?: {
      account_holder_type?: 'individual' | 'company';
      account_type?: 'checking' | 'savings';
      bank_name?: string;
      fingerprint?: string;
      last4?: string;
      routing_number?: string;
    };
  };
  expected_arrival_date?: number;
  returned_details?: {
    code?: string;
    transaction?: string;
  };
}

// Create outbound transfer to bank account
const outboundTransfer = await stripe.treasury.outboundTransfers.create({
  financial_account: 'fa_123',
  destination_payment_method: 'pm_bank_account_external',
  amount: 25000, // $250.00
  currency: 'usd',
  description: 'Payout to supplier'
});

// Create scheduled outbound transfer
const scheduledTransfer = await stripe.treasury.outboundTransfers.create({
  financial_account: 'fa_123',
  destination_payment_method: 'pm_bank_account_payroll',
  amount: 75000, // $750.00
  currency: 'usd',
  statement_descriptor: 'ACME PAYROLL',
  metadata: {
    type: 'payroll',
    pay_period: '2024-01',
    employee_count: '5'
  }
});

// Retrieve outbound transfer
const retrieved = await stripe.treasury.outboundTransfers.retrieve('obt_123');

// List outbound transfers
const outboundTransfers = await stripe.treasury.outboundTransfers.list({
  financial_account: 'fa_123',
  limit: 20
});

// List transfers by date range
const recentTransfers = await stripe.treasury.outboundTransfers.list({
  financial_account: 'fa_123',
  created: {
    gte: Math.floor(Date.now() / 1000) - 86400 * 7 // Last 7 days
  }
});

// Cancel pending outbound transfer
const canceled = await stripe.treasury.outboundTransfers.cancel('obt_123');
```

### Treasury.OutboundPayments

Send ACH and wire payments to external accounts:

```typescript { .api }
interface TreasuryOutboundPayment {
  id: string;
  object: 'treasury.outbound_payment';
  financial_account: string;
  amount: number;
  currency: string;
  status: 'processing' | 'posted' | 'failed' | 'canceled' | 'returned';
  destination_payment_method: string;
  destination_payment_method_details?: {
    type: 'us_bank_account';
    us_bank_account?: {
      account_holder_type?: 'individual' | 'company';
      account_type?: 'checking' | 'savings';
      bank_name?: string;
      routing_number?: string;
    };
  };
  end_user_details: {
    present: boolean;
    ip_address?: string;
  };
  returned_details?: {
    code?: string;
    transaction?: string;
  };
}

// Create ACH outbound payment
const achPayment = await stripe.treasury.outboundPayments.create({
  financial_account: 'fa_123',
  amount: 15000, // $150.00
  currency: 'usd',
  destination_payment_method: 'pm_bank_account_vendor',
  description: 'Vendor payment for services',
  end_user_details: {
    present: true,
    ip_address: '192.168.1.1'
  },
  statement_descriptor: 'ACME VENDOR PAY'
});

// Create wire payment
const wirePayment = await stripe.treasury.outboundPayments.create({
  financial_account: 'fa_123',
  amount: 100000, // $1,000.00
  currency: 'usd',
  destination_payment_method: 'pm_bank_account_supplier',
  description: 'Wire payment for equipment',
  end_user_details: {
    present: false
  },
  metadata: {
    payment_type: 'wire',
    urgency: 'high',
    approval_id: 'approval_456'
  }
});

// Retrieve outbound payment
const retrieved = await stripe.treasury.outboundPayments.retrieve('obp_123');

// List outbound payments
const payments = await stripe.treasury.outboundPayments.list({
  financial_account: 'fa_123',
  limit: 20
});

// Cancel pending outbound payment
const canceled = await stripe.treasury.outboundPayments.cancel('obp_123');
```

## Money Movement - Internal

### Treasury.ReceivedCredits

Track incoming credits to financial accounts:

```typescript { .api }
interface TreasuryReceivedCredit {
  id: string;
  object: 'treasury.received_credit';
  financial_account: string;
  amount: number;
  currency: string;
  status: 'succeeded';
  network: 'ach' | 'us_domestic_wire' | 'stripe';
  description?: string;
  initiating_payment_method_details?: {
    type: string;
    us_bank_account?: {
      account_holder_type?: 'individual' | 'company';
      account_type?: 'checking' | 'savings';
      bank_name?: string;
      fingerprint?: string;
      last4?: string;
      routing_number?: string;
    };
  };
}

// Retrieve received credit
const credit = await stripe.treasury.receivedCredits.retrieve('rc_123');

// List received credits
const credits = await stripe.treasury.receivedCredits.list({
  financial_account: 'fa_123',
  limit: 20
});

// List credits by network type
const achCredits = await stripe.treasury.receivedCredits.list({
  financial_account: 'fa_123',
  network: 'ach'
});

// List credits by date range
const recentCredits = await stripe.treasury.receivedCredits.list({
  financial_account: 'fa_123',
  created: {
    gte: Math.floor(Date.now() / 1000) - 86400 * 30 // Last 30 days
  }
});
```

### Treasury.ReceivedDebits

Track outgoing debits from financial accounts:

```typescript { .api }
interface TreasuryReceivedDebit {
  id: string;
  object: 'treasury.received_debit';
  financial_account: string;
  amount: number;
  currency: string;
  status: 'succeeded';
  network: 'ach';
  description?: string;
  initiating_payment_method_details?: {
    type: string;
    us_bank_account?: {
      account_holder_type?: 'individual' | 'company';
      account_type?: 'checking' | 'savings';
      bank_name?: string;
      fingerprint?: string;
      last4?: string;
      routing_number?: string;
    };
  };
}

// Retrieve received debit
const debit = await stripe.treasury.receivedDebits.retrieve('rd_123');

// List received debits
const debits = await stripe.treasury.receivedDebits.list({
  financial_account: 'fa_123',
  limit: 20
});

// List debits by status and network
const achDebits = await stripe.treasury.receivedDebits.list({
  financial_account: 'fa_123',
  network: 'ach',
  status: 'succeeded'
});
```

## Transaction Reversals

### Treasury.CreditReversals

Reverse credit transactions:

```typescript { .api }
interface TreasuryCreditReversal {
  id: string;
  object: 'treasury.credit_reversal';
  financial_account: string;
  received_credit: string;
  amount: number;
  currency: string;
  status: 'processing' | 'succeeded' | 'failed';
  status_transitions: {
    posted_at?: number;
  };
  network: 'ach' | 'stripe';
}

// Create credit reversal
const creditReversal = await stripe.treasury.creditReversals.create({
  received_credit: 'rc_123'
});

// Create partial credit reversal
const partialReversal = await stripe.treasury.creditReversals.create({
  received_credit: 'rc_456',
  amount: 5000 // Reverse only $50 of the original credit
});

// Retrieve credit reversal
const retrieved = await stripe.treasury.creditReversals.retrieve('crev_123');

// List credit reversals
const reversals = await stripe.treasury.creditReversals.list({
  financial_account: 'fa_123',
  limit: 20
});

// List reversals by received credit
const creditReversals = await stripe.treasury.creditReversals.list({
  received_credit: 'rc_123'
});
```

### Treasury.DebitReversals

Reverse debit transactions:

```typescript { .api }
interface TreasuryDebitReversal {
  id: string;
  object: 'treasury.debit_reversal';
  financial_account: string;
  received_debit: string;
  amount: number;
  currency: string;
  status: 'processing' | 'succeeded' | 'failed';
  status_transitions: {
    completed_at?: number;
  };
  network: 'ach';
}

// Create debit reversal
const debitReversal = await stripe.treasury.debitReversals.create({
  received_debit: 'rd_123'
});

// Create partial debit reversal
const partialDebitReversal = await stripe.treasury.debitReversals.create({
  received_debit: 'rd_456',
  amount: 3000 // Reverse only $30 of the original debit
});

// Retrieve debit reversal
const retrieved = await stripe.treasury.debitReversals.retrieve('drev_123');

// List debit reversals
const reversals = await stripe.treasury.debitReversals.list({
  financial_account: 'fa_123',
  limit: 20
});
```

## Transaction Tracking

### Treasury.Transactions

Monitor all transactions in financial accounts:

```typescript { .api }
interface TreasuryTransaction {
  id: string;
  object: 'treasury.transaction';
  financial_account: string;
  amount: number;
  currency: string;
  description: string;
  status: 'open' | 'posted' | 'void';
  status_transitions: {
    posted_at?: number;
    void_at?: number;
  };
  flow_type: 'credit' | 'debit';
  flow_details: {
    type: 'inbound_transfer' | 'outbound_transfer' | 'outbound_payment' | 'received_credit' | 'received_debit' | 'credit_reversal' | 'debit_reversal' | 'other';
    inbound_transfer?: { id: string };
    outbound_transfer?: { id: string };
    outbound_payment?: { id: string };
    received_credit?: { id: string };
    received_debit?: { id: string };
    credit_reversal?: { id: string };
    debit_reversal?: { id: string };
  };
}

// Retrieve transaction
const transaction = await stripe.treasury.transactions.retrieve('trxn_123');

// List all transactions
const transactions = await stripe.treasury.transactions.list({
  financial_account: 'fa_123',
  limit: 50
});

// List transactions by flow type
const credits = await stripe.treasury.transactions.list({
  financial_account: 'fa_123',
  flow_type: 'credit'
});

const debits = await stripe.treasury.transactions.list({
  financial_account: 'fa_123',
  flow_type: 'debit'
});

// List transactions by status
const postedTransactions = await stripe.treasury.transactions.list({
  financial_account: 'fa_123',
  status: 'posted'
});

// List recent transactions
const recentTransactions = await stripe.treasury.transactions.list({
  financial_account: 'fa_123',
  created: {
    gte: Math.floor(Date.now() / 1000) - 86400 // Last 24 hours
  }
});
```

### Treasury.TransactionEntries

Detailed transaction entry records:

```typescript { .api }
interface TreasuryTransactionEntry {
  id: string;
  object: 'treasury.transaction_entry';
  financial_account: string;
  transaction: string;
  type: 'credit' | 'debit';
  amount: number;
  currency: string;
  effective_at: number;
  flow_type: string;
  flow_details: {
    type: string;
    [key: string]: any;
  };
}

// Retrieve transaction entry
const entry = await stripe.treasury.transactionEntries.retrieve('trxne_123');

// List transaction entries
const entries = await stripe.treasury.transactionEntries.list({
  financial_account: 'fa_123',
  limit: 50
});

// List entries by transaction
const transactionEntries = await stripe.treasury.transactionEntries.list({
  transaction: 'trxn_123'
});

// List entries by effective date
const todayEntries = await stripe.treasury.transactionEntries.list({
  financial_account: 'fa_123',
  effective_at: {
    gte: Math.floor(new Date().setHours(0, 0, 0, 0) / 1000)
  }
});
```

## Test Helpers

### TestHelpers.Treasury

Simulate treasury scenarios in test mode:

```typescript { .api }
// Test inbound transfer scenarios
const succeededTransfer = await stripe.testHelpers.treasury.succeed('ibt_test_123');

const failedTransfer = await stripe.testHelpers.treasury.fail('ibt_test_123', {
  failure_code: 'account_closed'
});

const returnedTransfer = await stripe.testHelpers.treasury.return('ibt_test_123', {
  failure_code: 'account_closed'
});

// Test outbound transfer scenarios
const postedOutbound = await stripe.testHelpers.treasury.post('obt_test_123');

const failedOutbound = await stripe.testHelpers.treasury.fail('obt_test_123', {
  failure_code: 'insufficient_funds'
});

const returnedOutbound = await stripe.testHelpers.treasury.return('obt_test_123', {
  failure_code: 'no_account'
});

// Test outbound payment scenarios
const postedPayment = await stripe.testHelpers.treasury.post('obp_test_123');

const failedPayment = await stripe.testHelpers.treasury.fail('obp_test_123', {
  failure_code: 'generic_decline'
});

const returnedPayment = await stripe.testHelpers.treasury.return('obp_test_123', {
  failure_code: 'credit_entry_refused_by_receiver'
});

// Create test received credits and debits
const testCredit = await stripe.testHelpers.treasury.createReceivedCredit({
  financial_account: 'fa_test_123',
  network: 'ach',
  amount: 10000,
  currency: 'usd',
  description: 'Test incoming ACH credit'
});

const testDebit = await stripe.testHelpers.treasury.createReceivedDebit({
  financial_account: 'fa_test_123',
  network: 'ach',
  amount: 5000,
  currency: 'usd',
  description: 'Test outgoing ACH debit'
});
```

## Integration Examples

### Multi-tenant Financial Accounts

```typescript { .api }
// Create separate financial accounts for marketplace participants
async function createMerchantAccount(merchantId: string) {
  const financialAccount = await stripe.treasury.financialAccounts.create({
    supported_currencies: ['usd'],
    features: {
      inbound_transfers: { ach: { requested: true } },
      outbound_transfers: { ach: { requested: true } },
      intra_stripe_flows: { requested: true }
    },
    metadata: {
      merchant_id: merchantId,
      account_type: 'merchant_settlement'
    }
  });
  
  return financialAccount;
}

// Transfer funds between accounts
async function transferToMerchant(
  sourceAccountId: string, 
  destinationAccountId: string, 
  amount: number
) {
  // First move to platform account
  const outbound = await stripe.treasury.outboundTransfers.create({
    financial_account: sourceAccountId,
    destination_payment_method: 'ba_platform_account',
    amount: amount,
    currency: 'usd'
  });
  
  // Then to merchant account
  const inbound = await stripe.treasury.inboundTransfers.create({
    financial_account: destinationAccountId,
    origin_payment_method: 'ba_platform_account',
    amount: amount,
    currency: 'usd'
  });
  
  return { outbound, inbound };
}
```

### Automated Payroll System

```typescript { .api }
// Process payroll payments
async function processPayroll(payrollData: PayrollEntry[]) {
  const results = [];
  
  for (const entry of payrollData) {
    try {
      const payment = await stripe.treasury.outboundPayments.create({
        financial_account: 'fa_payroll_account',
        amount: entry.netPay,
        currency: 'usd',
        destination_payment_method: entry.employeeBankAccount,
        description: `Payroll for ${entry.employeeName}`,
        end_user_details: {
          present: false
        },
        metadata: {
          employee_id: entry.employeeId,
          pay_period: entry.payPeriod,
          gross_pay: entry.grossPay.toString(),
          deductions: entry.deductions.toString()
        }
      });
      
      results.push({ success: true, payment, employee: entry.employeeName });
    } catch (error) {
      results.push({ success: false, error, employee: entry.employeeName });
    }
  }
  
  return results;
}
```

### Real-time Balance Monitoring

```typescript { .api }
// Monitor account balance and trigger alerts
async function monitorAccountBalance(financialAccountId: string) {
  const account = await stripe.treasury.financialAccounts.retrieve(financialAccountId);
  const balance = account.balance.usd;
  
  if (balance.available < 100000) { // Less than $1,000
    await sendLowBalanceAlert({
      accountId: financialAccountId,
      availableBalance: balance.available,
      pendingBalance: balance.pending
    });
  }
  
  // Get recent transactions for analysis
  const transactions = await stripe.treasury.transactions.list({
    financial_account: financialAccountId,
    created: {
      gte: Math.floor(Date.now() / 1000) - 86400 // Last 24 hours
    }
  });
  
  return {
    balance,
    recentTransactions: transactions.data,
    alertSent: balance.available < 100000
  };
}
```

Stripe Treasury provides a comprehensive financial infrastructure that enables platforms to offer sophisticated banking and money movement capabilities with full regulatory compliance and real-time transaction monitoring.