refactored webhook realted to coupon

This commit is contained in:
rizwanisready
2024-08-05 18:40:34 +05:30
parent 85767e7b96
commit 73ca0ea974
9 changed files with 536 additions and 411 deletions

View File

@@ -7,9 +7,7 @@ from rest_framework import status
from rest_framework.views import APIView
from django.conf import settings
import stripe
from accounts.models import IAmPrincipal
import json
from goodtimes import constants, services
from goodtimes import constants
from manage_subscriptions.models import (
Subscription,
PrincipalSubscription,
@@ -35,7 +33,11 @@ from .serializers import PrincipalSubscriptionSerializer
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from rest_framework.response import Response
from goodtimes.webhook import PaymentProcessingService
from goodtimes.webhook.payment_processing_service import PaymentProcessingService
import logging
logger = logging.getLogger(__name__)
class CreatePrincipalSubscriptionApi(APIView):
@@ -175,25 +177,32 @@ class StripeWebhookTest(APIView):
endpoint_secret = "whsec_ccf1f87295603cdd1733995ee2d3c0d6f74c7ceaf28916ea45114a54b7ce1d0f" # Make sure to retrieve this from your settings
event = None
try:
event = stripe.Event.construct_from(json.loads(payload), stripe.api_key)
event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret)
event_id = event["id"]
event_type = event["type"]
# principal_id = event["data"]["object"]["metadata"]["principal"]
stripe_subscription_id = event["data"]["object"].get("subscription")
if stripe_subscription_id:
stripe_subscription = stripe.Subscription.retrieve(stripe_subscription_id)
current_period_start = stripe_subscription["current_period_start"]
current_period_end = stripe_subscription["current_period_end"]
else:
current_period_start = None
current_period_end = None
stripe_subscription = (
stripe.Subscription.retrieve(stripe_subscription_id)
if stripe_subscription_id
else None
)
current_period_start = (
stripe_subscription["current_period_start"]
if stripe_subscription
else None
)
current_period_end = (
stripe_subscription["current_period_end"]
if stripe_subscription
else None
)
webhook_event, created = WebhookEvent.objects.get_or_create(
event_id=event_id,
defaults={
"event_type": event_type,
"event_payload": json.loads(payload),
"event_payload": event,
},
)
@@ -209,53 +218,59 @@ class StripeWebhookTest(APIView):
current_period_start=current_period_start,
current_period_end=current_period_end,
)
payment_service.process_event()
webhook_event = WebhookEvent.objects.get(event_id=event_id)
transaction = payment_service.create_transaction()
try:
payment_service.process_event(transaction)
transaction.transaction_status = TransactionStatus.SUCCESS
except Exception as e:
transaction.transaction_status = TransactionStatus.FAIL
transaction.error_message = str(e)
logger.error(f"Transaction Error: {str(e)}")
raise e
finally:
transaction.save()
webhook_event.status = "processed"
webhook_event.processed_at = timezone.now() # Make sure to import timezone
webhook_event.processed_at = timezone.now()
webhook_event.save()
return ApiResponse.success(
status=status.HTTP_200_OK, message="Event processed successfully"
)
except ValueError as e:
# Invalid payload
return ApiResponse.error(
status=status.HTTP_400_BAD_REQUEST,
message="Invalid payload",
errors=str(e),
)
except stripe.error.SignatureVerificationError as e:
# Invalid signature
logger.error(f"Invalid Stripe signature: {str(e)}")
return ApiResponse.error(
status=status.HTTP_400_BAD_REQUEST,
message="Invalid signature",
errors=str(e),
)
except Transaction.DoesNotExist:
# Handle case where the transaction does not exist
except ValueError as e:
logger.error(f"Invalid payload: {str(e)}")
return ApiResponse.error(
status=status.HTTP_404_NOT_FOUND, message="Transaction not found"
status=status.HTTP_400_BAD_REQUEST,
message="Invalid payload",
errors=str(e),
)
except Transaction.DoesNotExist as e:
logger.error(f"Transaction does not exist: {str(e)}")
return ApiResponse.error(
status=status.HTTP_404_NOT_FOUND,
message="Transaction not found",
errors=str(e),
)
except Exception as e:
webhook_event.status = "failed"
webhook_event.error_message = str(e)
webhook_event.save()
logger.error(f"Error processing webhook event: {str(e)}")
if "webhook_event" in locals():
webhook_event.status = "failed"
webhook_event.error_message = str(e)
webhook_event.save()
return ApiResponse.error(
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
message="Error processing event",
errors=str(e),
)
def _has_active_principal_subscription(self, principal_id):
return PrincipalSubscription.objects.filter(
principal__id=principal_id,
active=True,
deleted=False,
is_paid=True,
end_date__gte=timezone.now().date(),
).exists()
class LastActiveSubscriptionView(APIView):
authentication_classes = [JWTAuthentication]