如何在Django中设置Stripe webhook
我正在做一个项目,买家会进行付款,然后这笔钱会分给多个用户。
这样分账的方法对吗?
我该怎么运行我的 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)
提前感谢你的帮助!
1 个回答
0
你这里提到的 webhook_secret
实际上就是你的 webhook 端点 ID。你需要添加的那个值就是 whsec_xxx
,你可以在访问 https://dashboard.stripe.com/test/webhooks/we_1LVfDcIwzRTKa8uKt3Uhtms0 的时候,在仪表盘上找到,并点击“Reveal under Signing Secret”来查看。