FastAPI와 Stripe를 연동하여 결제 서비스 구현하기

FastAPI와 Stripe를 사용하여 웹 애플리케이션에 결제 서비스를 구현하는 방법을 알아보겠습니다.

1. Stripe 계정 생성 및 API 키 발급

먼저, Stripe 계정을 생성하고 API 키를 발급받아야 합니다. Stripe 계정은 https://stripe.com/에서 생성할 수 있습니다. 생성한 계정으로 로그인한 후 API Keys 탭에서 “Secret key”와 “Publishable key”를 발급받습니다.

2. FastAPI 프로젝트 설정

FastAPI 프로젝트를 세팅하기 위해 다음 명령어를 실행합니다.

$ mkdir payment-service
$ cd payment-service
$ python -m venv venv
$ source venv/bin/activate
$ pip install fastapi uvicorn stripe

3. FastAPI 애플리케이션 작성

FastAPI 애플리케이션을 작성해보겠습니다. payment_service/main.py 파일을 생성하고 다음과 같이 코드를 작성합니다.

from fastapi import FastAPI
from stripe.api_resources import checkout

app = FastAPI()

@app.post("/checkout")
async def create_checkout_session():
    # Stripe API를 사용하여 결제 세션 생성 로직 작성
    # ...
    return checkout_session

@app.post("/webhook")
async def webhook_endpoint():
    # Stripe webhook 처리 로직 작성
    # ...
    return "Webhook processed successfully"

4. Stripe 결제 세션 생성

Stripe API를 사용하여 결제 세션을 생성하는 함수를 작성합니다. payment_service/main.py 파일에 다음과 같이 코드를 추가합니다.

import stripe

stripe.api_key = "YOUR_STRIPE_SECRET_KEY"

@app.post("/checkout")
async def create_checkout_session():
    session = stripe.checkout.Session.create(
        # 결제 세션 생성 파라미터 설정
        payment_method_types=["card"],
        line_items=[{
            "price_data": {
                "currency": "usd",
                "product_data": {
                    "name": "Example Product",
                },
                "unit_amount": 1000,
            },
            "quantity": 1,
        }],
        mode="payment",
        success_url="https://example.com/success",
        cancel_url="https://example.com/cancel",
    )

    return session

5. Stripe 웹훅 처리

Stripe 웹훅을 처리하는 함수를 작성합니다. payment_service/main.py 파일에 다음과 같이 코드를 추가합니다.

import stripe

stripe.api_key = "YOUR_STRIPE_SECRET_KEY"

@app.post("/webhook")
async def webhook_endpoint(payload: dict):
    event = stripe.Event.construct_from(payload, stripe.api_key, stripe.api_version)

    # 이벤트 종류에 따른 웹훅 처리 로직 작성
    # ...
    
    return "Webhook processed successfully"

6. 애플리케이션 실행

FastAPI 애플리케이션을 실행하기 위해 다음 명령어를 실행합니다.

$ uvicorn payment_service.main:app --reload

애플리케이션이 성공적으로 실행되면 http://localhost:8000/docs로 접속하여 Swagger UI로 API를 테스트할 수 있습니다.

이제 FastAPI와 Stripe를 연동하여 결제 서비스를 구현하는 방법을 알아보았습니다. Stripe API를 사용하여 결제 세션을 생성하고 웹훅을 처리함으로써 실제 결제 서비스를 구현할 수 있습니다. #FastAPI #Stripe