Stripe Node.js Library

repository·master·Indexed 26 days ago

https://github.com/stripe/stripe-node

A type-safe Stripe API wrapper for server-side JavaScript and TypeScript applications. The library provides a convenient interface for interacting with the Stripe API, featuring support for Promises, async iterators for auto-pagination, and built-in TypeScript types. It includes utilities for verifying webhook signatures, configuring network retries, and managing Stripe Connect accounts.

Tokens
14.5K
Snippets
20
Records
109
Agent score
88%

What's inside stripe-node

  1. Configure network retries

    master

    The library automatically retries failed requests that are safe to retry. You can control this behavior using the maxNetworkRetries option.

    • Disable retries: Set maxNetworkRetries: 0.
    • Custom retries: Set a higher integer to attempt multiple retries with exponential backoff. Idempotency keys are automatically added where appropriate.

    Retries can be configured globally during initialization or overridden on a per-request basis.

    // Disable retries globally
    const stripeClient = Stripe('sk_test_...', {
      maxNetworkRetries: 0,
    });
    
    // Retry twice globally
    const stripeClient = Stripe('sk_test_...', {
      maxNetworkRetries: 2,
    });
    
    // Override for a specific request
    stripeClient.customers.create(
      {
        email: 'customer@example.com',
      },
      {
        maxNetworkRetries: 2,
      }
    );
  2. Install Public or Private Preview SDKs

    master

    Stripe features in the public preview phase can be accessed via versions with the -beta.X suffix. Private preview features use the -alpha.X suffix.

    To install the latest Public Preview: npm install stripe@public-preview --save-exact

    To install the latest Private Preview: npm install stripe@private-preview --save-exact

    To install a specific version: npm install stripe@<version> (e.g., npm install stripe@18.6.0-beta.1)

    Note: It is highly recommended to use --save-exact to pin your version, as preview releases may contain breaking changes without a major version bump.

    npm install stripe@public-preview --save-exact
    # or
    npm install stripe@18.6.0-beta.1
  3. Use auto-pagination for list requests

    master

    When retrieving lists of resources, you can use several methods to automatically handle pagination.

    1. Async Iterators (for-await-of): Best for Node environments supporting async iteration (Node 10+).

    2. autoPagingEach: Pass an async function to .autoPagingEach(). Returning false from the callback will stop the iteration.

    3. autoPagingToArray: Fetches all items across pages and returns them as a single array. Warning: Always provide a limit in the initial list call to prevent excessive memory consumption.

    // Async iterators
    for await (const customer of stripeClient.customers.list()) {
      doSomething(customer);
      if (shouldStop()) {
        break;
      }
    }
    
    // autoPagingEach
    await stripeClient.customers.list().autoPagingEach(async (customer) => {
      await doSomething(customer);
      if (shouldBreak()) {
        return false;
      }
    });
    
    // autoPagingToArray
    const allNewCustomers = await stripeClient.customers
      .list({created: {gt: lastMonth}, limit: 100})
      .autoPagingToArray({limit: 10000});
  4. Initialize the Stripe client

    master

    To use the library, instantiate the Stripe class with your account's secret key (available in the Stripe Dashboard).

    import Stripe from 'stripe';
    const stripeClient = new Stripe('sk_test_...');
    
    const customer = await stripeClient.customers.create({
      email: 'customer@example.com',
    });
    
    console.log(customer.id);
  5. Use Stripe with TypeScript

    master

    Stripe provides built-in types for the latest API version.

    Key requirements:

    • Import Stripe as a default import (do not use import * as Stripe).
    • Instantiate using new Stripe().
    • Use the provided type interfaces (e.g., Stripe.CustomerCreateParams) for parameters and return values.

    Note on API Versions: Types reflect the latest API version. If you are using an older API version, you may need to use // @ts-ignore to suppress type mismatches.

    import Stripe from 'stripe';
    const stripeClient = new Stripe('sk_test_...');
    
    const createCustomer = async () => {
      const params: Stripe.CustomerCreateParams = {
        description: 'test customer',
      };
    
      const customer: Stripe.Customer = await stripeClient.customers.create(params);
    
      console.log(customer.id);
    };
    createCustomer();
  6. Configure Stripe Connect using the stripeAccount option

    master

    To perform actions on behalf of a connected account using Stripe Connect, pass the stripeAccount option in the request configuration object (the second argument to the method). This adds the Stripe-Account header to the request.

    // List the balance transactions for a connected account:
    stripeClient.balanceTransactions.list(
      {
        limit: 10,
      },
      {
        stripeAccount: 'acct_foo',
      }
    );
  7. Handle Expandable fields in TypeScript

    master

    Expandable fields are typed as string | Foo. When you use the expand option, you must cast the field to the expected object type to access its properties.

    const paymentIntent: Stripe.PaymentIntent = await stripeClient.paymentIntents.retrieve(
      'pi_123456789',
      {
        expand: ['customer'],
      }
    );
    const customerEmail: string = (paymentIntent.customer as Stripe.Customer).email;
    
    // Helper to handle both ID strings and expanded objects
    function getId(stripeObject: {id: string} | string) {
      return typeof stripeObject === 'string' ? stripeObject : stripeObject.id;
    }
    
    const customerId: string = getId(paymentIntent.customer);
  8. Configure request timeouts

    master

    Timeouts can be configured globally during initialization or overridden for specific API calls.

    Global Timeout: Set the timeout property in the configuration object (value in milliseconds).

    Per-request Timeout: Pass a configuration object as the second argument to any Stripe method to override the global timeout.

    // Global timeout
    const stripeClient = Stripe('sk_test_...', {
      timeout: 20 * 1000, // 20 seconds
    });
    
    // Per-request override
    stripeClient.customers.create(
      {
        email: 'customer@example.com',
      },
      {
        timeout: 1000, // 1 second
      }
    );
  9. Verify webhook signatures

    master

    To ensure webhook events were sent by Stripe, use stripeClient.webhooks.constructEvent().

    Important: You must pass the raw request body exactly as received from Stripe. Do not use a parsed JSON body.

    Mocking Webhooks for Testing: Use stripeClient.webhooks.generateTestHeaderString to create a valid signature header for testing purposes.

    // Constructing an event
    const event = stripeClient.webhooks.constructEvent(
      webhookRawBody,
      webhookStripeSignatureHeader,
      webhookSecret
    );
    
    // Testing/Mocking
    const payload = {
      id: 'evt_test_webhook',
      object: 'event',
    };
    const payloadString = JSON.stringify(payload, null, 2);
    const secret = 'whsec_test_secret';
    
    const header = stripeClient.webhooks.generateTestHeaderString({
      payload: payloadString,
      secret,
    });
    
    const event = stripeClient.webhooks.constructEvent(
      payloadString,
      header,
      secret
    );
  10. Configure a proxy agent

    master

    To route Stripe requests through a proxy, pass an instance of a proxy agent (such as https-proxy-agent) to the httpAgent option during initialization.

    if (process.env.http_proxy) {
      const ProxyAgent = require('https-proxy-agent');
    
      const stripe = Stripe('sk_test_...', {
        httpAgent: new ProxyAgent(process.env.http_proxy),
      });
    }