Authentication overview
Stripe Billing integrates with the core Stripe API platform, inheriting its authentication mechanisms. This provides a consistent approach for developers already familiar with other Stripe products, such as Stripe Payments or Stripe Connect. The primary method for authenticating requests to the Stripe Billing API is through the use of API keys, which are categorized into secret keys and publishable keys. These keys allow applications to programmatically interact with Stripe's services to manage subscriptions, invoices, and other billing-related operations.
Authentication ensures that only authorized applications can access and manipulate sensitive billing data. All communications with the Stripe API must occur over HTTPS, which encrypts data in transit, protecting against eavesdropping and tampering. Stripe's API is RESTful, accepting various HTTP methods (GET, POST, PUT, DELETE) for resource manipulation, and authentication details are typically included in the request headers.
The developer experience with Stripe Billing authentication is designed to be straightforward, leveraging the same SDKs and API patterns as the broader Stripe ecosystem. This consistency is noted in the Stripe Billing documentation, which emphasizes the unified API approach.
Supported authentication methods
Stripe Billing primarily relies on API keys for authentication. These keys serve different purposes and are used in distinct environments to maintain security.
API Keys
Stripe utilizes two main types of API keys:
- Secret API Keys: These keys are used for server-side operations where sensitive data is handled, such as creating subscriptions, processing charges, or retrieving customer details. Secret keys must be kept confidential and should never be exposed in client-side code, mobile applications, or public repositories. They grant full access to your Stripe account's API.
- Publishable API Keys: These keys are designed for client-side use, such as collecting payment information directly from a customer's browser or mobile app. Publishable keys can be safely embedded in client-side code because they only identify your account and do not grant access to sensitive operations or data. They are primarily used with Stripe.js to securely tokenize payment information, ensuring PCI compliance for the client-side interaction without handling raw card data.
Both secret and publishable keys are available in two modes: test mode and live mode. Test mode keys allow developers to simulate API calls and test their integration without affecting real money or customer data. Live mode keys are used for production environments and interact with actual customer and financial data.
The following table summarizes the key types and their appropriate usage:
| Method | When to Use | Security Level |
|---|---|---|
| Secret API Key | Server-side API calls (e.g., creating subscriptions, issuing invoices, managing customers) | High (requires strict confidentiality, full API access) |
| Publishable API Key | Client-side integration (e.g., collecting payment details with Stripe.js, displaying pricing) | Moderate (can be public, limited API access) |
Getting your credentials
To obtain your Stripe Billing API keys, you need to access your Stripe Dashboard. The process involves generating and retrieving the secret and publishable keys for both test and live modes.
- Log in to your Stripe Dashboard: Navigate to the Stripe Dashboard login page and sign in with your account credentials.
- Access API keys settings: From the dashboard, go to the "Developers" section in the left-hand navigation. Under "Developers," select "API keys."
- Retrieve your keys: On the API keys page, you will see your publishable key immediately. To reveal your secret key, you may need to click a button (e.g., "Reveal live key" or "Reveal test key") and confirm your identity (e.g., by re-entering your password).
- Understand test and live modes: Ensure you are in the correct mode (test or live) by using the toggle on the top right of the dashboard. Test mode keys start with
pk_test_andsk_test_, while live mode keys start withpk_live_andsk_live_. Integrate with test keys first for development and testing, then switch to live keys for production deployment, as detailed in Stripe's API key documentation.
For enhanced security and organizational control, Stripe also supports Restricted API Keys. These keys allow you to define granular permissions, limiting access to specific API resources (e.g., only allowing access to subscription management APIs and not payment processing APIs). This is particularly useful for granting limited access to third-party services or specific internal teams.
Authenticated request example
Authenticating requests to the Stripe Billing API involves including your secret API key in the request header. The following example demonstrates how to create a new customer and a subscription using the Node.js SDK, which automatically handles the authentication header when initialized with your secret key.
const stripe = require('stripe')('sk_test_YOUR_SECRET_KEY');
async function createSubscription() {
try {
// 1. Create a Customer
const customer = await stripe.customers.create({
email: '[email protected]',
description: 'New customer for subscription',
payment_method: 'pm_card_visa', // A test payment method token
invoice_settings: {
default_payment_method: 'pm_card_visa',
},
});
console.log('Customer created:', customer.id);
// 2. Create a Subscription
const subscription = await stripe.subscriptions.create({
customer: customer.id,
items: [
{price: 'price_12345'},
],
expand: ['latest_invoice.payment_intent'],
});
console.log('Subscription created:', subscription.id);
console.log('Invoice status:', subscription.latest_invoice.status);
} catch (error) {
console.error('Error creating subscription:', error.message);
}
}
createSubscription();
In this example, 'sk_test_YOUR_SECRET_KEY' should be replaced with your actual secret API key. The Node.js SDK handles the underlying HTTP request, including setting the Authorization: Bearer sk_test_YOUR_SECRET_KEY header. Similar patterns apply across other Stripe SDKs like Python, Ruby, and Java.
Security best practices
Adhering to security best practices is crucial when handling Stripe Billing API keys and making authenticated requests to protect your account and customer data.
- Keep Secret Keys Secret: Never hardcode secret API keys directly into your application code, especially in client-side applications. Store them securely using environment variables, AWS Secrets Manager, Google Cloud Secret Manager, or similar secure secret management services. This practice minimizes exposure if your codebase is compromised.
- Use Environment Variables: For server-side applications, load your secret key from environment variables. This keeps the key out of version control and allows for easy rotation across different deployment environments (development, staging, production).
- Restrict API Key Permissions: Utilize Stripe's Restricted API Keys for specific use cases or integrations. Grant only the necessary permissions (least privilege) required for a particular task or application component. For instance, if a service only needs to read subscription data, it should not have permissions to delete customers.
- Rotate API Keys Regularly: Periodically rotate your API keys to mitigate the risk of compromise. If a key is leaked, rotating it renders the compromised key invalid, preventing unauthorized access. Stripe provides tools in the Dashboard to manage key rotation.
- Encrypt Data in Transit: Always use HTTPS for all communications with the Stripe API. Stripe enforces this by requiring HTTPS, but ensuring your application's environment respects this is a foundational security measure. This aligns with general web security principles described by organizations like the Mozilla Developer Network's web security documentation.
- Implement Webhook Signature Verification: When receiving webhooks from Stripe (e.g., for subscription updates or invoice events), always verify the webhook signature. This ensures that the webhook event actually originated from Stripe and has not been tampered with, preventing spoofed events from affecting your application's billing logic. Stripe provides specific guidelines for verifying webhook signatures.
- Monitor API Activity: Regularly review your Stripe Dashboard logs for unusual API activity. Anomalies could indicate unauthorized access or misuse of your API keys.
- Adhere to PCI DSS: If your application handles any raw payment card data (which is not recommended when using Stripe.js for tokenization), ensure full compliance with the Payment Card Industry Data Security Standard (PCI DSS). Stripe's tokenization process significantly reduces your PCI compliance burden by ensuring sensitive card data never touches your servers.