Stripe 웹훅 처리
성공한 결제, 실패, 취소와 같은 비동기 결제 이벤트에 대응하도록 Stripe 웹훅을 설정하고 처리합니다.
Stripe 웹훅 처리은(는) CoddyKit의 무료 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Powered SaaS: Stripe + Auth + Billing + Deploy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What are Webhooks?
Imagine you're waiting for a package. You could constantly call the delivery company (polling) to ask for updates, or they could simply call you (webhook) when the package arrives. Webhooks are automated messages sent by one system to another when a specific event occurs.
They act like a notification system, allowing applications to communicate in real-time about changes or events.
Why Stripe Webhooks?
Payment processing is often asynchronous. This means an action, like a payment, might not complete instantly. It could take time, or even fail, after your user initiates it.
Stripe uses webhooks to notify your application about these crucial asynchronous events. Instead of constantly asking Stripe for updates, Stripe tells your app when a payment succeeds, a subscription renews, a refund is issued, or a failure occurs.
Key Stripe Event Types
Stripe sends different types of webhook events depending on what happened. Each event type has a unique identifier.
checkout.session.completed: A customer finished a Stripe Checkout session.invoice.payment_succeeded: A payment for an invoice (often related to subscriptions) was successful.customer.subscription.updated: A subscription changed status (e.g., from active to canceled).payment_intent.succeeded: A payment intent successfully captured funds.
These are just a few; there are many more to cover various scenarios.
Your Webhook Endpoint
To receive Stripe webhooks, your application needs a publicly accessible HTTP endpoint (a URL) that can accept POST requests. This endpoint will be the listener for all incoming Stripe events.
Here's a basic Python Flask example of what such an endpoint might look like:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/stripe-webhook', methods=['POST'])
def stripe_webhook():
# Stripe will send event data here
payload = request.get_data(as_text=True)
print(f"Received webhook: {payload[:100]}...") # Log first 100 chars
return jsonify(success=True), 200 # Always respond with 200 OK
if __name__ == '__main__':
# Run on a port for local testing. In production, use a server like Gunicorn.
app.run(port=4242, debug=True)Register with Stripe
Once you have your endpoint, you need to tell Stripe where to send the events. You do this in the Stripe Dashboard.
- Go to Developers > Webhooks.
- Click Add endpoint.
- Enter your public URL (e.g.,
https://yourdomain.com/stripe-webhook). - Select the event types you want to receive.
For local development, you can use the Stripe CLI's stripe listen command to forward events to your local endpoint.
Receiving Event Data
When an event occurs, Stripe sends a JSON payload to your endpoint. This payload contains all the details about the event, including its id, type, and the data object related to the event (e.g., a checkout.session or invoice object).
Your endpoint will read this JSON and decide what to do next based on the type of event.
from flask import Flask, request, jsonify
import json
app = Flask(__name__)
@app.route('/stripe-webhook', methods=['POST'])
def stripe_webhook():
event = json.loads(request.get_data())
event_id = event['id']
event_type = event['type']
print(f"Processing event ID: {event_id}, Type: {event_type}")
# In a real application, you'd perform actions here
# based on the event_type.
return jsonify(success=True), 200
if __name__ == '__main__':
app.run(port=4242, debug=True)Verify Webhook Signatures
This is crucial for security! Anyone could send a fake POST request to your webhook URL. To ensure an event genuinely came from Stripe and hasn't been tampered with, you must verify its signature.
Stripe includes a unique signature in the Stripe-Signature header of each webhook request. You'll use your webhook secret (from the Stripe Dashboard) to verify it.
from flask import Flask, request, jsonify
import stripe
import os
app = Flask(__name__)
# IMPORTANT: Use environment variables for secrets!
# For this example, replace with your actual keys:
stripe.api_key = "sk_test_YOUR_STRIPE_SECRET_KEY"
webhook_secret = "whsec_YOUR_WEBHOOK_SECRET" # Get from Stripe Dashboard
@app.route('/stripe-webhook', methods=['POST'])
def stripe_webhook():
payload = request.get_data()
sig_header = request.headers.get('stripe-signature')
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, webhook_secret
)
except ValueError as e:
# Invalid payload
print(f"Error: Invalid payload - {e}")
return "Invalid payload", 400
except stripe.error.SignatureVerificationError as e:
# Invalid signature
print(f"Error: Invalid signature - {e}")
return "Invalid signature", 400
# If we reach here, the event is verified and safe to process
print(f"Verified event type: {event['type']}")
return jsonify(success=True), 200
if __name__ == '__main__':
app.run(port=4242, debug=True)Processing Specific Events
Once an event is verified, your application can then process it based on its type. This typically involves updating your database, sending emails, or triggering other business logic.
It's common to use a switch statement or if/elif chain to handle different event types.
from flask import Flask, request, jsonify
import stripe
import os
app = Flask(__name__)
stripe.api_key = "sk_test_YOUR_STRIPE_SECRET_KEY"
webhook_secret = "whsec_YOUR_WEBHOOK_SECRET"
@app.route('/stripe-webhook', methods=['POST'])
def stripe_webhook():
payload = request.get_data()
sig_header = request.headers.get('stripe-signature')
event = None
try:
event = stripe.Webhook.construct_event(payload, sig_header, webhook_secret)
except Exception as e:
return str(e), 400
# Handle the event based on its type
if event['type'] == 'checkout.session.completed':
session = event['data']['object']
print(f"Checkout Session Completed: {session['id']}")
# TODO: Fulfill purchase, grant user access
elif event['type'] == 'invoice.payment_succeeded':
invoice = event['data']['object']
print(f"Invoice Payment Succeeded: {invoice['id']}")
# TODO: Update user's subscription status, send receipt
elif event['type'] == 'customer.subscription.deleted':
subscription = event['data']['object']
print(f"Subscription Deleted: {subscription['id']}")
# TODO: Revoke user access
else:
print(f"Unhandled event type: {event['type']}")
return jsonify(success=True), 200
if __name__ == '__main__':
app.run(port=4242, debug=True)Webhook Best Practices
- Respond Quickly: Stripe expects a
200 OKresponse within a few seconds. If processing is heavy, do it asynchronously (e.g., send to a queue). - Idempotency: Design your event handlers to be idempotent. Stripe might send the same event multiple times, so ensure processing an event twice doesn't cause issues.
- Error Handling: Implement robust logging and error handling. If your endpoint returns an error, Stripe will retry sending the event.
- Security: Always use HTTPS for your webhook endpoint.
Webhook Security Check
When setting up a Stripe webhook endpoint, which of the following is the most critical security measure to implement?
Recap: Handling Webhooks
In this lesson, we explored how to handle Stripe webhooks. You learned that webhooks are essential for reacting to asynchronous payment events in real-time.
- You create a dedicated endpoint in your application.
- You register this endpoint in the Stripe Dashboard.
- Crucially, you verify the webhook signature to ensure authenticity and integrity.
- Finally, you process different event types to keep your application's state synchronized with Stripe's, fulfilling orders, updating subscriptions, and more.
자주 묻는 질문
“Stripe 웹훅 처리” 강의는 무료인가요?
네 — “Stripe 웹훅 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의 전체를 잠금 해제할 수 있습니다. AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에는 총 4개의 강의가 포함되어 있습니다.
“Stripe 웹훅 처리”에서 뭘 배우나요?
성공한 결제, 실패, 취소와 같은 비동기 결제 이벤트에 대응하도록 Stripe 웹훅을 설정하고 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Powered SaaS: Stripe + Auth + Billing + Deploy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Powered SaaS: Stripe + Auth + Billing + Deploy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Powered SaaS: Stripe + Auth + Billing + Deploy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“Stripe 웹훅 처리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 구독 관리
- Stripe 웹훅 처리
- 고객 포털 및 결제 내역
- 사용량 측정 결제와 사용량 기반 가격 책정