# Stripe Node.js Library

The official Stripe Node.js library provides comprehensive access to Stripe's REST API with full TypeScript support. This library handles payments, subscriptions, customer management, and all other Stripe functionality through a well-organized, namespaced API structure.

## Package Information

- **Package Name**: stripe
- **Package Type**: npm
- **Language**: TypeScript/JavaScript
- **Installation**: `npm install stripe`

## Core Imports

```typescript
import Stripe from 'stripe';
```

For named import:

```typescript
import { Stripe } from 'stripe';
```

For CommonJS:

```javascript
const Stripe = require('stripe');
```

## Basic Usage

```typescript
import Stripe from 'stripe';

const stripe = new Stripe('sk_test_...', {
  apiVersion: '2025-08-27.basil',
  typescript: true
});
```

## Core Concepts

### Configuration

```typescript { .api }
interface StripeConfig {
  apiVersion?: '2025-08-27.basil';          // Latest API version
  typescript?: true;                        // Enable TypeScript support
  maxNetworkRetries?: number;              // Default: 1, max retries for failed requests
  httpAgent?: HttpAgent;                   // Custom HTTP agent for proxy usage
  httpClient?: HttpClient;                 // Custom HTTP client implementation
  timeout?: number;                        // Request timeout in ms (default: 80000)
  host?: string;                          // API host override
  port?: string | number;                 // API port override
  protocol?: 'http' | 'https';           // Protocol override
  telemetry?: boolean;                    // Enable/disable telemetry (default: true)
  appInfo?: AppInfo;                      // Plugin identification
  stripeAccount?: string;                 // Connect account for all requests
  stripeContext?: string;                 // Context for all requests
}

const stripe = new Stripe(apiKey, {
  apiVersion: '2025-08-27.basil',
  typescript: true,
  maxNetworkRetries: 3,
  timeout: 30000
});
```

### Request Options

```typescript { .api }
interface RequestOptions {
  apiKey?: string;                        // Override API key per request
  idempotencyKey?: string;               // Idempotency key for safe retries
  stripeAccount?: string;                // Connect account per request
  stripeContext?: string;                // Context per request  
  apiVersion?: string;                   // API version per request
  maxNetworkRetries?: number;            // Retry limit per request
  timeout?: number;                      // Timeout per request
  host?: string;                         // Host per request
}
```

## Architecture

The Stripe Node.js library is organized into namespaces and resources:

- **Core Resources**: Direct API resources accessible via `stripe.resourceName`
- **Namespaced Resources**: Organized by functional area via `stripe.namespace.resource`
- **Special Features**: Webhooks, OAuth, test helpers, and V2 API resources

### Standard Resource Methods

```typescript { .api }
// Most resources follow standard CRUD patterns:
interface StandardResource<T> {
  create(params: CreateParams, options?: RequestOptions): Promise<T>;
  retrieve(id: string, options?: RequestOptions): Promise<T>;
  update(id: string, params: UpdateParams, options?: RequestOptions): Promise<T>;
  list(params?: ListParams, options?: RequestOptions): Promise<ApiList<T>>;
  del?(id: string, options?: RequestOptions): Promise<DeletedResource>;
}

// Example usage
const customer = await stripe.customers.create({
  email: 'customer@example.com',
  name: 'John Doe'
});

const paymentIntent = await stripe.paymentIntents.create({
  amount: 2000,
  currency: 'usd',
  customer: customer.id
}, {
  idempotencyKey: 'unique-key-123'
});
```

## Major Functional Areas

### [Core Resources](./core-resources.md)

Essential payment processing and customer management resources:

```typescript { .api }
// Payment processing
const paymentIntent = await stripe.paymentIntents.create({
  amount: 2000,
  currency: 'usd',
  payment_method: 'pm_card_visa',
  confirm: true
});

// Customer management
const customer = await stripe.customers.create({
  email: 'customer@example.com',
  payment_method: 'pm_card_visa'
});

// Charges and refunds
const charge = await stripe.charges.create({
  amount: 2000,
  currency: 'usd',
  source: 'tok_visa'
});
```

### [Subscriptions](./subscriptions.md)

Complete subscription lifecycle management:

```typescript { .api }
// Create subscription
const subscription = await stripe.subscriptions.create({
  customer: 'cus_123',
  items: [{
    price: 'price_123',
    quantity: 1
  }],
  payment_behavior: 'default_incomplete',
  expand: ['latest_invoice.payment_intent']
});

// Manage subscription items
const subscriptionItem = await stripe.subscriptionItems.create({
  subscription: subscription.id,
  price: 'price_456'
});
```

### [Billing](./billing.md)

Advanced billing features including usage metering and credit management:

```typescript { .api }
// Usage metering
const meterEvent = await stripe.billing.meterEvents.create({
  event_name: 'api_request',
  payload: {
    stripe_customer_id: 'cus_123',
    value: '1'
  }
});

// Credit grants
const creditGrant = await stripe.billing.creditGrants.create({
  customer: 'cus_123',
  amount: {
    monetary: {
      value: 1000,
      currency: 'usd'
    }
  }
});
```

### [Issuing](./issuing.md)

Card issuing and transaction management:

```typescript { .api }
// Create cardholder
const cardholder = await stripe.issuing.cardholders.create({
  name: 'John Doe',
  email: 'john.doe@example.com',
  phone_number: '+15551234567',
  type: 'individual'
});

// Issue card
const card = await stripe.issuing.cards.create({
  cardholder: cardholder.id,
  currency: 'usd',
  type: 'virtual'
});
```

### [Treasury](./treasury.md)

Financial account management and money movement:

```typescript { .api }
// Create financial account
const financialAccount = await stripe.treasury.financialAccounts.create({
  supported_currencies: ['usd'],
  features: {
    card_issuing: { requested: true },
    deposit_insurance: { requested: true }
  }
});

// Create outbound transfer
const transfer = await stripe.treasury.outboundTransfers.create({
  financial_account: financialAccount.id,
  destination_payment_method: 'pm_123',
  amount: 10000,
  currency: 'usd'
});
```

### [Terminal](./terminal.md)

In-person payment processing:

```typescript { .api }
// Create reader
const reader = await stripe.terminal.readers.create({
  registration_code: 'simulated-wpe',
  label: 'Blue Rabbit',
  location: 'tml_loc_123'
});

// Process payment
const paymentIntent = await stripe.terminal.readers.processPaymentIntent(
  reader.id,
  {
    payment_intent: 'pi_123'
  }
);
```

### [Webhooks](./webhooks.md)

Event handling and webhook management:

```typescript { .api }
// Verify webhook signature
const event = stripe.webhooks.constructEvent(
  payload,
  signature,
  endpointSecret
);

// Handle events
switch (event.type) {
  case 'payment_intent.succeeded':
    const paymentIntent = event.data.object;
    console.log('Payment succeeded:', paymentIntent.id);
    break;
  default:
    console.log('Unhandled event type:', event.type);
}
```

### [Checkout](./checkout.md)

Hosted payment pages and complete checkout flows:

```typescript { .api }
// Create checkout session
const session = await stripe.checkout.sessions.create({
  mode: 'payment',
  line_items: [
    {
      price: 'price_123',
      quantity: 1
    }
  ],
  success_url: 'https://example.com/success',
  cancel_url: 'https://example.com/cancel'
});
```

### [Tax](./tax.md)

Comprehensive tax calculation and compliance:

```typescript { .api }
// Calculate tax
const calculation = await stripe.tax.calculations.create({
  currency: 'usd',
  line_items: [
    {
      amount: 1000,
      reference: 'item_1'
    }
  ],
  customer_details: {
    address: {
      country: 'US',
      state: 'CA',
      postal_code: '94105'
    },
    address_source: 'billing'
  }
});
```

### [Identity](./identity.md)

Identity verification and KYC compliance:

```typescript { .api }
// Create verification session
const verification = await stripe.identity.verificationSessions.create({
  type: 'document',
  options: {
    document: {
      allowed_types: ['passport', 'driving_license'],
      require_matching_selfie: true
    }
  },
  return_url: 'https://example.com/verify/return'
});
```

### [Radar](./radar.md)

Advanced fraud prevention and risk management:

```typescript { .api }
// Create value list for fraud prevention
const blocklist = await stripe.radar.valueLists.create({
  alias: 'blocked_emails',
  name: 'Blocked Email Domains',
  item_type: 'email'
});

// Add item to blocklist
await stripe.radar.valueListItems.create({
  value_list: blocklist.id,
  value: 'suspicious@example.com'
});
```

### [Configuration](./configuration.md)

Advanced configuration options, error handling, and authentication:

```typescript { .api }
// Error handling
try {
  const payment = await stripe.paymentIntents.create(params);
} catch (err) {
  if (err instanceof stripe.errors.StripeCardError) {
    console.log('Card error:', err.decline_code);
  } else if (err instanceof stripe.errors.StripeInvalidRequestError) {
    console.log('Invalid parameters:', err.param);
  }
}
```

## Quick Start Example

```typescript { .api }
import Stripe from 'stripe';

const stripe = new Stripe('sk_test_...', {
  apiVersion: '2025-08-27.basil',
  typescript: true
});

// Complete payment flow
async function processPayment() {
  try {
    // Create customer
    const customer = await stripe.customers.create({
      email: 'customer@example.com'
    });

    // Create payment intent
    const paymentIntent = await stripe.paymentIntents.create({
      amount: 2000,
      currency: 'usd',
      customer: customer.id,
      payment_method_types: ['card']
    });

    // Confirm payment (in real scenario, this happens on frontend)
    const confirmedPayment = await stripe.paymentIntents.confirm(
      paymentIntent.id,
      {
        payment_method: 'pm_card_visa'
      }
    );

    console.log('Payment successful:', confirmedPayment.status);
    return confirmedPayment;
  } catch (error) {
    console.error('Payment failed:', error);
    throw error;
  }
}
```

## Response Types and Pagination

```typescript { .api }
// API List with auto-pagination
interface ApiList<T> {
  object: 'list';
  data: Array<T>;
  has_more: boolean;
  url: string;
}

// Auto-pagination methods
const customers = stripe.customers.list({ limit: 10 });

// Iterate through all customers
for await (const customer of customers) {
  console.log(customer.email);
}

// Convert to array with limit
const customerArray = await customers.autoPagingToArray({ limit: 100 });

// Process each item with callback
await customers.autoPagingEach(async (customer) => {
  await processCustomer(customer);
});
```

## Event Monitoring

```typescript { .api }
// Monitor requests and responses
stripe.on('request', (event) => {
  console.log('Request:', {
    method: event.method,
    url: event.url,
    requestId: event.request_id
  });
});

stripe.on('response', (event) => {
  console.log('Response:', {
    status: event.status_code,
    requestId: event.request_id,
    elapsed: event.elapsed
  });
});
```

This library provides access to 127+ API resources across multiple namespaces, with comprehensive TypeScript support and extensive error handling capabilities. Key capabilities include payment processing, subscription management, hosted checkout, tax calculation, identity verification, fraud prevention, card issuing, treasury management, terminal payments, and advanced webhooks. Each functional area has specialized methods beyond the standard CRUD operations to support domain-specific workflows.