Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Stripe Node
https://github.com/stripe/stripe-node
Admin
The Stripe Node library provides convenient access to the Stripe API from applications written in
...
Tokens:
22,662
Snippets:
114
Trust Score:
8.9
Update:
2 weeks ago
Context
Skills
Chat
Benchmark
81.7
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Stripe Node.js Library The Stripe Node.js library provides convenient server-side access to the Stripe API for payment processing, subscription management, and financial infrastructure. This SDK enables developers to integrate Stripe's comprehensive payment platform into Node.js applications, supporting features like one-time payments, recurring subscriptions, invoicing, refunds, and webhook handling. The library is fully typed with TypeScript definitions and works across Node.js, Deno, Bun, and various serverless environments including Cloudflare Workers. The SDK follows a resource-based architecture where each Stripe API resource (customers, payments, subscriptions, etc.) is exposed as a property on the main Stripe client. All methods return Promises and support both async/await and callback patterns. The library includes built-in support for automatic retries, request telemetry, webhook signature verification, and auto-pagination for list endpoints. ## Initializing the Stripe Client The Stripe client requires your secret API key and supports various configuration options for customizing behavior including timeout, retries, and proxy settings. ```typescript import Stripe from 'stripe'; // Basic initialization const stripe = new Stripe('sk_test_your_api_key'); // With configuration options const stripeConfigured = new Stripe('sk_test_your_api_key', { apiVersion: '2026-02-25.clover', maxNetworkRetries: 2, timeout: 20000, // 20 seconds telemetry: true, appInfo: { name: 'MyApp', version: '1.0.0', url: 'https://myapp.com' } }); // Lazy initialization for build-time safety let _stripe: Stripe | null = null; const getStripe = (): Stripe => { if (!_stripe) { _stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string); } return _stripe; }; ``` ## Customers API Create, retrieve, update, list, and delete customer records. Customers store payment methods, billing information, and can be associated with subscriptions and invoices. ```typescript import Stripe from 'stripe'; const stripe = new Stripe('sk_test_your_api_key'); // Create a customer const customer = await stripe.customers.create({ email: 'customer@example.com', name: 'John Doe', description: 'Premium customer', metadata: { userId: '12345' }, address: { line1: '123 Main St', city: 'San Francisco', state: 'CA', postal_code: '94102', country: 'US' } }); console.log('Created customer:', customer.id); // Output: Created customer: cus_1234567890 // Retrieve a customer const retrieved = await stripe.customers.retrieve('cus_1234567890'); console.log('Customer email:', retrieved.email); // Update a customer const updated = await stripe.customers.update('cus_1234567890', { description: 'VIP customer', metadata: { tier: 'gold' } }); // List customers with pagination const customers = await stripe.customers.list({ limit: 10, created: { gte: Math.floor(Date.now() / 1000) - 86400 } // Last 24 hours }); for (const cust of customers.data) { console.log(cust.id, cust.email); } // Search customers const searchResults = await stripe.customers.search({ query: "email:'customer@example.com'" }); // Delete a customer const deleted = await stripe.customers.del('cus_1234567890'); console.log('Deleted:', deleted.deleted); // true ``` ## Payment Intents API Payment Intents represent the full lifecycle of a payment, handling authentication, confirmation, and capture. This is the recommended approach for accepting payments. ```typescript import Stripe from 'stripe'; const stripe = new Stripe('sk_test_your_api_key'); // Create a PaymentIntent const paymentIntent = await stripe.paymentIntents.create({ amount: 2000, // $20.00 in cents currency: 'usd', customer: 'cus_1234567890', payment_method_types: ['card'], description: 'Order #1234', metadata: { orderId: '1234' }, receipt_email: 'customer@example.com' }); console.log('PaymentIntent created:', paymentIntent.id); console.log('Client secret:', paymentIntent.client_secret); // Output: PaymentIntent created: pi_1234567890 // Client secret: pi_1234567890_secret_xyz // Retrieve a PaymentIntent const retrieved = await stripe.paymentIntents.retrieve('pi_1234567890'); console.log('Status:', retrieved.status); // Confirm a PaymentIntent (server-side) const confirmed = await stripe.paymentIntents.confirm('pi_1234567890', { payment_method: 'pm_card_visa' }); // Capture an authorized PaymentIntent (for separate auth/capture) const captured = await stripe.paymentIntents.capture('pi_1234567890', { amount_to_capture: 1500 // Partial capture of $15.00 }); // Cancel a PaymentIntent const canceled = await stripe.paymentIntents.cancel('pi_1234567890', { cancellation_reason: 'requested_by_customer' }); // Search PaymentIntents const searchResults = await stripe.paymentIntents.search({ query: "status:'succeeded' AND metadata['orderId']:'1234'" }); ``` ## Checkout Sessions API Stripe Checkout provides a pre-built, hosted payment page for one-time payments and subscriptions with minimal integration effort. ```typescript import Stripe from 'stripe'; const stripe = new Stripe('sk_test_your_api_key'); // Create a Checkout Session for one-time payment const session = await stripe.checkout.sessions.create({ mode: 'payment', customer: 'cus_1234567890', line_items: [ { price_data: { currency: 'usd', product_data: { name: 'Premium Widget', description: 'A high-quality widget', images: ['https://example.com/widget.png'] }, unit_amount: 2999 // $29.99 }, quantity: 2 } ], success_url: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url: 'https://example.com/cancel', metadata: { orderId: 'order_123' } }); console.log('Checkout URL:', session.url); // Output: Checkout URL: https://checkout.stripe.com/pay/cs_test_... // Create a Checkout Session for subscription const subscriptionSession = await stripe.checkout.sessions.create({ mode: 'subscription', customer: 'cus_1234567890', line_items: [ { price: 'price_1234567890', // Recurring price ID quantity: 1 } ], success_url: 'https://example.com/success', cancel_url: 'https://example.com/cancel' }); // Retrieve a session const retrieved = await stripe.checkout.sessions.retrieve('cs_test_123', { expand: ['line_items', 'customer'] }); // List line items for a session const lineItems = await stripe.checkout.sessions.listLineItems('cs_test_123'); // Expire a session const expired = await stripe.checkout.sessions.expire('cs_test_123'); ``` ## Products and Prices API Products represent goods or services, while Prices define the cost and billing cycle. Together they form the catalog for Checkout, Invoices, and Subscriptions. ```typescript import Stripe from 'stripe'; const stripe = new Stripe('sk_test_your_api_key'); // Create a product const product = await stripe.products.create({ name: 'Pro Plan', description: 'Full access to all features', metadata: { tier: 'pro' } }); console.log('Product created:', product.id); // Create a one-time price const oneTimePrice = await stripe.prices.create({ product: product.id, unit_amount: 9999, // $99.99 currency: 'usd' }); // Create a recurring price const recurringPrice = await stripe.prices.create({ product: product.id, unit_amount: 1999, // $19.99/month currency: 'usd', recurring: { interval: 'month', interval_count: 1 } }); console.log('Recurring price:', recurringPrice.id); // Create a metered price (usage-based billing) const meteredPrice = await stripe.prices.create({ product: product.id, currency: 'usd', recurring: { interval: 'month', usage_type: 'metered' }, unit_amount: 10 // $0.10 per unit }); // List prices for a product const prices = await stripe.prices.list({ product: product.id, active: true }); // Update a product const updated = await stripe.products.update(product.id, { name: 'Pro Plan - Updated', active: true }); // Search products const searchResults = await stripe.products.search({ query: "active:'true' AND metadata['tier']:'pro'" }); ``` ## Subscriptions API Subscriptions enable recurring billing for customers, supporting trials, proration, usage-based billing, and multiple subscription items. ```typescript import Stripe from 'stripe'; const stripe = new Stripe('sk_test_your_api_key'); // Create a subscription const subscription = await stripe.subscriptions.create({ customer: 'cus_1234567890', items: [ { price: 'price_monthly_pro' } ], payment_behavior: 'default_incomplete', payment_settings: { save_default_payment_method: 'on_subscription' }, expand: ['latest_invoice.payment_intent'] }); console.log('Subscription ID:', subscription.id); console.log('Status:', subscription.status); // Output: Subscription ID: sub_1234567890 // Output: Status: incomplete // Create a subscription with trial const trialSubscription = await stripe.subscriptions.create({ customer: 'cus_1234567890', items: [{ price: 'price_monthly_pro' }], trial_period_days: 14 }); // Retrieve a subscription const retrieved = await stripe.subscriptions.retrieve('sub_1234567890'); // Update a subscription (change plan) const updated = await stripe.subscriptions.update('sub_1234567890', { items: [ { id: subscription.items.data[0].id, price: 'price_monthly_enterprise' } ], proration_behavior: 'create_prorations' }); // Cancel a subscription const canceled = await stripe.subscriptions.cancel('sub_1234567890', { invoice_now: true, prorate: true }); // Resume a paused subscription const resumed = await stripe.subscriptions.resume('sub_1234567890', { billing_cycle_anchor: 'now' }); // Search subscriptions const searchResults = await stripe.subscriptions.search({ query: "status:'active'" }); ``` ## Invoices API Invoices enable sending itemized bills to customers, supporting automatic collection, manual sending, and custom invoice items. ```typescript import Stripe from 'stripe'; const stripe = new Stripe('sk_test_your_api_key'); // Create an invoice const invoice = await stripe.invoices.create({ customer: 'cus_1234567890', collection_method: 'send_invoice', days_until_due: 30, description: 'Consulting services for January 2024' }); // Add invoice items await stripe.invoiceItems.create({ customer: 'cus_1234567890', invoice: invoice.id, amount: 5000, // $50.00 currency: 'usd', description: 'Consulting hours (5 @ $10/hr)' }); // Finalize the invoice const finalized = await stripe.invoices.finalizeInvoice(invoice.id); console.log('Invoice number:', finalized.number); console.log('Invoice URL:', finalized.hosted_invoice_url); // Send the invoice const sent = await stripe.invoices.sendInvoice(invoice.id); // Pay an invoice const paid = await stripe.invoices.pay(invoice.id, { payment_method: 'pm_card_visa' }); // Create an invoice preview const preview = await stripe.invoices.createPreview({ customer: 'cus_1234567890', subscription_items: [{ price: 'price_monthly_pro' }] }); console.log('Preview total:', preview.total); // Void an invoice const voided = await stripe.invoices.voidInvoice(invoice.id); // List invoices const invoices = await stripe.invoices.list({ customer: 'cus_1234567890', status: 'paid', limit: 10 }); ``` ## Refunds API Refunds return funds to customers for charges or payment intents, supporting full or partial refunds. ```typescript import Stripe from 'stripe'; const stripe = new Stripe('sk_test_your_api_key'); // Create a full refund for a PaymentIntent const refund = await stripe.refunds.create({ payment_intent: 'pi_1234567890', reason: 'requested_by_customer' }); console.log('Refund ID:', refund.id); console.log('Refund status:', refund.status); // Output: Refund ID: re_1234567890 // Output: Refund status: succeeded // Create a partial refund const partialRefund = await stripe.refunds.create({ payment_intent: 'pi_1234567890', amount: 500 // Refund $5.00 of the total }); // Refund a charge directly const chargeRefund = await stripe.refunds.create({ charge: 'ch_1234567890' }); // Retrieve a refund const retrieved = await stripe.refunds.retrieve('re_1234567890'); // Update a refund metadata const updated = await stripe.refunds.update('re_1234567890', { metadata: { reason_code: 'RMA-12345' } }); // Cancel a pending refund const canceled = await stripe.refunds.cancel('re_1234567890'); // List refunds const refunds = await stripe.refunds.list({ payment_intent: 'pi_1234567890', limit: 10 }); ``` ## Webhook Handling Webhooks notify your application of events in your Stripe account. The SDK provides signature verification to ensure webhook authenticity. ```typescript import Stripe from 'stripe'; import express from 'express'; const stripe = new Stripe('sk_test_your_api_key'); const webhookSecret = 'whsec_your_webhook_secret'; const app = express(); // Webhook endpoint - must use raw body app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => { const sig = req.headers['stripe-signature'] as string; let event: Stripe.Event; try { // Verify webhook signature event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret); } catch (err: any) { console.log(`Webhook signature verification failed: ${err.message}`); return res.status(400).send(`Webhook Error: ${err.message}`); } // Handle specific events switch (event.type) { case 'payment_intent.succeeded': const paymentIntent = event.data.object as Stripe.PaymentIntent; console.log(`Payment ${paymentIntent.id} succeeded!`); break; case 'payment_intent.payment_failed': const failedPayment = event.data.object as Stripe.PaymentIntent; console.log(`Payment ${failedPayment.id} failed.`); break; case 'customer.subscription.created': const subscription = event.data.object as Stripe.Subscription; console.log(`Subscription ${subscription.id} created.`); break; case 'customer.subscription.deleted': const canceledSub = event.data.object as Stripe.Subscription; console.log(`Subscription ${canceledSub.id} canceled.`); break; case 'invoice.paid': const invoice = event.data.object as Stripe.Invoice; console.log(`Invoice ${invoice.id} paid.`); break; default: console.log(`Unhandled event type: ${event.type}`); } res.json({ received: true }); } ); // Testing webhooks locally const testPayload = JSON.stringify({ id: 'evt_test_webhook', object: 'event', type: 'payment_intent.succeeded' }); const testHeader = stripe.webhooks.generateTestHeaderString({ payload: testPayload, secret: webhookSecret }); const testEvent = stripe.webhooks.constructEvent(testPayload, testHeader, webhookSecret); console.log('Test event:', testEvent.id); ``` ## Auto-Pagination The SDK provides automatic pagination for list endpoints, allowing iteration through large datasets without manual page management. ```typescript import Stripe from 'stripe'; const stripe = new Stripe('sk_test_your_api_key'); // Using async iterators (for-await-of) async function listAllCustomers() { for await (const customer of stripe.customers.list({ limit: 100 })) { console.log(customer.id, customer.email); // Break early if needed if (customer.email === 'target@example.com') { break; } } } // Using autoPagingEach await stripe.customers.list({ limit: 100 }).autoPagingEach(async (customer) => { await processCustomer(customer); // Return false to stop iteration if (shouldStop()) { return false; } }); // Using autoPagingToArray (for smaller datasets) const allCustomers = await stripe.customers .list({ limit: 100 }) .autoPagingToArray({ limit: 1000 }); // Max 10,000 items console.log(`Fetched ${allCustomers.length} customers`); // Paginating in reverse const recentCharges = await stripe.charges .list({ ending_before: 'ch_latest', limit: 50 }) .autoPagingToArray({ limit: 500 }); ``` ## Error Handling The SDK provides typed error classes for different failure scenarios, enabling precise error handling and recovery. ```typescript import Stripe from 'stripe'; const stripe = new Stripe('sk_test_your_api_key'); async function createPayment() { try { const paymentIntent = await stripe.paymentIntents.create({ amount: 2000, currency: 'usd', payment_method: 'pm_card_visa_chargeDeclined' }); return paymentIntent; } catch (error) { if (error instanceof Stripe.errors.StripeError) { switch (error.type) { case 'StripeCardError': // Card was declined console.log('Card declined:', error.message); console.log('Decline code:', error.decline_code); console.log('Error code:', error.code); break; case 'StripeInvalidRequestError': // Invalid parameters console.log('Invalid request:', error.message); console.log('Param:', error.param); break; case 'StripeAuthenticationError': // Invalid API key console.log('Authentication failed:', error.message); break; case 'StripeRateLimitError': // Too many requests console.log('Rate limited. Retry after backoff.'); break; case 'StripeConnectionError': // Network issue console.log('Connection error:', error.message); break; case 'StripeAPIError': // Stripe internal error console.log('API error:', error.message); break; case 'StripeIdempotencyError': // Idempotency key misuse console.log('Idempotency error:', error.message); break; default: console.log('Unknown Stripe error:', error.message); } // Access common error properties console.log('Request ID:', error.requestId); console.log('Status code:', error.statusCode); console.log('Doc URL:', error.doc_url); } else { // Non-Stripe error throw error; } } } ``` ## Stripe Connect Stripe Connect enables platforms to process payments on behalf of connected accounts, supporting Standard, Express, and Custom account types. ```typescript import Stripe from 'stripe'; const stripe = new Stripe('sk_test_your_api_key'); // Create a connected account const account = await stripe.accounts.create({ type: 'express', country: 'US', email: 'merchant@example.com', capabilities: { card_payments: { requested: true }, transfers: { requested: true } } }); console.log('Connected account:', account.id); // Create an account link for onboarding const accountLink = await stripe.accountLinks.create({ account: account.id, refresh_url: 'https://example.com/reauth', return_url: 'https://example.com/return', type: 'account_onboarding' }); console.log('Onboarding URL:', accountLink.url); // Create a payment on behalf of connected account const paymentIntent = await stripe.paymentIntents.create({ amount: 10000, currency: 'usd', application_fee_amount: 1000, // Platform takes $10 transfer_data: { destination: account.id } }, { stripeAccount: account.id // Optional: for direct charges }); // Make API calls on behalf of connected account const connectedCustomers = await stripe.customers.list( { limit: 10 }, { stripeAccount: 'acct_connected_account_id' } ); // Create a billing portal session for connected account's customer const portalSession = await stripe.billingPortal.sessions.create({ customer: 'cus_connected_customer', return_url: 'https://example.com/account' }, { stripeAccount: 'acct_connected_account_id' }); ``` ## Raw Requests For accessing undocumented or beta API endpoints, use the rawRequest method to make custom API calls. ```typescript import Stripe from 'stripe'; const stripe = new Stripe('sk_test_your_api_key'); // Make a raw POST request const response = await stripe.rawRequest( 'POST', '/v1/customers', { email: 'test@example.com' }, { apiVersion: '2026-02-25.clover' } ); console.log('Response:', response); // Make a raw GET request const getResponse = await stripe.rawRequest( 'GET', '/v1/customers/cus_123', undefined, {} ); // Access beta endpoints const betaResponse = await stripe.rawRequest( 'POST', '/v1/beta_feature', { param: 'value' }, { apiVersion: '2026-02-25.clover; beta_feature=v1' } ); ``` ## V2 Billing Meter Events The V2 API provides high-throughput meter event streaming for usage-based billing scenarios. ```typescript import Stripe from 'stripe'; const apiKey = 'sk_test_your_api_key'; const customerId = 'cus_1234567890'; let meterEventSession: any = null; async function refreshMeterEventSession() { if (!meterEventSession || new Date(meterEventSession.expires_at) <= new Date()) { const client = new Stripe(apiKey); meterEventSession = await client.v2.billing.meterEventSession.create(); } } async function sendMeterEvent(eventName: string, value: string) { await refreshMeterEventSession(); const client = new Stripe(meterEventSession.authentication_token); await client.v2.billing.meterEventStream.create({ events: [{ event_name: eventName, payload: { stripe_customer_id: customerId, value: value } }] }); } // Report usage events await sendMeterEvent('api_requests', '100'); await sendMeterEvent('storage_gb', '25'); ``` ## Summary The Stripe Node.js SDK is the recommended way to integrate Stripe payment processing into server-side JavaScript applications. It provides comprehensive coverage of Stripe's API including payment processing (PaymentIntents, Charges), recurring billing (Subscriptions, Invoices), checkout flows (Checkout Sessions), customer management, refunds, and platform payments (Connect). The SDK handles complex concerns like webhook signature verification, automatic pagination, network retries, and typed error handling out of the box. For production applications, the typical integration pattern involves: (1) creating customers and storing their IDs, (2) using Checkout Sessions or PaymentIntents for payment collection, (3) managing subscriptions for recurring revenue, (4) handling webhooks for asynchronous event processing, and (5) implementing proper error handling for payment failures. The SDK's TypeScript definitions provide excellent IDE support and type safety, while the Promise-based API integrates seamlessly with modern async/await patterns. For platform businesses, Stripe Connect support enables processing payments on behalf of connected accounts with application fees and transfers.