Back

Stripe API Essential Guide

Jul 19, 20246 minute read

What type of API does Stripe provide?

Stripe primarily uses a REST API.

REST (Representational State Transfer) is a popular architectural style for designing web services.

The Stripe API provides methods for creating and managing payments, subscriptions, and customers using HTTP methods like GET, POST, PUT, and DELETE.

While Stripe's main API is REST-based, there are efforts to create unofficial GraphQL wrappers for the Stripe API. For example, there's an open-source project that provides a GraphQL API for Stripe. However, this is not an official Stripe offering.

REST APIs are designed to be lightweight, easy to use, and flexible, which aligns with Stripe's goal of providing a developer-friendly payment processing solution.

Does the Stripe API have webhooks?

Yes, the official Stripe API does have webhooks. Stripe uses webhooks to send real-time event notifications to your application when certain events occur in your Stripe account. Here are the key points about Stripe webhooks:

Webhook Overview

  • Stripe generates event data that can be sent to your application to inform you of activity in your account.
  • When an event occurs, Stripe creates a new Event object.
  • By registering webhook endpoints, you enable Stripe to automatically send Event objects as POST requests to your registered endpoint.

Types of Events

Stripe offers a wide range of events you can subscribe to. Some common event types include:

  • payment_intent.succeeded: When a payment is successful.
  • payment_intent.payment_failed: When a payment fails.
  • customer.subscription.created: When a new subscription is created.
  • customer.subscription.updated: When a subscription is updated.
  • customer.subscription.deleted: When a subscription is canceled.
  • invoice.paid: When an invoice is paid.
  • invoice.payment_failed: When an invoice payment fails.
  • invoice.upcoming: Sent a few days before a subscription renews.

Setting Up Webhooks

  1. Create a webhook endpoint handler in your application to receive event data.
  2. Test your webhook endpoint locally using the Stripe CLI.
  3. Register your endpoint with Stripe using the Dashboard or API.

Best Practices

  • Quickly return a 2xx status code before performing any complex logic to avoid timeouts.
  • Verify webhook signatures to ensure events are sent by Stripe.
  • Implement proper error handling and retries.
  • Use HTTPS for your webhook endpoint in live mode.

Subscription-specific Considerations

  • Webhooks are especially important for subscriptions, where most activity occurs asynchronously.
  • Use webhooks to track active subscriptions and update customer access based on payment status.
  • Handle events related to invoice statuses, particularly for subscription-generated invoices.

By utilizing Stripe's webhook system, you can build a robust integration that responds in real-time to various events in your Stripe account, ensuring your application stays in sync with the payment processing activities.

Rate Limits and other limitations

The Stripe API rate limits are designed to prevent abuse and ensure fair usage for all users. Let's break down the rate limits and discuss how to work with them effectively:

Stripe API Rate Limits

  1. Basic Rate Limiter:

    • Live mode: 100 read operations and 100 write operations per second
    • Test mode: 25 read operations and 25 write operations per second
  2. Stricter Limits for Specific Resources:

    • Files API: 20 read operations and 20 write operations per second
    • Search API: 20 read operations per second
  3. API Read Request Allocations:

    • 500 requests per transaction on a rolling 30-day basis
    • Minimum allocation of 10,000 read requests per month for every account

Key Points to Consider

  1. Rate limits apply separately to live mode and test mode.
  2. The limits are per-second, not per-request.
  3. Certain resources have stricter limits but also count against the basic limits.
  4. Read API request allocations are based on transaction count.

Handling Rate Limits

To work within these rate limits, consider the following strategies:

  1. Implement backoff and retry logic: When you receive a 429 error (Too Many Requests), implement an exponential backoff strategy to retry the request after a delay.

  2. Optimize your API usage: Reduce the number of API calls by batching requests where possible and caching frequently accessed data.

  3. Use webhooks: Instead of polling the API for updates, use webhooks to receive real-time notifications about events.

  4. Implement client-side rate limiting: Control the rate of requests on your side to stay within the limits.

Code Implementation

Here's an example of how you can modify your code to handle rate limits more effectively:

