48 lines
1.7 KiB
Python
48 lines
1.7 KiB
Python
import stripe
|
|
from decimal import Decimal
|
|
|
|
|
|
def handle_stripe_coupon(coupon_instance, stripe_secret_key):
|
|
"""
|
|
Handles the creation or updating of a Stripe coupon.
|
|
Returns True if successful, otherwise returns False.
|
|
"""
|
|
try:
|
|
stripe.api_key = stripe_secret_key
|
|
|
|
# Prepare coupon data without setting the ID
|
|
coupon_data = {
|
|
"name": coupon_instance.title,
|
|
"metadata": {
|
|
"local_id": coupon_instance.id,
|
|
},
|
|
"redeem_by": int(coupon_instance.valid_to.timestamp()),
|
|
"max_redemptions": (
|
|
coupon_instance.max_redeems if coupon_instance.max_redeems > 0 else None
|
|
),
|
|
"duration": "once",
|
|
}
|
|
|
|
if coupon_instance.discount_amount:
|
|
coupon_data["amount_off"] = int(
|
|
coupon_instance.discount_amount * Decimal(100)
|
|
) # Amount in cents/fils
|
|
coupon_data["currency"] = "gbp"
|
|
elif coupon_instance.discount_percentage:
|
|
coupon_data["percent_off"] = float(coupon_instance.discount_percentage)
|
|
|
|
# Creating a new Stripe coupon
|
|
stripe_coupon = stripe.Coupon.create(**coupon_data)
|
|
# Using the Stripe-generated ID for coupon_code and coupon_id
|
|
coupon_instance.coupon_code = stripe_coupon.id
|
|
coupon_instance.coupon_id = stripe_coupon.id
|
|
|
|
# Saving the coupon instance after successful Stripe operation
|
|
coupon_instance.save()
|
|
return True, "Coupon successfully created."
|
|
|
|
except Exception as e:
|
|
error_message = f"Error creating Stripe coupon: {e}"
|
|
print(error_message)
|
|
return False, error_message
|