Skip to content

enviodev/stripe-api-gateway

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Stripe Billing API Wrapper Gateway

A production-ready billing proxy service that wraps any API endpoint with Stripe metered billing capabilities. Built with Rust (Axum) and Next.js.

Features

  • API Key Authentication: Secure API key validation and management
  • Request Proxying: Forward authenticated requests to upstream APIs
  • Usage Tracking: Real-time usage tracking with Redis
  • Stripe Integration: Automatic metered billing through Stripe subscriptions
  • Batch Sync: Efficient batch syncing of usage data to Stripe
  • Admin Dashboard: Beautiful Next.js UI for managing API keys and viewing usage
  • Prometheus Metrics: Built-in metrics for monitoring
  • Rate Limiting: Configurable rate limiting per API key
  • Production Ready: Error handling, logging, and Docker support

Architecture

Client Request → Rust Proxy (Axum) → Upstream API
                      ↓
                   Redis (Usage Tracking)
                      ↓
                   Stripe (Billing)
                      ↑
                Next.js Admin UI

Components

  1. Rust Proxy Service (rust-proxy/)

    • HTTP proxy server with API key validation
    • Request forwarding and response streaming
    • Usage tracking in Redis
    • Background worker for Stripe sync
    • Admin API for key management
  2. Next.js Admin UI (admin-ui/)

    • Dashboard with usage analytics
    • API key management interface
    • Usage charts and statistics
    • Stripe integration links
  3. Redis

    • API key storage
    • Usage counters
    • Rate limiting

Quick Start

Prerequisites

  • Docker and Docker Compose
  • Stripe account (test mode is fine)
  • Redis (handled by Docker Compose)

Setup

  1. Clone the repository

    git clone <repo-url>
    cd stripe-billing-api-wrapper-gateway
  2. Create environment file

    cp env.example .env
  3. Configure environment variables Edit .env and set:

    • UPSTREAM_BASE_URL: Your API endpoint to wrap
    • STRIPE_SECRET_KEY: Your Stripe secret key (sktest... or sklive...)
    • STRIPE_PRICE_ID: Your Stripe metered price ID (price_...)
  4. Start all services

    make up
    # or: docker-compose up -d
  5. Access the services

Stripe Setup

Create a Metered Price

  1. Go to Stripe Dashboard
  2. Navigate to Products → Add Product
  3. Create a product (e.g., "API Usage")
  4. Add a price:
    • Pricing model: Usage-based
    • Charge for metered usage: Sum of usage values
    • Unit amount: Set your price per request (e.g., $0.01)
  5. Copy the Price ID (starts with price_...)

Get Your API Keys

  • Secret Key: Dashboard → Developers → API keys
  • Use test mode keys (sktest...) for development

Usage

Creating an API Key

  1. Open the Admin UI at http://localhost:3002
  2. Navigate to API Keys → Create New Key
  3. Fill in:
    • Label: Descriptive name
    • Customer Email: Email for the Stripe customer
  4. Save the generated API key securely

Making Requests

Use the API key in the X-API-Key header:

curl -H "X-API-Key: sk_xxxxx" \
     http://localhost:3000/proxy/your/endpoint

The proxy will:

  1. Validate the API key
  2. Forward the request to your upstream API
  3. Track the usage in Redis
  4. Sync usage to Stripe (every 10 minutes)

Viewing Usage

  1. Open the Admin UI at http://localhost:3002
  2. Navigate to Usage to see aggregate statistics
  3. Click on any API key to see detailed monthly usage

Configuration

Environment Variables

Variable Description Default
UPSTREAM_BASE_URL Your API endpoint to wrap Required
REDIS_URL Redis connection URL redis://127.0.0.1:6379
STRIPE_SECRET_KEY Stripe secret key Required
STRIPE_PRICE_ID Stripe metered price ID Required
PROXY_PORT Port for proxy server 3000
ADMIN_PORT Port for admin API 3001
SYNC_INTERVAL_MINUTES Minutes between Stripe syncs 10
RATE_LIMIT_PER_MINUTE Max requests per minute per key 60
RUST_LOG Log level info

Admin UI Configuration

Create admin-ui/.env.local:

cd admin-ui
cp env.example .env.local
# Edit .env.local with your configuration

Example configuration:

NEXT_PUBLIC_API_URL=http://localhost:3001
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...

Development

Running Locally

Rust Proxy:

cd rust-proxy
cp .env.example .env
# Edit .env with your configuration
cargo run

Admin UI:

cd admin-ui
npm install
cp .env.local.example .env.local
# Edit .env.local with your configuration
npm run dev

Redis:

docker run -d -p 6379:6379 redis:7-alpine

Running Tests

# Rust tests
cd rust-proxy
cargo test

# UI tests
cd admin-ui
npm test

API Documentation

Admin API Endpoints

Health Check

GET /health

API Keys

List all API keys

GET /api-keys

Create API key

POST /api-keys
Content-Type: application/json

{
  "label": "Production Key",
  "customer_email": "[email protected]"
}

Deactivate API key

DELETE /api-keys/:key_suffix

Usage

Get usage summary (current month)

GET /usage/summary

Get detailed usage for a key

GET /usage/:key_suffix

Metrics

Prometheus metrics

GET /metrics

Proxy Endpoint

ANY /proxy/*
X-API-Key: your_api_key

All requests to /proxy/* are forwarded to the upstream API with the path preserved.

Deployment

Docker Compose (Recommended)

# Build and start
docker-compose up -d

# View logs
docker-compose logs -f

# Stop
docker-compose down

Kubernetes

See k8s/ directory for Kubernetes manifests (if available).

Cloud Providers

The application is containerized and can be deployed to:

  • AWS ECS/Fargate
  • Google Cloud Run
  • Azure Container Instances
  • DigitalOcean App Platform

Monitoring

Prometheus Metrics

Available at http://localhost:3001/metrics:

  • http_requests_total - Total HTTP requests
  • http_request_duration_seconds - Request duration
  • proxy_requests_total - Proxy requests by status
  • api_key_usage_total - Usage per API key
  • stripe_sync_total - Stripe sync operations

Logs

Structured JSON logging to stdout:

# View all logs
docker-compose logs -f

# View proxy logs
docker-compose logs -f rust-proxy

# View UI logs
docker-compose logs -f admin-ui

Troubleshooting

Proxy not forwarding requests

  • Check UPSTREAM_BASE_URL is set correctly
  • Verify API key is valid: curl http://localhost:3001/api-keys
  • Check Redis is running: redis-cli ping

Stripe sync failing

  • Verify STRIPE_SECRET_KEY and STRIPE_PRICE_ID are correct
  • Check logs: docker-compose logs rust-proxy | grep stripe
  • Ensure the price is configured as metered usage

UI not loading

  • Check NEXT_PUBLIC_API_URL points to admin API
  • Verify admin API is running: curl http://localhost:3001/health

Security Considerations

  • Store API keys securely (use environment variables)
  • Use HTTPS in production
  • Consider IP whitelisting for admin API
  • Rotate API keys regularly
  • Monitor usage for anomalies
  • Use Stripe webhook signing for production

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

MIT License - see LICENSE file for details

Support

For issues and questions:

Roadmap

  • Webhook support for Stripe events
  • Multiple pricing tiers
  • Usage alerts and notifications
  • GraphQL admin API
  • Multi-region support
  • Advanced rate limiting strategies

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published