auto recurring testing phase 3

This commit is contained in:
rizwanisready
2024-07-31 20:10:21 +05:30
parent e3b86d64fd
commit 31f9e768ea
2 changed files with 72 additions and 65 deletions

View File

@@ -674,13 +674,10 @@ def validate_coupon(request):
@csrf_exempt
@require_POST
def create_checkout_session(request):
success_url = reverse_lazy("manage_subscriptions:stripe")
stripe.api_key = settings.STRIPE_SECRET_KEY
data = json.loads(request.body)
print("data: ", data)
subscription_id = data.get("subscriptionId", None)
coupon_code = data.get("couponCode", None)
print("Initialize coupon_code: ", coupon_code)
subscription_id = data.get("subscriptionId")
coupon_code = data.get("couponCode")
principal_id = request.user.id
try:
@@ -688,89 +685,96 @@ def create_checkout_session(request):
except Subscription.DoesNotExist:
return JsonResponse({"error": "Subscription not found."}, status=404)
order_id = (
"order_" + str(timezone.localtime().timestamp()) + str(request.user.email)
)
print("order_id: ", order_id)
# Calculating the final amount after applying the coupon discount
order_id = f"order_{timezone.localtime().timestamp()}_{request.user.email}"
# Default transaction amount based on subscription amount
final_amount = subscription.amount
print("final_amount before applying coupon: ", final_amount)
coupon = None
session_data = {
"payment_method_types": ["card"],
"success_url": request.build_absolute_uri("/subscriptions/success/"),
"cancel_url": request.build_absolute_uri("/subscriptions/cancel/"),
"metadata": {
"principal": str(request.user.id),
"order_id": order_id,
"subscription_id": str(subscription.id),
"transaction_id": "",
"couponCode": coupon_code if coupon_code else None,
},
}
# Coupon Handling
if coupon_code:
try:
coupon = Coupon.objects.get(coupon_code=coupon_code)
if coupon.is_valid():
if coupon.discount_amount:
final_amount -= coupon.discount_amount
elif coupon.discount_percentage:
final_amount -= final_amount * (
coupon.discount_percentage / Decimal("100")
if coupon.is_valid() and coupon.coupon_id:
# Retrieving the coupon from Stripe
try:
stripe_coupon = stripe.Coupon.retrieve(coupon.coupon_id)
session_data["discounts"] = [{"coupon": stripe_coupon.id}]
except stripe.error.InvalidRequestError:
return JsonResponse(
{"error": f"Invalid coupon code: {coupon_code}"}, status=400
)
except stripe.error.StripeError as e:
return JsonResponse(
{"error": f"Stripe error: {str(e)}"}, status=400
)
final_amount = max(
0, final_amount
) # Ensuring the amount is not negative
print("final_amount after applying coupon: ", final_amount)
else:
return JsonResponse(
{"error": "Invalid or expired coupon code."}, status=400
)
except Coupon.DoesNotExist:
return JsonResponse({"error": "Coupon not found."}, status=404)
print("after coupon try block: ", coupon)
# Create a Transaction object with status INITIATE
transaction = Transaction.objects.create(
principal=request.user,
principal_subscription=None, # Since the subscription is not created yet
transaction_type=TransactionType.PAYMENT, # or PAYMENT, as applicable
payment_method=PaymentMethod.CARD, # Assuming CARD for this example
principal_subscription=None, # Subscription not created yet
transaction_type=TransactionType.PAYMENT,
payment_method=PaymentMethod.CARD,
transaction_status=TransactionStatus.INITIATE,
amount=final_amount, # Fetching amount from the Subscription object
amount=final_amount,
order_id=order_id,
comment="Principal Subscription Initiated",
)
try:
# customer = stripe.Customer.create(
# email=request.user.email,
# shipping={
# "name": request.user.first_name,
# "address": {
# "line1": request.user.city,
# "city": request.user.city,
# "postal_code": "SW1A 2AA",
# "country": request.user.address_line1, # Adjust accordingly
# },
# },
# )
# Updating transaction_id in session_data metadata
session_data["metadata"]["transaction_id"] = str(transaction.id)
# Create a checkout session
checkout_session = stripe.checkout.Session.create(
payment_method_types=["card"],
# customer=customer.id, # Optional: Link the session to the Stripe customer created above
line_items=[
# Creating the Stripe Checkout Session
try:
if subscription.price_id:
session_data["line_items"] = [
{
"price": "price_1PgkAUCesU6kunsI0AwDONty",
"price": subscription.price_id,
"quantity": 1,
}
],
# allow_promotion_codes=True,
# mode="payment",
mode="subscription",
# discounts=[{"coupon": "VLMAsicx"}],
success_url=request.build_absolute_uri("/subscriptions/success/"),
cancel_url=request.build_absolute_uri("/subscriptions/cancel/"),
metadata={
"principal": str(request.user.id),
"order_id": str(order_id),
"subscription_id": str(subscription.id),
"transaction_id": str(transaction.id),
"couponCode": str(coupon.coupon_code) if coupon else None,
# "principal_subscription_id": str(principal_subscription.id),
},
)
]
else:
session_data["line_items"] = [
{
"price_data": {
"currency": "usd",
"product_data": {
"name": subscription.title,
"description": subscription.short_description,
},
"unit_amount": int(
subscription.amount * 100
), # Amount in cents
"recurring": {
"interval": "month", # or 'year', etc.
},
},
"quantity": 1,
}
]
checkout_session = stripe.checkout.Session.create(**session_data)
return JsonResponse({"sessionId": checkout_session["id"]})
except Exception as e:
return JsonResponse({"error": str(e)})
return JsonResponse({"error": str(e)}, status=500)
class SuccessView(TemplateView):

View File

@@ -130,7 +130,7 @@
<div class="Adventure-btn text-center">
<input type="text" placeholder="Enter Coupon Code" class="form-control coupon-code-input" size="20">
<!-- Add a data attribute to store subscription ID -->
<button class="common-btn subscribe-btn" data-subscription-id="{{ subscription.id }}">Join now</button>
<button class="common-btn subscribe-btn" data-subscription-id="{{ subscription.id }}" data-price-id="{{ subscription.price_id }}">Join now</button>
<!-- Error message container -->
<div class="alert alert-danger coupon-error-message mt-2" style="display: none;"></div>
</div>
@@ -535,10 +535,12 @@
document.querySelectorAll(".subscribe-btn").forEach(button => {
button.addEventListener("click", () => {
const subscriptionId = button.getAttribute("data-subscription-id");
const priceId = button.getAttribute("data-price-id");
const couponCode = button.previousElementSibling.value;
const errorMessageContainer = button.nextElementSibling;
console.log("subscriptionId: ", subscriptionId);
console.log("couponCode: ", couponCode);
console.log("priceId: ", priceId);
button.disabled = true;
button.previousElementSibling.value = "";
@@ -570,7 +572,8 @@
},
body: JSON.stringify({
subscriptionId: subscriptionId,
couponCode: couponCode
couponCode: couponCode,
priceId: priceId
}),
})
.then((result) => {