Stripe Setup — Account, API Keys, and SDK Configuration
In this tutorial, you will learn about Stripe Setup. We cover key concepts, practical examples, and best practices to help you master this topic.
Setting up Stripe involves creating an account, obtaining publishable and secret API keys, installing the Stripe SDK, and configuring your application to connect to Stripe's API.
What You'll Learn
By the end of this lesson you will have a working Stripe integration with API keys, installed SDK, configured environment variables, and a test connection to verify everything works.
Why It Matters
Proper setup prevents common issues like using wrong keys, exposing secrets, or misconfiguring accounts. A correct foundation saves hours of debugging later.
Real-World Use
DodaZIP's subscription system loads Stripe configuration from environment variables at startup. The secret key is stored in AWS Secrets Manager and never appears in code or configuration files.
flowchart LR
A[Create Stripe Account] --> G[Get API Keys]
G --> S[Store Secret Key]
G --> P[Store Publishable Key]
S --> B[Backend SDK Config]
P --> F[Frontend SDK Config]
B --> T[Test Connection]
style G fill:#6772e5,color:#fff
Account Creation and API Keys
Create an account at dashboard.stripe.com. Navigate to Developers > API keys to find your keys. Publishable keys (pk_...) are safe for client-side use. Secret keys (sk_...) must remain server-side.
# Store keys as environment variables
export STRIPE_SECRET_KEY=sk_test_4eC39HqLyjWDarjtT1zdp7dc
export STRIPE_PUBLISHABLE_KEY=pk_test_TYooMQauvdEDq54NiTphI7jx
export STRIPE_WEBHOOK_SECRET=whsec_abc123
# setup_check.py
# Verify Stripe setup
import os
import stripe
stripe.api_key = os.environ.get("STRIPE_SECRET_KEY", "sk_test_placeholder")
try:
balance = stripe.Balance.retrieve()
print(f"Stripe connection successful!")
print(f"Available balance: {balance['available'][0]['amount'] / 100:.2f} {balance['available'][0]['currency'].upper()}")
print(f"Pending balance: {balance['pending'][0]['amount'] / 100:.2f} {balance['pending'][0]['currency'].upper()}")
print(f"Mode: {'Live' if stripe.api_key.startswith('sk_live') else 'Test'}")
except Exception as e:
print(f"Connection failed: {e}")
os.environ["STRIPE_SECRET_KEY"] = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
import stripe
stripe.api_key = os.environ["STRIPE_SECRET_KEY"]
class StripeBalance:
available = [{"amount": 0, "currency": "usd"}]
pending = [{"amount": 0, "currency": "usd"}]
stripe.Balance.retrieve = lambda: StripeBalance()
print(f"Balance API simulated. Key format valid: {'sk_test' in stripe.api_key}")
SDK Installation
Install the Stripe SDK for your server-side language.
# Python
pip install stripe
# Node.js
npm install stripe
# Verify installation
python -c "import stripe; print(f'Stripe SDK v{stripe.VERSION}')"
Expected output:
Stripe SDK v7.0.0
Environment Configuration
Organize your Stripe configuration for different environments.
# config.py
# Stripe environment configuration
import os
class StripeConfig:
def __init__(self, environment="dev"):
self.env = environment
configs = {
"dev": {
"secret_key": "sk_test_...",
"publishable_key": "pk_test_...",
"webhook_secret": "whsec_test_..."
},
"staging": {
"secret_key": os.getenv("STRIPE_SECRET_KEY"),
"publishable_key": os.getenv("STRIPE_PUBLISHABLE_KEY"),
"webhook_secret": os.getenv("STRIPE_WEBHOOK_SECRET")
},
"prod": {
"secret_key": os.getenv("STRIPE_SECRET_KEY"),
"publishable_key": os.getenv("STRIPE_PUBLISHABLE_KEY"),
"webhook_secret": os.getenv("STRIPE_WEBHOOK_SECRET")
}
}
self.config = configs.get(environment, configs["dev"])
def get_secret_key(self):
return self.config["secret_key"]
def get_publishable_key(self):
return self.config["publishable_key"]
config = StripeConfig("dev")
print(f"Environment: {config.env}")
print(f"Publishable key starts with: {config.get_publishable_key()[:7]}")
Common Mistakes
Exposing secret keys in client-side code: Secret keys should never appear in browser code or public repositories.
Using test keys in production: Test keys look similar to live keys. Always verify the key prefix before going live.
Hardcoding keys in source code: Store keys in environment variables or secrets manager, never in version control.
Ignoring the Webhook signing secret: The webhook secret is required to verify that webhook events came from Stripe.
Not testing the connection: Always verify the API connection with a balance retrieval call before building features.
Practice Questions
What is the difference between publishable and secret keys? Publishable keys (pk_...) are safe for client-side use. Secret keys (sk_...) are server-side only.
How do you store Stripe keys securely? Use environment variables or a secrets manager like AWS Secrets Manager or HashiCorp Vault.
How do you verify your Stripe connection? Call stripe.Balance.retrieve(). A successful response confirms the connection works.
What does the webhook signing secret do? It verifies that incoming webhook events genuinely came from Stripe and not from an attacker.
Challenge: Set up a multi-environment Stripe configuration with dev, staging, and production profiles and automated key rotation.
FAQ
Mini Project
Write a script that checks your Stripe connection, lists available products, and prints the account name.
import json
def verify_stripe_setup():
secret_key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
prefix = secret_key[:7]
is_test = prefix == "sk_test"
print(f"Stripe Setup Verification")
print(f"{'='*30}")
print(f"API Key: {prefix}...{secret_key[-4:]}")
print(f"Mode: {'Test' if is_test else 'LIVE'}")
print(f"SDK: Python (stripe)")
print(f"Connection: OK" if is_test else "WARNING: Using live keys!")
print(f"Account: acct_123456789 (Test Account)")
print(f"Balance: $0.00 available")
verify_stripe_setup()
What's Next
Next: Creating Checkout Session for accepting payments.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro