Skip to content

Commit

Permalink
fix: update stripe webhook for better handling payment status.
Browse files Browse the repository at this point in the history
  • Loading branch information
nika-alaverdashvili committed Oct 29, 2024
1 parent 41b17f5 commit 7f52d87
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions payments/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,32 +103,42 @@ def post(self, request):
def stripe_webhook(request):
"""
Handle Stripe webhook events.
This view function listens for incoming webhook events from Stripe, verifies
the event signature, and updates the Payment object status based on the event type.
When a `checkout.session.completed` event is received, it retrieves the associated
Payment object using the `stripe_session_id`. If the payment status is "paid",
the Payment object's status is set to `COMPLETED`. If the payment status is "canceled",
the Payment object's status is set to `CANCELED`.
Returns:
HttpResponse: A response with status 200 for successful processing,
or appropriate error status if there are issues.
"""
payload = request.body
sig_header = request.META.get("HTTP_STRIPE_SIGNATURE")
event = None

# Retrieve the Stripe webhook secret directly from the environment
endpoint_secret = os.getenv("STRIPE_WEBHOOK_SECRET")

try:
# Verify the event by Stripe's signature
event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret)
except (ValueError, stripe.error.SignatureVerificationError):
# Invalid payload or signature verification failed
return HttpResponse(status=400, content="Invalid signature")

if event["type"] == "checkout.session.completed":
session = event["data"]["object"]

# Retrieve the Payment object and update its status
try:
payment = Payment.objects.get(stripe_session_id=session["id"])
payment.status = Payment.Status.COMPLETED

if session["payment_status"] == "paid":
payment.status = Payment.Status.COMPLETED
elif session["payment_status"] == "canceled":
payment.status = Payment.Status.CANCELED
payment.save()
except Payment.DoesNotExist:
# Payment object not found
return HttpResponse(status=404, content="Payment object not found")

# Return a 200 response to acknowledge receipt of the event
return HttpResponse(status=200)

0 comments on commit 7f52d87

Please sign in to comment.