diff --git a/README.md b/README.md index e8acfba..d31ebf0 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,144 @@ -# FastAPI Application +# Stripe Payment Integration Service -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A FastAPI service for handling Stripe payments with complete payment processing capabilities. + +## Features + +- Create and manage Stripe payment intents +- Process payments securely +- Handle Stripe webhooks for payment status updates +- Store payment records in SQLite database +- RESTful API with automatic OpenAPI documentation +- Health check endpoint + +## Environment Variables + +You need to set the following environment variables: + +```bash +STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key_here +STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret_here +``` + +## Installation + +1. Install dependencies: +```bash +pip install -r requirements.txt +``` + +2. Run database migrations: +```bash +alembic upgrade head +``` + +3. Start the development server: +```bash +uvicorn main:app --reload --host 0.0.0.0 --port 8000 +``` + +## API Endpoints + +### Base Endpoints +- `GET /` - Service information +- `GET /health` - Health check +- `GET /docs` - Interactive API documentation +- `GET /redoc` - Alternative API documentation + +### Payment Endpoints +- `POST /api/v1/payments/create-payment-intent` - Create a new payment intent +- `GET /api/v1/payments/payment-intent/{payment_intent_id}` - Get payment intent details +- `GET /api/v1/payments/payment/{payment_intent_id}` - Get payment record from database +- `POST /api/v1/payments/webhook` - Handle Stripe webhooks + +## Usage Example + +### Create a Payment Intent + +```bash +curl -X POST "http://localhost:8000/api/v1/payments/create-payment-intent" \ + -H "Content-Type: application/json" \ + -d '{ + "amount": 2000, + "currency": "usd", + "customer_email": "customer@example.com", + "customer_name": "John Doe", + "description": "Payment for services" + }' +``` + +### Response + +```json +{ + "client_secret": "pi_xxxxx_secret_xxxxx", + "payment_intent_id": "pi_xxxxx", + "amount": 2000, + "currency": "usd", + "status": "requires_payment_method" +} +``` + +## Database Schema + +The service uses SQLite with the following tables: + +### Payments Table +- `id` - Primary key +- `stripe_payment_intent_id` - Stripe payment intent ID +- `amount` - Payment amount +- `currency` - Payment currency +- `status` - Payment status +- `customer_email` - Customer email +- `customer_name` - Customer name +- `description` - Payment description +- `metadata` - Additional metadata (JSON) +- `created_at` - Creation timestamp +- `updated_at` - Last update timestamp +- `is_webhook_processed` - Webhook processing status + +### Payment Methods Table +- `id` - Primary key +- `stripe_payment_method_id` - Stripe payment method ID +- `customer_email` - Customer email +- `type` - Payment method type +- `card_brand` - Card brand (for card payments) +- `card_last_four` - Last four digits of card +- `is_default` - Default payment method flag +- `created_at` - Creation timestamp + +## Development + +### Code Formatting +The project uses Ruff for code formatting and linting: + +```bash +ruff check . +ruff format . +``` + +### Database Migrations +To create a new migration: + +```bash +alembic revision --autogenerate -m "Description of changes" +``` + +To apply migrations: + +```bash +alembic upgrade head +``` + +## Webhook Configuration + +Configure your Stripe webhook endpoint URL in the Stripe Dashboard: +- URL: `https://yourdomain.com/api/v1/payments/webhook` +- Events: `payment_intent.succeeded`, `payment_intent.payment_failed` + +## Security Notes + +- Always use HTTPS in production +- Store Stripe keys securely as environment variables +- Verify webhook signatures for security +- Never expose secret keys in client-side code diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..5cda32e --- /dev/null +++ b/alembic.ini @@ -0,0 +1,97 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = alembic + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python-dateutil library that can be +# installed by adding `alembic[tz]` to the pip requirements +# string value is passed to dateutil.tz.gettz() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the +# "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses +# os.pathsep. If this key is omitted entirely, it falls back to the legacy +# behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +version_path_separator = os + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = sqlite:////app/storage/db/db.sqlite + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..5915046 --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,79 @@ +from logging.config import fileConfig +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from alembic import context +import sys +from pathlib import Path + +# Add the project root to the path +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from app.db.base import Base + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +target_metadata = Base.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure(connection=connection, target_metadata=target_metadata) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..37d0cac --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} \ No newline at end of file diff --git a/alembic/versions/001_initial_migration.py b/alembic/versions/001_initial_migration.py new file mode 100644 index 0000000..8eb612f --- /dev/null +++ b/alembic/versions/001_initial_migration.py @@ -0,0 +1,101 @@ +"""Initial migration - create payments and payment_methods tables + +Revision ID: 001 +Revises: +Create Date: 2024-01-01 00:00:00.000000 + +""" + +from alembic import op +import sqlalchemy as sa + +# revision identifiers, used by Alembic. +revision = "001" +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # Create payments table + op.create_table( + "payments", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("stripe_payment_intent_id", sa.String(), nullable=True), + sa.Column("amount", sa.Float(), nullable=False), + sa.Column("currency", sa.String(), nullable=True), + sa.Column("status", sa.String(), nullable=False), + sa.Column("customer_email", sa.String(), nullable=True), + sa.Column("customer_name", sa.String(), nullable=True), + sa.Column("description", sa.String(), nullable=True), + sa.Column("metadata", sa.String(), nullable=True), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("(CURRENT_TIMESTAMP)"), + nullable=True, + ), + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("is_webhook_processed", sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index( + op.f("ix_payments_customer_email"), "payments", ["customer_email"], unique=False + ) + op.create_index(op.f("ix_payments_id"), "payments", ["id"], unique=False) + op.create_index( + op.f("ix_payments_stripe_payment_intent_id"), + "payments", + ["stripe_payment_intent_id"], + unique=True, + ) + + # Create payment_methods table + op.create_table( + "payment_methods", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("stripe_payment_method_id", sa.String(), nullable=True), + sa.Column("customer_email", sa.String(), nullable=True), + sa.Column("type", sa.String(), nullable=False), + sa.Column("card_brand", sa.String(), nullable=True), + sa.Column("card_last_four", sa.String(), nullable=True), + sa.Column("is_default", sa.Boolean(), nullable=True), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("(CURRENT_TIMESTAMP)"), + nullable=True, + ), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index( + op.f("ix_payment_methods_customer_email"), + "payment_methods", + ["customer_email"], + unique=False, + ) + op.create_index( + op.f("ix_payment_methods_id"), "payment_methods", ["id"], unique=False + ) + op.create_index( + op.f("ix_payment_methods_stripe_payment_method_id"), + "payment_methods", + ["stripe_payment_method_id"], + unique=True, + ) + + +def downgrade() -> None: + op.drop_index( + op.f("ix_payment_methods_stripe_payment_method_id"), + table_name="payment_methods", + ) + op.drop_index(op.f("ix_payment_methods_id"), table_name="payment_methods") + op.drop_index( + op.f("ix_payment_methods_customer_email"), table_name="payment_methods" + ) + op.drop_table("payment_methods") + op.drop_index(op.f("ix_payments_stripe_payment_intent_id"), table_name="payments") + op.drop_index(op.f("ix_payments_id"), table_name="payments") + op.drop_index(op.f("ix_payments_customer_email"), table_name="payments") + op.drop_table("payments") diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..59ccf73 --- /dev/null +++ b/app/api/__init__.py @@ -0,0 +1,3 @@ +from .payments import router as payments_router + +__all__ = ["payments_router"] diff --git a/app/api/payments.py b/app/api/payments.py new file mode 100644 index 0000000..715c692 --- /dev/null +++ b/app/api/payments.py @@ -0,0 +1,156 @@ +from fastapi import APIRouter, Depends, HTTPException, Request +from sqlalchemy.orm import Session +from typing import Optional, Dict, Any +from pydantic import BaseModel, EmailStr +import stripe +import json + +from app.db.session import get_db +from app.services.stripe_service import StripeService +from app.models.payment import Payment + +router = APIRouter(prefix="/payments", tags=["payments"]) + + +class CreatePaymentIntentRequest(BaseModel): + amount: int # Amount in cents + currency: str = "usd" + customer_email: Optional[EmailStr] = None + customer_name: Optional[str] = None + description: Optional[str] = None + metadata: Optional[Dict[str, Any]] = None + + +class PaymentIntentResponse(BaseModel): + client_secret: str + payment_intent_id: str + amount: int + currency: str + status: str + + +class PaymentResponse(BaseModel): + id: int + stripe_payment_intent_id: str + amount: float + currency: str + status: str + customer_email: Optional[str] + customer_name: Optional[str] + description: Optional[str] + created_at: str + + +@router.post("/create-payment-intent", response_model=PaymentIntentResponse) +async def create_payment_intent( + request: CreatePaymentIntentRequest, db: Session = Depends(get_db) +): + """Create a new payment intent""" + try: + stripe_service = StripeService() + + # Create payment intent with Stripe + payment_intent = stripe_service.create_payment_intent( + amount=request.amount, + currency=request.currency, + customer_email=request.customer_email, + customer_name=request.customer_name, + description=request.description, + metadata=request.metadata, + ) + + # Save to database + stripe_service.save_payment_to_db( + db=db, + payment_intent=payment_intent, + customer_email=request.customer_email, + customer_name=request.customer_name, + ) + + return PaymentIntentResponse( + client_secret=payment_intent.client_secret, + payment_intent_id=payment_intent.id, + amount=payment_intent.amount, + currency=payment_intent.currency, + status=payment_intent.status, + ) + + except stripe.error.StripeError as e: + raise HTTPException(status_code=400, detail=f"Stripe error: {str(e)}") + except Exception as e: + raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}") + + +@router.get("/payment-intent/{payment_intent_id}", response_model=PaymentIntentResponse) +async def get_payment_intent(payment_intent_id: str): + """Retrieve a payment intent""" + try: + stripe_service = StripeService() + payment_intent = stripe_service.retrieve_payment_intent(payment_intent_id) + + return PaymentIntentResponse( + client_secret=payment_intent.client_secret, + payment_intent_id=payment_intent.id, + amount=payment_intent.amount, + currency=payment_intent.currency, + status=payment_intent.status, + ) + + except stripe.error.StripeError as e: + raise HTTPException(status_code=400, detail=f"Stripe error: {str(e)}") + + +@router.get("/payment/{payment_intent_id}", response_model=PaymentResponse) +async def get_payment(payment_intent_id: str, db: Session = Depends(get_db)): + """Get payment details from database""" + payment = ( + db.query(Payment) + .filter(Payment.stripe_payment_intent_id == payment_intent_id) + .first() + ) + if not payment: + raise HTTPException(status_code=404, detail="Payment not found") + + return PaymentResponse( + id=payment.id, + stripe_payment_intent_id=payment.stripe_payment_intent_id, + amount=payment.amount, + currency=payment.currency, + status=payment.status, + customer_email=payment.customer_email, + customer_name=payment.customer_name, + description=payment.description, + created_at=payment.created_at.isoformat() if payment.created_at else "", + ) + + +@router.post("/webhook") +async def stripe_webhook(request: Request, db: Session = Depends(get_db)): + """Handle Stripe webhooks""" + payload = await request.body() + sig_header = request.headers.get("stripe-signature") + + if not sig_header: + raise HTTPException(status_code=400, detail="Missing Stripe signature") + + stripe_service = StripeService() + + # Verify webhook signature + if not stripe_service.verify_webhook_signature(payload, sig_header): + raise HTTPException(status_code=400, detail="Invalid webhook signature") + + try: + event = json.loads(payload) + + # Handle the event + if stripe_service.handle_webhook_event(db, event): + return {"status": "success"} + else: + return {"status": "unhandled_event_type"} + + except json.JSONDecodeError: + raise HTTPException(status_code=400, detail="Invalid JSON payload") + except Exception as e: + raise HTTPException( + status_code=500, detail=f"Webhook processing error: {str(e)}" + ) diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..3b8c18b --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,17 @@ +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker +from pathlib import Path + +DB_DIR = Path("/app") / "storage" / "db" +DB_DIR.mkdir(parents=True, exist_ok=True) + +SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite" + +engine = create_engine( + SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} +) + +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +Base = declarative_base() diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..22f0172 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,9 @@ +from app.db.base import SessionLocal + + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..4a21025 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1,3 @@ +from .payment import Payment, PaymentMethod + +__all__ = ["Payment", "PaymentMethod"] diff --git a/app/models/payment.py b/app/models/payment.py new file mode 100644 index 0000000..d173f55 --- /dev/null +++ b/app/models/payment.py @@ -0,0 +1,33 @@ +from sqlalchemy import Column, Integer, String, Float, DateTime, Boolean +from sqlalchemy.sql import func +from app.db.base import Base + + +class Payment(Base): + __tablename__ = "payments" + + id = Column(Integer, primary_key=True, index=True) + stripe_payment_intent_id = Column(String, unique=True, index=True) + amount = Column(Float, nullable=False) + currency = Column(String, default="usd") + status = Column(String, nullable=False) + customer_email = Column(String, index=True) + customer_name = Column(String) + description = Column(String) + metadata = Column(String) # JSON string for additional data + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), onupdate=func.now()) + is_webhook_processed = Column(Boolean, default=False) + + +class PaymentMethod(Base): + __tablename__ = "payment_methods" + + id = Column(Integer, primary_key=True, index=True) + stripe_payment_method_id = Column(String, unique=True, index=True) + customer_email = Column(String, index=True) + type = Column(String, nullable=False) # card, bank_account, etc. + card_brand = Column(String) # visa, mastercard, etc. + card_last_four = Column(String) + is_default = Column(Boolean, default=False) + created_at = Column(DateTime(timezone=True), server_default=func.now()) diff --git a/app/services/stripe_service.py b/app/services/stripe_service.py new file mode 100644 index 0000000..1f62908 --- /dev/null +++ b/app/services/stripe_service.py @@ -0,0 +1,130 @@ +import stripe +import os +from typing import Dict, Any, Optional +from sqlalchemy.orm import Session +from app.models.payment import Payment +import json + + +class StripeService: + def __init__(self): + stripe.api_key = os.getenv("STRIPE_SECRET_KEY") + self.webhook_secret = os.getenv("STRIPE_WEBHOOK_SECRET") + + def create_payment_intent( + self, + amount: int, + currency: str = "usd", + customer_email: Optional[str] = None, + customer_name: Optional[str] = None, + description: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + ) -> stripe.PaymentIntent: + """Create a Stripe payment intent""" + payment_intent_data = { + "amount": amount, + "currency": currency, + "automatic_payment_methods": {"enabled": True}, + } + + if customer_email: + payment_intent_data["receipt_email"] = customer_email + + if description: + payment_intent_data["description"] = description + + if metadata: + payment_intent_data["metadata"] = metadata + + return stripe.PaymentIntent.create(**payment_intent_data) + + def confirm_payment_intent(self, payment_intent_id: str) -> stripe.PaymentIntent: + """Confirm a payment intent""" + return stripe.PaymentIntent.confirm(payment_intent_id) + + def retrieve_payment_intent(self, payment_intent_id: str) -> stripe.PaymentIntent: + """Retrieve a payment intent""" + return stripe.PaymentIntent.retrieve(payment_intent_id) + + def create_customer( + self, email: str, name: Optional[str] = None + ) -> stripe.Customer: + """Create a Stripe customer""" + customer_data = {"email": email} + if name: + customer_data["name"] = name + return stripe.Customer.create(**customer_data) + + def save_payment_to_db( + self, + db: Session, + payment_intent: stripe.PaymentIntent, + customer_email: Optional[str] = None, + customer_name: Optional[str] = None, + ) -> Payment: + """Save payment data to database""" + payment = Payment( + stripe_payment_intent_id=payment_intent.id, + amount=payment_intent.amount / 100, # Convert from cents + currency=payment_intent.currency, + status=payment_intent.status, + customer_email=customer_email, + customer_name=customer_name, + description=payment_intent.description, + metadata=json.dumps(payment_intent.metadata) + if payment_intent.metadata + else None, + ) + db.add(payment) + db.commit() + db.refresh(payment) + return payment + + def update_payment_status( + self, db: Session, payment_intent_id: str, status: str + ) -> Optional[Payment]: + """Update payment status in database""" + payment = ( + db.query(Payment) + .filter(Payment.stripe_payment_intent_id == payment_intent_id) + .first() + ) + if payment: + payment.status = status + db.commit() + db.refresh(payment) + return payment + + def verify_webhook_signature(self, payload: bytes, sig_header: str) -> bool: + """Verify Stripe webhook signature""" + try: + stripe.Webhook.construct_event(payload, sig_header, self.webhook_secret) + return True + except ValueError: + return False + except stripe.error.SignatureVerificationError: + return False + + def handle_webhook_event(self, db: Session, event: Dict[str, Any]) -> bool: + """Handle Stripe webhook events""" + if event["type"] == "payment_intent.succeeded": + payment_intent = event["data"]["object"] + self.update_payment_status(db, payment_intent["id"], "succeeded") + + # Mark webhook as processed + payment = ( + db.query(Payment) + .filter(Payment.stripe_payment_intent_id == payment_intent["id"]) + .first() + ) + if payment: + payment.is_webhook_processed = True + db.commit() + return True + + elif event["type"] == "payment_intent.payment_failed": + payment_intent = event["data"]["object"] + self.update_payment_status(db, payment_intent["id"], "failed") + return True + + return False diff --git a/main.py b/main.py new file mode 100644 index 0000000..668c4f1 --- /dev/null +++ b/main.py @@ -0,0 +1,47 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from app.api.payments import router as payments_router +from app.db.base import engine, Base + +# Create database tables +Base.metadata.create_all(bind=engine) + +app = FastAPI( + title="Stripe Payment Integration Service", + description="A FastAPI service for handling Stripe payments", + version="1.0.0", +) + +# Configure CORS +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Include routers +app.include_router(payments_router, prefix="/api/v1") + + +@app.get("/") +async def root(): + """Base endpoint with service information""" + return { + "title": "Stripe Payment Integration Service", + "description": "A FastAPI service for handling Stripe payments", + "version": "1.0.0", + "documentation": "/docs", + "health_check": "/health", + } + + +@app.get("/health") +async def health_check(): + """Health check endpoint""" + return { + "status": "healthy", + "service": "stripe-payment-integration-service", + "version": "1.0.0", + } diff --git a/openapi.json b/openapi.json new file mode 100644 index 0000000..db14b68 --- /dev/null +++ b/openapi.json @@ -0,0 +1,163 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Stripe Payment Integration Service", + "description": "A FastAPI service for handling Stripe payments", + "version": "1.0.0" + }, + "paths": { + "/": { + "get": { + "summary": "Root", + "operationId": "root__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + }, + "/health": { + "get": { + "summary": "Health Check", + "operationId": "health_check_health_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + }, + "/api/v1/payments/create-payment-intent": { + "post": { + "tags": ["payments"], + "summary": "Create Payment Intent", + "operationId": "create_payment_intent_api_v1_payments_create_payment_intent_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreatePaymentIntentRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentIntentResponse" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "CreatePaymentIntentRequest": { + "properties": { + "amount": { + "type": "integer", + "title": "Amount" + }, + "currency": { + "type": "string", + "title": "Currency", + "default": "usd" + }, + "customer_email": { + "anyOf": [ + { + "type": "string", + "format": "email" + }, + { + "type": "null" + } + ], + "title": "Customer Email" + }, + "customer_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Customer Name" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Description" + }, + "metadata": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Metadata" + } + }, + "type": "object", + "required": ["amount"], + "title": "CreatePaymentIntentRequest" + }, + "PaymentIntentResponse": { + "properties": { + "client_secret": { + "type": "string", + "title": "Client Secret" + }, + "payment_intent_id": { + "type": "string", + "title": "Payment Intent Id" + }, + "amount": { + "type": "integer", + "title": "Amount" + }, + "currency": { + "type": "string", + "title": "Currency" + }, + "status": { + "type": "string", + "title": "Status" + } + }, + "type": "object", + "required": ["client_secret", "payment_intent_id", "amount", "currency", "status"], + "title": "PaymentIntentResponse" + } + } + } +} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c3e89f7 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +fastapi==0.104.1 +uvicorn[standard]==0.24.0 +stripe==7.8.0 +sqlalchemy==2.0.23 +alembic==1.13.1 +python-multipart==0.0.6 +python-jose[cryptography]==3.3.0 +passlib[bcrypt]==1.7.4 +python-dotenv==1.0.0 +ruff==0.1.7 \ No newline at end of file