const { promisify } = require('util'); const sleep = promisify(setTimeout); async function fetchWithRetry(fetchFunction, maxRetries = 3, initialDelay = 1000) { let retries = 0; while (retries < maxRetries) { try { return await fetchFunction(); } catch (error) { if (error.statusCode === 429) { const delay = initialDelay * Math.pow(2, retries); console.log(`Rate limited. Retrying in ${delay}ms...`); await sleep(delay); retries++; } else { throw error; } } } throw new Error('Max retries reached'); } async function fetchFromLastObj(last_obj) { return fetchWithRetry(() => stripe.products.list({ active: true, limit: maxRetrieve, starting_after: last_obj, }) ); } async function fetchAllProducts() { let last_obj_seen = null; let allProducts = []; while (true) { const response = await fetchFromLastObj(last_obj_seen); const fetchedList = response.data; if (fetchedList.length === 0) break; allProducts = allProducts.concat(fetchedList); last_obj_seen = fetchedList[fetchedList.length - 1].id; if (!response.has_more) break; // Add a small delay between requests to avoid hitting rate limits await sleep(100); } return allProducts; } // Usage fetchAllProducts() .then(products => { console.log(`Retrieved ${products.length} products`); // Process products... }) .catch(error => console.error('Error fetching products:', error));

Summary and Best Practices

  1. Implemented exponential backoff and retry logic for handling rate limits.
  2. Used async/await for better readability and error handling.
  3. Implemented a fetchWithRetry function to handle 429 errors automatically.
  4. Added a small delay between requests to avoid hitting rate limits unnecessarily.
  5. Used the has_more property to determine when to stop fetching.

By following these practices, you can work more effectively within Stripe's rate limits while fetching all your products. Remember to always handle errors gracefully and implement proper logging to monitor your API usage.

Latest API Version

The most recent version of the Stripe API is 2024-03-14.

Key points to consider:

  • Stripe uses dated API versions to manage changes and avoid breaking existing integrations.

  • The API version controls the behavior you see in API responses, allowed parameters, and webhook data.

  • Your API version is set the first time you make an API request, but you can upgrade it later.

  • Stripe recommends specifying the API version explicitly in your code rather than relying on the account's default version.

  • You can test newer API versions by setting the Stripe-Version header in API calls.

  • To finalize an upgrade, you need to click the "Upgrade version" button in your Stripe Dashboard.

Best practices:

  1. Stay informed about API changes by subscribing to the Stripe Developer Digest.

  2. Test your integration with new API versions before upgrading.

  3. Ensure your code can handle Stripe-generated object IDs up to 255 characters long.

  4. Make your webhook listener able to handle unfamiliar event types gracefully.

  5. When upgrading, thoroughly test your integration to ensure compatibility with the new version.

By following these practices and staying up-to-date with the latest API version, you can ensure your integration remains robust and takes advantage of the latest Stripe features.

How to get a Stripe developer account and API Keys?

1. Create a Stripe account

  1. Go to the Stripe website (stripe.com) and click on "Create account" or "Sign up".
  2. Fill in the required information to create your account.
  3. Verify your email address.

2. Set up your development environment

  1. Install the Stripe CLI:

    • For macOS users, you can use Homebrew:
      brew install stripe/stripe-cli/stripe
      
    • For other operating systems, follow the installation instructions on the Stripe documentation.
  2. Authenticate your Stripe CLI:

    stripe login
    

    This will open a browser window for you to authenticate your Stripe account.

3. Get your API keys

  1. Log in to your Stripe Dashboard.
  2. Go to the Developers section.
  3. Find your API keys. You'll see both publishable and secret keys for test and live modes.

4. Choose a server-side SDK

Stripe offers SDKs for various programming languages. Choose the one that fits your tech stack. For example, if you're using Ruby:

  1. Add the Stripe gem to your project:
    bundle add stripe
    
  2. Install the gem:
    bundle install
    

5. Make your first API request

Here's an example of creating a product and a price using the Ruby SDK:

require 'stripe' Stripe.api_key = "sk_test_your_test_key_here" product = Stripe::Product.create( name: 'Starter Subscription', description: '$12/Month subscription', ) price = Stripe::Price.create( currency: 'usd', unit_amount: 1200, recurring: {interval: 'month'}, product: product.id, ) puts "Success! Here is your starter subscription product id: #{product.id}" puts "Success! Here is your starter subscription price id: #{price.id}"

What can you do with the Stripe API?

Based on the provided search results, here's a list of data models you can interact with using the Stripe API, along with what is possible for each data model:

Payments

  • Accept payments from various methods including credit cards, debit cards, and digital wallets
  • Process transactions from initiation to funds settlement
  • Handle international payments in over 135 currencies

Subscriptions and Billing

  • Manage and automate recurring revenue
  • Handle free trials, upgrades, downgrades, and cancellations
  • Create and manage subscription models for SaaS businesses
  • Implement usage-based billing (metering) for real-time usage events

Connect Platform

  • Accept payments and pay out to third parties (service providers, contractors, vendors)
  • Enable platforms and marketplaces to allow users to accept recurring payments or send invoices

Fraud Management (Radar)

  • Use machine learning to identify and prevent fraudulent transactions
  • Evaluate payments across Stripe's global network to detect patterns and identify fraud

Reporting and Analytics

  • Generate financial reports and analytics
  • Access real-time insights into financial data
  • Sync transaction data with accounting software
  • Use Stripe Sigma for SQL-based reporting and custom queries

Customers

  • Store and manage customer information
  • Update expired or renewed card information automatically

Products

  • Manage product information

Invoices

  • Create, customize, send, and revise Stripe-hosted invoices
  • Automate invoice collection with features like payment reminders and Smart Retries
  • Provide invoice previews for new or existing customers

Balance Transactions

  • Access and analyze balance transaction data

Tokenization

  • Securely store payment information by replacing sensitive data with tokens

Payouts

  • Send payments to individual accounts

Preauthorization

  • Temporarily hold funds on a customer's card

Refunds and Disputes

  • Handle refunds and manage disputes efficiently

Integrations

  • Integrate with CRM systems like HubSpot and Salesforce
  • Sync data with accounting systems like QuickBooks and Xero
  • Connect with data warehouses like Snowflake or Amazon Redshift

Compliance

  • Assist with PCI DSS compliance
  • Help businesses comply with various standards and regulations

This list covers the main data models and functionalities available through the Stripe API, based on the provided search results. Each of these models offers various possibilities for interacting with and managing payment-related data and processes.