如何在 django 中设置 stripe webhook

问题描述 投票:0回答:1

我正在开发一个项目,买家将付款并将付款转移给多个用户

这是分期付款的正确方法吗

我如何运行我的 webhook

这是我的代码

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()
        user = request.user
        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
            referrals = Referral.objects.filter(referred_user=seller_id).first()
            # referred_by =  referrals.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 + taxes
        # if referrals:
        admin_amount = int((total_charges) * 0.2)
        seller_amount = total_charges - admin_amount
        referral_amount = int(admin_amount * 0.02)
        stripe.api_key = "sk_test_EI5Kddsg2MCELde0vbX2cDGw"
        charge_id = None
        # payment_intent = stripe.Charge.create(
        #     amount=total_charges,
        #     currency='usd',
        #     source='tok_visa',
        # )

        # charge_id = payment_intent.id
        session = stripe.checkout.Session.create(
            success_url=f"{my_domain}/payment_success/{auction_id}/{courier_id}?mode={mode}",
            cancel_url=f"{my_domain}/payment_failed/{auction_id}/{courier_id}?mode={mode}",
            mode='payment',
            payment_method_types=['card'],
            line_items=[
                {
                    'price_data': {
                        'currency': 'usd',
                        'product_data': {
                            'name': 'Your Product Name',
                        },
                        'unit_amount': total_charges,  # Amount in cents
                    },
                    'quantity': 1,
                },
            ],
        )
        if mode == 'auction':
            auction.payment_intent = session.payment_intent
            auction.save()
        else:
            event.payment_intent = session.payment_intent
            event.save()

        return redirect(session.url, code=303)

这是 webhook 代码,请查看并告诉我它是否正确

@method_decorator(csrf_exempt, name='dispatch')
class PaymentsWebhook(View):
    def post(self, request, *args, **kwargs):
        payload = request.body
        webhook_secret = 'we_1LVfDcIwzRTKa8uKt3Uhtms0'
        signature = request.headers.get('stripe-signature')
        try:
            event = stripe.Webhook.construct_event(payload, signature, webhook_secret)
        except ValueError as e:
            return HttpResponse(status=400)
        except stripe.error.SignatureVerificationError as e:
            return HttpResponse(status=400)
        
        if event['type'] == 'checkout.session.completed':
            data = event['data']['object']
            customer = data['customer']
            payment_status = data['payment_status']
            if payment_status == 'paid':
                user = User.objects.get(stripe_customer_id=customer)
                print('user', user.first_name, user.last_name, 'paid successfully')

                # Calculate seller amount and referral amount
                total_payment = data['amount_total'] / 100  # Converting amount from cents to dollars
                application_fee = 20  # Assuming fixed application fee in dollars
                referral_percentage = 0.02  # 2% referral commission
                seller_amount = total_payment - application_fee
                referral_amount = total_payment * referral_percentage

                payment_intent = stripe.PaymentIntent.retrieve(data['payment_intent'])
                if payment_intent.charges.data:
                    most_recent_charge = payment_intent.charges.data[0]
                    charge_id = most_recent_charge.id
                    # Assuming you have seller_account_id defined
                    stripe.Transfer.create(
                        amount=int(seller_amount * 100),  # Converting amount to cents
                        currency='usd',
                        source_transaction=charge_id,
                        destination='acct_1OqviFIxAI6NhXOK',
                        transfer_group=f"ORDER10_{user.id}",
                    )
                    stripe.Transfer.create(
                        amount=int(referral_amount * 100),  # Converting amount to cents
                        currency='usd',
                        source_transaction=charge_id,
                        destination="acct_1OoODQIbLDChIvG2",
                        transfer_group=f"ORDER10_{user.id}",
                    )                    
        elif event['type'] == 'customer.subscription.deleted':
            data = event['data']['object']
            customer = data['customer']
            try:
                user = User.objects.get(stripe_customer_id=customer)
                user.is_premium = False
                user.save()
                print("Successfully removed user " + user.first_name + " " + user.last_name + "'s premium")
            except:
                print("Failed to find customer:", customer) 
                
        return HttpResponse(status=200)

提前感谢您的帮助

python django stripe-payments webhooks payment
1个回答
0
投票

此处的

webhook_secret
基本上是您的 Webhook 端点 ID。您应该添加的基本上是您访问
https://dashboard.stripe.com/test/webhooks/we_1LVfDcIwzRTKa8uKt3Uhtms0
时可以在仪表板上找到的 whsec_xxx,然后单击 Signing Secret 下的 Reveal

© www.soinside.com 2019 - 2024. All rights reserved.