HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/unlimited-leads/Unlimited-Leads-Be/services/stripe/stripe.py
import stripe
from django.conf import settings


stripe.api_key = settings.STRIPE_SECRET_KEY

class StripeUtils:
    # create customer in stripe
    @staticmethod
    def create_customer(name, email):
        try:
            customer = stripe.Customer.create(
                name=name,
                email=email,
            )
            return customer['id']
        except stripe.error.StripeError as e:
            raise Exception(f"Stripe error: {str(e)}")
        
    # create payment intent for one time payment
    @staticmethod
    def create_payment_intent(customer_id, amount, currency="usd", payment_method_types=None, metadata=None):
        if payment_method_types is None:
            # payment_method_types = ['card', 'paypal']
            payment_method_types = ['card']

        try:
            payment_intent = stripe.PaymentIntent.create(
                amount=amount,
                currency=currency,
                customer=customer_id,
                payment_method_types=payment_method_types,
                metadata=metadata if metadata else {} 
            )
            return payment_intent
        except stripe.error.StripeError as e:
            raise Exception(f"Stripe error: {str(e)}")
        
    # create setup intent for subscription
    @staticmethod
    def create_setup_intent(customer_id, payment_method_types=None, usage="off_session"):
        if payment_method_types is None:
            payment_method_types = ['card']

        try:
            setup_intent = stripe.SetupIntent.create(
                customer=customer_id,
                payment_method_types=payment_method_types,
                usage=usage
            )
            return setup_intent
        except stripe.error.StripeError as e:
            raise Exception(f"Stripe error: {str(e)}")

    # cancel a subscription by their subscription_id
    @staticmethod
    def cancel_subscription(subscription_id):
        try:
            subscription = stripe.Subscription.delete(subscription_id)
            return subscription  # Return the full subscription object
        except stripe.error.StripeError as e:
            raise Exception(f"Stripe error: {str(e)}")

    @staticmethod
    def attach_payment_method(payment_method_id, customer_id):
        """
        Attaches a PaymentMethod to a Customer and sets it as the default payment method.
        """
        try:
            # Attach the payment method to the customer
            stripe.PaymentMethod.attach(
                payment_method_id,
                customer=customer_id,
            )
            # Set the payment method as the default for invoices
            stripe.Customer.modify(
                customer_id,
                invoice_settings={
                    'default_payment_method': payment_method_id,
                }
            )
        except stripe.error.StripeError as e:
            raise Exception(f"Stripe error while attaching payment method: {str(e)}")
        
    @staticmethod
    def create_subscription(customer_id, price_id, payment_settings=None):
        """
        Creates a subscription for a customer with the specified price ID.
        """
        return stripe.Subscription.create(
            customer=customer_id,
            items=[{"price": price_id}],
            payment_settings=payment_settings or {
                'payment_method_options': {
                    'card': {
                        'request_three_d_secure': 'automatic',
                    },
                },
                'save_default_payment_method': 'on_subscription',
            },
            # metadata=metadata or {},
            collection_method='charge_automatically',
            off_session=True,
            expand=['latest_invoice.payment_intent'],
        )