From 48d18d6ef35aeabfa43aea8b4b5738adc9cb1c34 Mon Sep 17 00:00:00 2001 From: rizwanisready Date: Tue, 6 Aug 2024 21:04:00 +0530 Subject: [PATCH] getting discounted amount from transaction --- .../webhook/payment_processing_service.py | 6 ++++- goodtimes/webhook/webhook_service.py | 17 +++++++++++++ manage_subscriptions/views.py | 25 +++++++++++++++---- templates/stripe_html/index.html | 5 +++- 4 files changed, 46 insertions(+), 7 deletions(-) diff --git a/goodtimes/webhook/payment_processing_service.py b/goodtimes/webhook/payment_processing_service.py index 95ff625..fb9af51 100644 --- a/goodtimes/webhook/payment_processing_service.py +++ b/goodtimes/webhook/payment_processing_service.py @@ -49,6 +49,10 @@ class PaymentProcessingService: def coupon(self): return self.webhook_service.get_coupon() + @property + def amount(self): + return self.webhook_service.get_final_amount() + def create_transaction(self): """Create a transaction based on webhook data.""" transaction = Transaction.objects.create( @@ -57,7 +61,7 @@ class PaymentProcessingService: transaction_type=TransactionType.PAYMENT, payment_method=PaymentMethod.CARD, transaction_status=TransactionStatus.INITIATE, - amount=self.subscription.amount, + amount=self.amount, order_id=self.order_id, comment="Principal Subscription Initiated", ) diff --git a/goodtimes/webhook/webhook_service.py b/goodtimes/webhook/webhook_service.py index 3b77dfc..cbbadce 100644 --- a/goodtimes/webhook/webhook_service.py +++ b/goodtimes/webhook/webhook_service.py @@ -1,3 +1,4 @@ +from decimal import Decimal from django.conf import settings import stripe from django.core.exceptions import ObjectDoesNotExist @@ -75,3 +76,19 @@ class WebhookService: logger.error(f"Invalid coupon code: {coupon_code}") raise ValueError(f"Invalid coupon code: {coupon_code}") return None + + def get_final_amount(self): + """Retrieve Amount after coupon discount from either stripe event or metadata.""" + if self.event_type == "checkout.session.completed": + return ( + Decimal(self._charge_data.get("amount_total", 0)) / 100 + ) + elif self.event_type == "invoice.payment_succeeded": + return ( + Decimal(self._charge_data.get("amount_paid", 0)) / 100 + ) + + # Fallback: Try to get the amount from metadata + return ( + Decimal(self._metadata.get("metadata", {}).get("finalAmount", 0)) / 100 + ) diff --git a/manage_subscriptions/views.py b/manage_subscriptions/views.py index 8c36f65..b22b7b8 100644 --- a/manage_subscriptions/views.py +++ b/manage_subscriptions/views.py @@ -640,6 +640,7 @@ def validate_coupon(request): data = json.loads(request.body) coupon_code = data.get("couponCode", None) subscription_id = data.get("subscriptionId", None) + final_amount = None try: subscription = Subscription.objects.get(id=subscription_id) @@ -659,6 +660,7 @@ def validate_coupon(request): # Check discount amount if coupon.discount_amount and coupon.discount_amount > subscription.amount: + final_amount = subscription.amount - coupon.discount_amount return JsonResponse( {"error": "Coupon discount amount exceeds subscription amount."}, status=400, @@ -666,23 +668,30 @@ def validate_coupon(request): # Check discount percentage if coupon.discount_percentage: - discount_amount = ( + discount = ( coupon.discount_percentage / Decimal("100") ) * subscription.amount - if discount_amount > subscription.amount: + if discount > subscription.amount: return JsonResponse( { "error": "Coupon discount percentage exceeds subscription amount." }, status=400, ) - + final_amount = subscription.amount - discount # Retrieving coupon from Stripe if applicable if coupon.coupon_id: try: stripe_coupon = stripe.Coupon.retrieve(coupon.coupon_id) print("stripe_coupon: ", stripe_coupon) - return JsonResponse({"data": {"coupon": stripe_coupon}}, status=200) + if ( + stripe_coupon.max_redemptions + and stripe_coupon.times_redeemed >= stripe_coupon.max_redemptions + ): + return JsonResponse( + {"error": "Coupon max redeems reached."}, status=400 + ) + return JsonResponse({"data": {"coupon": stripe_coupon, "finalAmount": final_amount}}, status=200) except stripe.error.InvalidRequestError: return JsonResponse( {"error": f"Invalid coupon code: {coupon_code}"}, status=400 @@ -707,6 +716,7 @@ def create_checkout_session(request): data = json.loads(request.body) subscription_id = data.get("subscriptionId") coupon_code = data.get("couponCode") + transaction_amount = data.get("discountAmount") principal_id = request.user.id try: @@ -724,10 +734,15 @@ def create_checkout_session(request): "success_url": request.build_absolute_uri("/subscriptions/success/"), "cancel_url": request.build_absolute_uri("/subscriptions/cancel/"), "metadata": { + "transaction_amount": str(transaction_amount), "principal": str(request.user.id), "order_id": order_id, "subscription_id": str(subscription.id), - "product_id": str(subscription.stripe_product.product_id if subscription.stripe_product else None), + "product_id": str( + subscription.stripe_product.product_id + if subscription.stripe_product + else None + ), "couponCode": coupon_code if coupon_code else None, }, } diff --git a/templates/stripe_html/index.html b/templates/stripe_html/index.html index d82de43..5acebce 100644 --- a/templates/stripe_html/index.html +++ b/templates/stripe_html/index.html @@ -567,6 +567,8 @@ // Creating checkout session for the selected subscription console.log("Data:", data); console.log("data.coupon:", data.coupon); + const finalAmount = data.finalAmount; + console.log("data.finalAmount:", finalAmount); fetch(stripeFinalUrl, { method: "POST", headers: { @@ -575,7 +577,8 @@ body: JSON.stringify({ subscriptionId: subscriptionId, couponCode: couponCode, - priceId: priceId + priceId: priceId, + discountAmount: discountAmount, }), }) .then((result) => {