diff --git a/goodtimes/webhook/payment_processing_service.py b/goodtimes/webhook/payment_processing_service.py index 30906c8..4d2f7b1 100644 --- a/goodtimes/webhook/payment_processing_service.py +++ b/goodtimes/webhook/payment_processing_service.py @@ -22,6 +22,7 @@ class PaymentProcessingService: current_period_end, ): self.webhook_service = WebhookService(webhook_data) + self._order_id = None self.notification_service = NotificationService() self.subscription_service = SubscriptionService() self.stripe_subscription = stripe_subscription @@ -45,8 +46,13 @@ class PaymentProcessingService: @property def order_id(self): - """Return the order ID from the webhook service.""" - return self.webhook_service.get_order_id() + """Return the order ID from the created transaction.""" + return self._order_id + + @order_id.setter + def order_id(self, value): + """Set the order ID.""" + self._order_id = value @property def coupon(self): @@ -60,47 +66,52 @@ class PaymentProcessingService: def create_transaction(self): """Create a transaction based on webhook data.""" - return Transaction.objects.create( + transaction = Transaction.objects.create( principal=self.principal, principal_subscription=None, transaction_type=TransactionType.PAYMENT, payment_method=PaymentMethod.CARD, transaction_status=TransactionStatus.INITIATE, amount=self.amount, - order_id=self.order_id, + # order_id=self.order_id, comment="Principal Subscription Initiated", ) + # Save the transaction to auto-generate the order_id + transaction.save() + + # Step 1: Update the order_id in PaymentProcessingService + self.order_id = transaction.order_id + + return transaction def process_event(self): """Process the webhook event.""" - with transaction.atomic(): - event_type = self.webhook_service.event_type - try: - if event_type == "invoice.payment_succeeded": - if self.charge_data.get("billing_reason") != "subscription_create": - txn = self.create_transaction() - self.handle_success(txn) - elif event_type == "checkout.session.completed": - txn = self.create_transaction() + try: + with transaction.atomic(): + event_type = self.webhook_service.event_type + if event_type == "invoice.payment_succeeded" and self.charge_data.get("billing_reason") == "subscription_create": + logger.info(f"Skipping event {event_type} with billing reason 'subscription_create'") + return + + txn = self.create_transaction() + + if event_type in ["checkout.session.completed", "invoice.payment_succeeded"]: self.handle_success(txn) elif event_type in ["checkout.session.expired", "invoice.payment_failed"]: - order_id = self.order_id - try: - txn = Transaction.objects.get(order_id=order_id) - txn.transaction_status = TransactionStatus.FAIL - txn.save() - return - except Transaction.DoesNotExist: - txn = self.create_transaction() self.handle_failure(txn) - except Exception as e: - logger.error(f"Transaction Error: {str(e)}") - raise e + else: + logger.warning(f"Unknown event type {event_type}. Skipping.") + return + + except Exception as e: + logger.error(f"Unexpected error: {str(e)}") + self.handle_failure(txn) + raise def handle_success(self, transaction): """Handle a successful payment.""" try: - self.create_principal_subscription() + self.create_principal_subscription(transaction) self.process_referral_rewards() self.send_success_notification(transaction) self.update_transaction_status( @@ -113,14 +124,14 @@ class PaymentProcessingService: logger.error(f"Transaction Error: {str(e)}") raise e - def create_principal_subscription(self): + def create_principal_subscription(self, transaction): """Create or update the principal subscription.""" self.subscription_service.principal_subscription = ( self.subscription_service.create_principal_subscription( principal=self.principal, subscription=self.subscription, stripe_subscription=self.stripe_subscription, - order_id=self.order_id, + order_id=transaction.order_id, current_period_start=self.current_period_start, current_period_end=self.current_period_end, coupon=self.coupon, diff --git a/goodtimes/webhook/webhook_service.py b/goodtimes/webhook/webhook_service.py index cbbadce..ba8cd4f 100644 --- a/goodtimes/webhook/webhook_service.py +++ b/goodtimes/webhook/webhook_service.py @@ -61,10 +61,6 @@ class WebhookService: """Retrieve subscription from metadata.""" return self._get_object_from_metadata(Subscription, "subscription_id") - def get_order_id(self): - """Retrieve order ID from metadata.""" - return self._metadata.get("order_id") - def get_coupon(self): """Retrieve coupon from metadata.""" coupon_code = self._metadata.get("couponCode") diff --git a/manage_subscriptions/views.py b/manage_subscriptions/views.py index 9a8eea7..57a32eb 100644 --- a/manage_subscriptions/views.py +++ b/manage_subscriptions/views.py @@ -848,8 +848,6 @@ def create_checkout_session(request): except Subscription.DoesNotExist: return JsonResponse({"error": "Subscription not found."}, status=404) - order_id = f"order_{timezone.localtime().timestamp()}_{request.user.email}" - # Default transaction amount based on subscription amount print("Before Session Data") session_data = { @@ -859,7 +857,6 @@ def create_checkout_session(request): "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