From b02b72adac54baebe6275dd0da956ab507a5714c Mon Sep 17 00:00:00 2001 From: Rohan Chaturvedi Date: Tue, 19 Nov 2024 12:05:03 +0530 Subject: [PATCH] fix: handle stripe subscription created webhook (#390) --- backend/ee/billing/webhooks/stripe.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/backend/ee/billing/webhooks/stripe.py b/backend/ee/billing/webhooks/stripe.py index 800521231..f86f9cbf9 100644 --- a/backend/ee/billing/webhooks/stripe.py +++ b/backend/ee/billing/webhooks/stripe.py @@ -7,6 +7,29 @@ from django.conf import settings +def handle_subscription_created(event): + """ + Handles the creation of a subscription. Updates the organisation's + stripe_subscription_id and plan tier based on the price_id. + """ + subscription = event["data"]["object"] + + try: + organisation = Organisation.objects.get( + stripe_customer_id=subscription["customer"] + ) + + # Set the subscription ID and update the plan + organisation.stripe_subscription_id = subscription["id"] + organisation.plan = map_stripe_plan_to_tier( + subscription["items"]["data"][0]["price"]["id"] + ) + organisation.save() + + except Organisation.DoesNotExist: + return JsonResponse({"error": "Organisation not found"}, status=404) + + def handle_subscription_updated(event): subscription = event["data"]["object"] @@ -74,7 +97,9 @@ def stripe_webhook(request): return JsonResponse({"error": "Invalid signature"}, status=400) # Route events to the appropriate handler - if event["type"] == "customer.subscription.updated": + if event["type"] == "customer.subscription.created": + handle_subscription_created(event) + elif event["type"] == "customer.subscription.updated": handle_subscription_updated(event) elif event["type"] == "customer.subscription.deleted": handle_subscription_deleted(event)