我正在将购物车数据从cookie发送到Stripe并检索它,但我无法找到正确处理它的解决方案。
请帮忙!
我正在学习Django,并希望将非登录用户的购物车项目保存到cookie中,并将其作为元数据发送到Stripe。从那里检索它,如果签出完成,则处理订单,但我无法处理检索到的数据以保存订单。
Stripe Checkout会话:
@csrf_exempt
def create_checkout_session(request):
stripe.api_key = settings.STRIPE_SECRET_KEY
domain_url = 'http://localhost:8000/checkout/'
if request.user.is_authenticated:
customer = request.user.customer
else:
data = json.loads(request.body)
total = data['form']['total'].replace('.', '')
email = data['form']['email']
first_name = data['form']['first_name']
last_name = data['form']['last_name']
customer, created = Customer.objects.get_or_create(
email=email
)
customer.first_name = first_name
customer.last_name = last_name
customer.save()
cart_info = cart_details(request)
cart_items = cart_info['cart_items']
order = cart_info['order']
items = cart_info['items']
print(items)
if request.method == 'GET':
checkout_session = stripe.checkout.Session.create(
shipping_address_collection={
"allowed_countries":
["US", "CA", "NL", "GB"]
},
client_reference_id=request.user.id,
customer_email=request.user.email,
success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
cancel_url=domain_url + 'cancelled/',
payment_method_types=['card'],
mode='payment',
line_items=[
{
'name': 'Kenpachi Katana Store',
'quantity': 1,
'currency': 'usd',
'amount': int(order.get_cart_total*100),
}
]
)
return JsonResponse({'sessionId': checkout_session['id']})
else:
checkout_session = stripe.checkout.Session.create(
shipping_address_collection={
"allowed_countries":
["US", "CA", "NL"]
},
**metadata=[items]**,
client_reference_id=customer.id,
customer_email=email,
success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
cancel_url=domain_url + 'cancelled/',
payment_method_types=['card'],
mode='payment',
line_items=[
{
'name': 'Kenpachi Katana Store',
'quantity': 1,
'currency': 'usd',
'amount': total,
}
]
)
return JsonResponse({'sessionId': checkout_session['id']})
带有Cookie Cart变量的终端输出:
print(type(items))
& lt;类的列表在
:
[{'product':
`{'id': 1,
'name': 'Sasuke Katana',
'price': Decimal('270.00'),
'imageURL': '/media/1_ccbb983f-a35d-40f8-8efb-dc55db02ad8f_700x.webp'},
'quantity': 1,
'get_total': Decimal('270.00')},
`
{'product':
{'id': 3,
'name': 'Zoro Katana',
'price': Decimal('260.00'),
'imageURL': '/media/1_466b0afb-d483-4a32-b0bb-89388aeccaa4_700x.webp'},
'quantity': 1,
'get_total': Decimal('260.00')
}]
很容易通过它循环
for item in items:
print(item)
输出:
输入图片描述
订单完成后,我检索Stripe Session来完成订单
@csrf_exempt
def stripe_webhook(request):
stripe.api_key = settings.STRIPE_SECRET_KEY
endpoint_secret = settings.STRIPE_ENDPOINT_SECRET
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload,
sig_header,
endpoint_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':
session = event['data']['object']
session = stripe.checkout.Session.retrieve(
event['data']['object']['id'],
expand=['line_items'],
)
stripe_metadata = session['metadata'].setdefault('0')
print(stripe_metadata)
print(type(stripe_metadata))
# Fulfill the purchase...
# TODO: drill down on the metadata from stripe
transaction_id = datetime.datetime.now().timestamp()
total = session['amount_total']
customer_id = session['client_reference_id']
customer = Customer.objects.get(pk=customer_id)
order, created = Order.objects.get_or_create(
customer=customer,
complete=False
)
order.transaction_id = transaction_id
if (total / 100) == int(order.get_cart_total):
order.complete = True
ShippingAddress.objects.create(
customer=customer,
order=order,
address=session['shipping']['address']['line1'],
city=session['shipping']['address']['city'],
state=session['shipping']['address']['state'],
zipcode=session['shipping']['address']['postal_code'],
country=session['shipping']['address']['country'],
)
order.save()
print('Order was added to the database')
return HttpResponse(status=200)
终端输出:
输入图片描述
以相同格式检索它的最佳选择是什么,以便能够遍历购物车中的产品。
任何帮助都将不胜感激。
GitHub repo with cookie cart功能:https://github.com/GeorgianF/Kenpachi-P5-CI/blob/main/cart/utils.py
谢谢!
也许你可以试试
stripe_metadata = json.loads(str(stripe_metadata))
将字符串转换为JSON格式