FInal bank, stripe and paypal sandbox completed

This commit is contained in:
IGNY8 VPS (Salman)
2026-01-08 00:12:41 +00:00
parent ad75fa031e
commit 7ad1f6bdff
19 changed files with 2622 additions and 375 deletions

View File

@@ -5,6 +5,8 @@ API endpoints for generating and downloading invoice PDFs
from django.http import HttpResponse
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from igny8_core.business.billing.models import Invoice
from igny8_core.business.billing.services.pdf_service import InvoicePDFGenerator
from igny8_core.business.billing.utils.errors import not_found_response
@@ -22,20 +24,46 @@ def download_invoice_pdf(request, invoice_id):
GET /api/v1/billing/invoices/<id>/pdf/
"""
try:
invoice = Invoice.objects.prefetch_related('line_items').get(
# Note: line_items is a JSONField, not a related model - no prefetch needed
invoice = Invoice.objects.select_related('account', 'account__owner', 'subscription', 'subscription__plan').get(
id=invoice_id,
account=request.user.account
)
except Invoice.DoesNotExist:
return not_found_response('Invoice', invoice_id)
# Generate PDF
pdf_buffer = InvoicePDFGenerator.generate_invoice_pdf(invoice)
# Return PDF response
response = HttpResponse(pdf_buffer.read(), content_type='application/pdf')
response['Content-Disposition'] = f'attachment; filename="invoice_{invoice.invoice_number}.pdf"'
logger.info(f'Invoice PDF downloaded: {invoice.invoice_number} by user {request.user.id}')
return response
try:
# Generate PDF
pdf_buffer = InvoicePDFGenerator.generate_invoice_pdf(invoice)
# Build descriptive filename: IGNY8-Invoice-INV123456-Growth-2026-01-08.pdf
plan_name = ''
if invoice.subscription and invoice.subscription.plan:
plan_name = invoice.subscription.plan.name.replace(' ', '-')
elif invoice.metadata and 'plan_name' in invoice.metadata:
plan_name = invoice.metadata['plan_name'].replace(' ', '-')
date_str = invoice.invoice_date.strftime('%Y-%m-%d') if invoice.invoice_date else ''
filename_parts = ['IGNY8', 'Invoice', invoice.invoice_number]
if plan_name:
filename_parts.append(plan_name)
if date_str:
filename_parts.append(date_str)
filename = '-'.join(filename_parts) + '.pdf'
# Return PDF response
response = HttpResponse(pdf_buffer.read(), content_type='application/pdf')
response['Content-Disposition'] = f'attachment; filename="{filename}"'
logger.info(f'Invoice PDF downloaded: {invoice.invoice_number} by user {request.user.id}')
return response
except Exception as e:
logger.error(f'Failed to generate PDF for invoice {invoice_id}: {str(e)}', exc_info=True)
return Response(
{'error': 'Failed to generate PDF', 'detail': str(e)},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)

View File

@@ -20,6 +20,7 @@ Endpoints:
import json
import logging
from decimal import Decimal
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from django.db import transaction
@@ -33,7 +34,7 @@ from rest_framework import status
from igny8_core.api.response import success_response, error_response
from igny8_core.api.permissions import IsAuthenticatedAndActive
from igny8_core.auth.models import Plan, Account, Subscription
from ..models import CreditPackage, Payment, Invoice, CreditTransaction
from ..models import CreditPackage, Payment, Invoice, CreditTransaction, WebhookEvent
from ..services.paypal_service import PayPalService, PayPalConfigurationError, PayPalAPIError
from ..services.invoice_service import InvoiceService
from ..services.credit_service import CreditService
@@ -530,28 +531,50 @@ def paypal_webhook(request):
# Process event
event_type = body.get('event_type', '')
resource = body.get('resource', {})
event_id = body.get('id', '')
logger.info(f"PayPal webhook received: {event_type}")
logger.info(f"PayPal webhook received: {event_type} (ID: {event_id})")
# Store webhook event for audit trail
webhook_event, created = WebhookEvent.record_event(
event_id=event_id,
provider='paypal',
event_type=event_type,
payload=body
)
if not created:
logger.info(f"Duplicate PayPal webhook event {event_id}, skipping")
return Response({'status': 'duplicate'})
if event_type == 'CHECKOUT.ORDER.APPROVED':
_handle_order_approved(resource)
elif event_type == 'PAYMENT.CAPTURE.COMPLETED':
_handle_capture_completed(resource)
elif event_type == 'PAYMENT.CAPTURE.DENIED':
_handle_capture_denied(resource)
elif event_type == 'BILLING.SUBSCRIPTION.ACTIVATED':
_handle_subscription_activated(resource)
elif event_type == 'BILLING.SUBSCRIPTION.CANCELLED':
_handle_subscription_cancelled(resource)
elif event_type == 'BILLING.SUBSCRIPTION.SUSPENDED':
_handle_subscription_suspended(resource)
elif event_type == 'BILLING.SUBSCRIPTION.PAYMENT.FAILED':
_handle_subscription_payment_failed(resource)
else:
logger.info(f"Unhandled PayPal event type: {event_type}")
return Response({'status': 'success'})
try:
if event_type == 'CHECKOUT.ORDER.APPROVED':
_handle_order_approved(resource)
elif event_type == 'PAYMENT.CAPTURE.COMPLETED':
_handle_capture_completed(resource)
elif event_type == 'PAYMENT.CAPTURE.DENIED':
_handle_capture_denied(resource)
elif event_type == 'BILLING.SUBSCRIPTION.ACTIVATED':
_handle_subscription_activated(resource)
elif event_type == 'BILLING.SUBSCRIPTION.CANCELLED':
_handle_subscription_cancelled(resource)
elif event_type == 'BILLING.SUBSCRIPTION.SUSPENDED':
_handle_subscription_suspended(resource)
elif event_type == 'BILLING.SUBSCRIPTION.PAYMENT.FAILED':
_handle_subscription_payment_failed(resource)
else:
logger.info(f"Unhandled PayPal event type: {event_type}")
# Mark webhook as successfully processed
webhook_event.mark_processed()
return Response({'status': 'success'})
except Exception as e:
logger.exception(f"Error processing PayPal webhook {event_type}: {e}")
# Mark webhook as failed
webhook_event.mark_failed(str(e))
return Response({'status': 'error', 'message': str(e)})
except Exception as e:
logger.exception(f"Error processing PayPal webhook: {e}")
return Response({'status': 'error', 'message': str(e)})
@@ -706,25 +729,30 @@ def _process_subscription_payment(account, plan_id: str, capture_result: dict) -
# Update/create AccountPaymentMethod and mark as verified
from ..models import AccountPaymentMethod
# Get country code from account billing info
country_code = account.billing_country if account.billing_country else ''
AccountPaymentMethod.objects.update_or_create(
# First, clear default from ALL existing payment methods for this account
AccountPaymentMethod.objects.filter(account=account).update(is_default=False)
# Delete any existing PayPal payment method to avoid conflicts
AccountPaymentMethod.objects.filter(account=account, type='paypal').delete()
# Create fresh PayPal payment method
AccountPaymentMethod.objects.create(
account=account,
type='paypal',
defaults={
'display_name': 'PayPal',
'is_default': True,
'is_enabled': True,
'is_verified': True, # Mark verified after successful payment
'country_code': country_code, # Set country from account billing info
'metadata': {
'last_payment_at': timezone.now().isoformat(),
'paypal_order_id': capture_result.get('order_id'),
}
display_name='PayPal',
is_default=True,
is_enabled=True,
is_verified=True, # Mark verified after successful payment
country_code=country_code, # Set country from account billing info
metadata={
'last_payment_at': timezone.now().isoformat(),
'paypal_order_id': capture_result.get('order_id'),
}
)
# Set other payment methods as non-default
AccountPaymentMethod.objects.filter(account=account).exclude(type='paypal').update(is_default=False)
# Add subscription credits
if plan.included_credits and plan.included_credits > 0:
@@ -739,7 +767,7 @@ def _process_subscription_payment(account, plan_id: str, capture_result: dict) -
}
)
# Update account status AND plan (like Stripe flow)
# Update account status, plan, AND payment_method (like Stripe flow)
update_fields = ['updated_at']
if account.status != 'active':
account.status = 'active'
@@ -747,6 +775,10 @@ def _process_subscription_payment(account, plan_id: str, capture_result: dict) -
if account.plan_id != plan.id:
account.plan = plan
update_fields.append('plan')
# Always update payment_method to paypal after successful PayPal payment
if account.payment_method != 'paypal':
account.payment_method = 'paypal'
update_fields.append('payment_method')
account.save(update_fields=update_fields)
logger.info(
@@ -872,10 +904,16 @@ def _handle_subscription_activated(resource: dict):
description=f'PayPal Subscription: {plan.name}',
)
# Activate account
# Activate account and set payment method
update_fields = ['updated_at']
if account.status != 'active':
account.status = 'active'
account.save(update_fields=['status', 'updated_at'])
update_fields.append('status')
if account.payment_method != 'paypal':
account.payment_method = 'paypal'
update_fields.append('payment_method')
if update_fields != ['updated_at']:
account.save(update_fields=update_fields)
except Account.DoesNotExist:
logger.error(f"Account {custom_id} not found for PayPal subscription activation")
@@ -939,3 +977,106 @@ def _handle_subscription_payment_failed(resource: dict):
except Subscription.DoesNotExist:
pass
class PayPalReturnVerificationView(APIView):
"""
Verify PayPal payment on return from PayPal approval page.
Maps PayPal token to order_id and checks payment status.
"""
permission_classes = [IsAuthenticated]
def get(self, request):
"""
Verify PayPal order status and return order_id for capture.
Query params:
- token: PayPal token from return URL (EC-xxx)
Returns order_id so frontend can call capture endpoint.
"""
token = request.query_params.get('token')
if not token:
return Response({
'error': 'token parameter is required'
}, status=status.HTTP_400_BAD_REQUEST)
account = request.user.account
try:
# Get PayPal service
service = PayPalService()
# Get order details from PayPal using token
# Unfortunately, PayPal doesn't have a direct token->order_id API
# So we need to store order_id before redirect, or use token as reference
# Check if we have a recent Payment record with this token in metadata
recent_payment = Payment.objects.filter(
account=account,
payment_method='paypal',
created_at__gte=timezone.now() - timedelta(hours=1),
metadata__icontains=token
).first()
if recent_payment and recent_payment.paypal_order_id:
order_id = recent_payment.paypal_order_id
else:
# Try to find order_id from token (stored in session/localStorage)
# This is why we need localStorage approach in frontend
return Response({
'error': 'order_id_not_found',
'message': 'Could not map PayPal token to order. Please try again.',
'token': token
}, status=status.HTTP_404_NOT_FOUND)
# Get order status from PayPal
order_details = service.get_order(order_id)
order_status = order_details.get('status') # 'CREATED', 'APPROVED', 'COMPLETED'
# Check if already captured
already_captured = Payment.objects.filter(
account=account,
paypal_order_id=order_id,
status='succeeded'
).exists()
response_data = {
'token': token,
'order_id': order_id,
'order_status': order_status,
'already_captured': already_captured,
'account_status': account.status,
'message': self._get_status_message(order_status, already_captured)
}
# If approved but not captured, return order_id for frontend to capture
if order_status == 'APPROVED' and not already_captured:
response_data['ready_to_capture'] = True
return Response(response_data)
except PayPalConfigurationError as e:
return Response({
'error': 'PayPal not configured',
'detail': str(e)
}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
except Exception as e:
logger.error(f"Error verifying PayPal return: {e}")
return Response({
'error': 'Failed to verify PayPal payment',
'detail': str(e)
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def _get_status_message(self, order_status: str, already_captured: bool) -> str:
"""Get user-friendly status message"""
if order_status == 'COMPLETED' or already_captured:
return 'Payment successful! Your account has been activated.'
elif order_status == 'APPROVED':
return 'Payment approved! Completing your order...'
elif order_status == 'CREATED':
return 'Payment not approved yet. Please complete payment on PayPal.'
else:
return f'Payment status: {order_status}. Please contact support if you were charged.'

View File

@@ -23,7 +23,7 @@ from rest_framework import status
from igny8_core.api.response import success_response, error_response
from igny8_core.api.permissions import IsAuthenticatedAndActive
from igny8_core.auth.models import Plan, Account, Subscription
from ..models import CreditPackage, Payment, Invoice, CreditTransaction
from ..models import CreditPackage, Payment, Invoice, CreditTransaction, WebhookEvent
from ..services.stripe_service import StripeService, StripeConfigurationError
from ..services.payment_service import PaymentService
from ..services.invoice_service import InvoiceService
@@ -324,8 +324,21 @@ def stripe_webhook(request):
event_type = event['type']
data = event['data']['object']
event_id = event.get('id', '')
logger.info(f"Stripe webhook received: {event_type}")
logger.info(f"Stripe webhook received: {event_type} (ID: {event_id})")
# Store webhook event for audit trail
webhook_event, created = WebhookEvent.record_event(
event_id=event_id,
provider='stripe',
event_type=event_type,
payload=dict(event)
)
if not created:
logger.info(f"Duplicate Stripe webhook event {event_id}, skipping")
return Response({'status': 'duplicate'})
try:
if event_type == 'checkout.session.completed':
@@ -340,11 +353,15 @@ def stripe_webhook(request):
_handle_subscription_deleted(data)
else:
logger.info(f"Unhandled Stripe event type: {event_type}")
# Mark webhook as successfully processed
webhook_event.mark_processed()
return Response({'status': 'success'})
except Exception as e:
logger.exception(f"Error processing Stripe webhook {event_type}: {e}")
# Mark webhook as failed
webhook_event.mark_failed(str(e))
# Return 200 to prevent Stripe retries for application errors
# Log the error for debugging
return Response({'status': 'error', 'message': str(e)})
@@ -531,25 +548,33 @@ def _activate_subscription(account, stripe_subscription_id: str, plan_id: str, s
# Update/create AccountPaymentMethod and mark as verified
from ..models import AccountPaymentMethod
from django.db import transaction
# Get country code from account billing info
country_code = account.billing_country if account.billing_country else ''
AccountPaymentMethod.objects.update_or_create(
account=account,
type='stripe',
defaults={
'display_name': 'Credit/Debit Card (Stripe)',
'is_default': True,
'is_enabled': True,
'is_verified': True, # Mark verified after successful payment
'country_code': country_code, # Set country from account billing info
'metadata': {
# Use atomic transaction to ensure consistency
with transaction.atomic():
# First, clear default from ALL existing payment methods for this account
AccountPaymentMethod.objects.filter(account=account).update(is_default=False)
# Delete any existing stripe payment method to avoid conflicts
AccountPaymentMethod.objects.filter(account=account, type='stripe').delete()
# Create fresh Stripe payment method
AccountPaymentMethod.objects.create(
account=account,
type='stripe',
display_name='Credit/Debit Card (Stripe)',
is_default=True,
is_enabled=True,
is_verified=True,
country_code=country_code,
metadata={
'last_payment_at': timezone.now().isoformat(),
'stripe_subscription_id': stripe_subscription_id,
}
}
)
# Set other payment methods as non-default
AccountPaymentMethod.objects.filter(account=account).exclude(type='stripe').update(is_default=False)
)
# Add initial credits from plan
if plan.included_credits and plan.included_credits > 0:
@@ -572,6 +597,10 @@ def _activate_subscription(account, stripe_subscription_id: str, plan_id: str, s
if account.plan_id != plan.id:
account.plan = plan
update_fields.append('plan')
# Always update payment_method to stripe after successful Stripe payment
if account.payment_method != 'stripe':
account.payment_method = 'stripe'
update_fields.append('payment_method')
account.save(update_fields=update_fields)
logger.info(
@@ -808,3 +837,163 @@ def _handle_subscription_deleted(subscription_data: dict):
except Subscription.DoesNotExist:
logger.warning(f"Subscription not found for deletion: {subscription_id}")
class StripeReturnVerificationView(APIView):
"""
Verify Stripe payment on return from checkout.
Frontend calls this when user returns from Stripe to get updated account status.
"""
permission_classes = [IsAuthenticated]
def get(self, request):
"""
Verify Stripe checkout session and return current account/subscription status.
Query params:
- session_id: Stripe checkout session ID
Returns updated account data so frontend can immediately show activation.
"""
session_id = request.query_params.get('session_id')
logger.info(f"[STRIPE-VERIFY] ========== VERIFICATION REQUEST ==========")
logger.info(f"[STRIPE-VERIFY] Session ID: {session_id}")
logger.info(f"[STRIPE-VERIFY] User: {request.user.email if request.user else 'Anonymous'}")
logger.info(f"[STRIPE-VERIFY] User ID: {request.user.id if request.user else 'N/A'}")
if not session_id:
logger.warning(f"[STRIPE-VERIFY] ❌ Missing session_id parameter")
return Response({
'error': 'session_id parameter is required'
}, status=status.HTTP_400_BAD_REQUEST)
account = request.user.account
logger.info(f"[STRIPE-VERIFY] Account: {account.name if account else 'No Account'}")
logger.info(f"[STRIPE-VERIFY] Account ID: {account.id if account else 'N/A'}")
logger.info(f"[STRIPE-VERIFY] Account Status: {account.status if account else 'N/A'}")
logger.info(f"[STRIPE-VERIFY] Stripe Customer ID: {account.stripe_customer_id if account else 'N/A'}")
try:
# Initialize Stripe service to get proper API key from IntegrationProvider
logger.info(f"[STRIPE-VERIFY] Initializing StripeService...")
service = StripeService()
logger.info(f"[STRIPE-VERIFY] ✓ StripeService initialized (sandbox={service.is_sandbox})")
# Retrieve session from Stripe to check payment status
# Pass api_key explicitly to ensure it's used
logger.info(f"[STRIPE-VERIFY] Retrieving checkout session from Stripe...")
session = stripe.checkout.Session.retrieve(
session_id,
api_key=service.provider.api_secret
)
logger.info(f"[STRIPE-VERIFY] ✓ Session retrieved successfully")
payment_status = session.get('payment_status') # 'paid', 'unpaid', 'no_payment_required'
customer_id = session.get('customer')
subscription_id = session.get('subscription')
mode = session.get('mode')
logger.info(f"[STRIPE-VERIFY] ===== STRIPE SESSION DATA =====")
logger.info(f"[STRIPE-VERIFY] payment_status: {payment_status}")
logger.info(f"[STRIPE-VERIFY] mode: {mode}")
logger.info(f"[STRIPE-VERIFY] customer: {customer_id}")
logger.info(f"[STRIPE-VERIFY] subscription: {subscription_id}")
logger.info(f"[STRIPE-VERIFY] amount_total: {session.get('amount_total')}")
logger.info(f"[STRIPE-VERIFY] currency: {session.get('currency')}")
logger.info(f"[STRIPE-VERIFY] metadata: {session.get('metadata', {})}")
# Check if webhook has processed this payment yet
logger.info(f"[STRIPE-VERIFY] Checking if payment record exists...")
# Note: metadata key is 'checkout_session_id' not 'stripe_checkout_session_id'
payment_exists = Payment.objects.filter(
account=account,
metadata__checkout_session_id=session_id
)
payment_record_exists = payment_exists.exists()
# IMPORTANT: Also check account status - if account is active, payment was processed
# This handles cases where payment record lookup fails but webhook succeeded
account_is_active = account.status == 'active'
payment_processed = payment_record_exists or (payment_status == 'paid' and account_is_active)
logger.info(f"[STRIPE-VERIFY] ===== DATABASE STATE =====")
logger.info(f"[STRIPE-VERIFY] Payment record exists: {payment_record_exists}")
logger.info(f"[STRIPE-VERIFY] Account is active: {account_is_active}")
logger.info(f"[STRIPE-VERIFY] payment_processed (combined): {payment_processed}")
if payment_record_exists:
payment = payment_exists.first()
logger.info(f"[STRIPE-VERIFY] Payment ID: {payment.id}")
logger.info(f"[STRIPE-VERIFY] Payment status: {payment.status}")
logger.info(f"[STRIPE-VERIFY] Payment amount: {payment.amount}")
# Get current subscription status
subscription = Subscription.objects.filter(account=account).order_by('-created_at').first()
logger.info(f"[STRIPE-VERIFY] Subscription exists: {subscription is not None}")
if subscription:
logger.info(f"[STRIPE-VERIFY] Subscription ID: {subscription.id}")
logger.info(f"[STRIPE-VERIFY] Subscription status: {subscription.status}")
logger.info(f"[STRIPE-VERIFY] Subscription plan: {subscription.plan.name if subscription.plan else 'N/A'}")
# Check invoices
from ..models import Invoice
recent_invoices = Invoice.objects.filter(account=account).order_by('-created_at')[:3]
logger.info(f"[STRIPE-VERIFY] Recent invoices count: {recent_invoices.count()}")
for inv in recent_invoices:
logger.info(f"[STRIPE-VERIFY] Invoice {inv.id}: status={inv.status}, amount={inv.total_amount}")
response_data = {
'session_id': session_id,
'payment_status': payment_status,
'payment_processed': payment_processed,
'account_status': account.status,
'subscription_status': subscription.status if subscription else None,
'message': self._get_status_message(payment_status, payment_processed)
}
# Only poll if payment is paid but account is NOT yet active
# If account is already active, no need to poll - we're done!
if payment_status == 'paid' and not account_is_active:
response_data['should_poll'] = True
response_data['poll_interval_ms'] = 1000 # Poll every second
logger.info(f"[STRIPE-VERIFY] ⏳ Payment paid but account not active yet, should_poll=True")
elif payment_status == 'paid' and account_is_active:
logger.info(f"[STRIPE-VERIFY] ✓ Payment paid AND account active - no polling needed")
logger.info(f"[STRIPE-VERIFY] ===== RESPONSE =====")
logger.info(f"[STRIPE-VERIFY] {response_data}")
logger.info(f"[STRIPE-VERIFY] ========== END VERIFICATION ==========")
return Response(response_data)
except StripeConfigurationError as e:
logger.error(f"Stripe not configured: {e}")
return Response({
'error': 'Stripe payment gateway not configured',
'detail': str(e)
}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
except stripe.error.StripeError as e:
logger.error(f"Stripe error verifying session {session_id}: {e}")
return Response({
'error': 'Failed to verify payment with Stripe',
'detail': str(e)
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
except Exception as e:
logger.error(f"Error verifying Stripe return: {e}")
return Response({
'error': 'Failed to verify payment status',
'detail': str(e)
}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def _get_status_message(self, payment_status: str, payment_processed: bool) -> str:
"""Get user-friendly status message"""
if payment_status == 'paid':
if payment_processed:
return 'Payment successful! Your account has been activated.'
else:
return 'Payment received! Processing your subscription...'
elif payment_status == 'unpaid':
return 'Payment not completed. Please try again.'
else:
return 'Payment status unknown. Please contact support if you were charged.'