Stripe split payment Django

34 Views Asked by At

I am working on a project where i have to split the payments for that i have connected the customer to the stripe and retrieved the stripe account number for the same

class AuctionPayment(View):
    def get(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return redirect('/')
        else:
            user = request.user
            customer_id = user.stripe_customer_id
            if customer_id == "":
                customer_id = stripe.Customer.create(email=user.email)["id"]
                user.stripe_customer_id = customer_id
                user.save()
        mode = request.GET.get('mode', 'auction')
        auction_id = self.kwargs["auction_id"]
        courier_id = self.kwargs["courier_id"]
        if mode == 'auction':
            auction = Auction.objects.get(pk=auction_id)
            seller_id =  auction.user
            seller_account_id = seller_id.stripe_connect_id
            print("-------------------------------------------------", seller_id ,  seller_account_id)
            referrals = Referral.objects.filter(referred_user=seller_id).first()
            referred_by =  referrals.referred_by
            print("----------------------------------------------------refered_by ", referred_by)
            courier = CourierService.objects.get(auction=auction, courier_id=courier_id)
            
            if auction.current_bid is not None:
                price = int(round(float(auction.current_bid) * 100.0))
            if auction.auction_status == "Ongoing":
                price = int(round(float(auction.product.nail_buy_now_price) * 100.0))
            buyer_address = auction.buyer_address
        else:
            event = SpecialEvent.objects.get(pk=auction_id)
            courier = CourierService.objects.get(event=event, courier_id=courier_id)
            seller = event.selected_seller
            seller_request = SellerRequest.objects.get(event=event, user=seller)
            price = int(round(float(seller_request.price) * 100.0))
            buyer_address = event.buyer_address
        taxes = 0
        if buyer_address.state.lower() == 'alabama' or buyer_address.state.lower() == 'al':
            taxes = int(round(float(price * 0.08)))
        shipping_charges = courier.price
        total_charges = price + shipping_charges + taxes
        # if referrals:
        admin_amount = int((total_charges - shipping_charges) * 0.2)
        seller_amount = total_charges - admin_amount
        referral_amount = int(admin_amount * 0.02)
        stripe.api_key = "api_key"
        session = stripe.checkout.Session.create(
            success_url=my_domain + '/payment_success/' + str(auction_id) + '/' + courier_id + "?mode=" + mode,
            cancel_url=my_domain + '/payment_failed/' + str(auction_id) + '/' + courier_id + "?mode=" + mode,
            mode='payment',
            payment_method_types=['card'],
            line_items=[{
                'price_data': {
                    'currency': 'usd',
                    'product_data': {
                        'name': 'NailSent Nails',
                    },
                    'unit_amount': total_charges,
                },
                'quantity': 1,
            }],
            customer=request.user.stripe_customer_id,
            payment_intent_data={
                'transfer_data': {
                    'destination': seller_account_id,
                    'amount': seller_amount,
                },
            },
           
        )
        stripe.Transfer.create(
            amount=2000,
            currency="usd",
            destination="acct_1OrzPRI5g3KKKWKv",
            transfer_group="nailSent referal reward",
            )
        # try:
        #     stripe.Transfer.create(
        #         amount=referral_amount,
        #         currency="usd",
        #         destination="connect_account_id_of_referral",
        #         source_transaction=session.payment_intent,
        #         transfer_group="NailSent_Nails_Referral_Transfer",
        #     )
        # except stripe.error.InvalidRequestError as e:
        #     # Log the error or handle it appropriately
        #     print("Error creating transfer:", str(e))
        stripe.api_key = 'api_key'
        # Validate shipping_charges (assuming it's already properly validated)
        if not isinstance(shipping_charges, int) or shipping_charges <= 0:
            raise ValueError("Shipping charges must be a positive integer.")
        fee_checkout_session = stripe.checkout.Session.create(
            success_url=my_domain + '/success?session_id={CHECKOUT_SESSION_ID}',
            cancel_url=my_domain + '/cancel/',
            payment_method_types=['card'],
            mode='payment',
            line_items=[{
                'name': 'Nails - Service Fee',
                'quantity': 1,
                'currency': 'usd',
                'amount': shipping_charges,
            }]
        )
        payment_intent = session["payment_intent"]
        if mode == 'auction':
            auction.payment_intent = payment_intent
            auction.save()
        else:
            event.payment_intent = payment_intent
            event.save()
        return redirect(session.url, {'session_id_shipment': fee_checkout_session.id}, code=303)

Things need to resolve

  • I am creating a platform where user will earn money whenever his referral product is sold The main concept is that when buyer will make the payment this payment should be split into 4 parts

  • admin

  • seller

  • referral

  • shipment

for now payment is getting split into admin and seller now i want that if that particular seller has a seller who's referral code he has used to create the account then that referral should receive the 2 percent of amount from the admin amount

and i want that shipment amount should be send the new stripe account(i have created two stripe account 1 for seller admin and referral and one just for amdin) i.e i have two stripe api

please suggest the solution or any modification will will improve this

thanks in advance

0

There are 0 best solutions below