Django支付验证视图无法获取请求用户ID,如何修改代码?
支付验证视图获取用户ID的修正
问题根源
支付完成后,第三方支付平台的回调请求是独立发起的,不会携带用户的登录会话信息,因此request.user会变成匿名用户,无法直接通过它筛选用户的未支付订单。
解决方案
直接通过传入的order_id获取对应订单,再从订单中关联用户信息,而非依赖request.user。同时增加订单不存在的异常处理,避免程序崩溃。
修改后的代码
def verify(request, *args, **kwargs): order_id = kwargs['order_id'] try: # 直接通过order_id获取订单,避免依赖request.user open_order: Order = Order.objects.get(id=order_id, is_paid=False) # 从订单中获取用户ID user_id = open_order.user.id total_price = int(open_order.total_price()) except Order.DoesNotExist: # 处理订单不存在的情况 return HttpResponse("订单不存在或已支付") t_status = request.GET.get('Status') t_authority = request.GET['Authority'] req = None if t_status == 'OK': req_header = {"accept": "application/json", "content-type": "application/json"} # 修复原代码中引号错误 req_data = { "merchant_id": MERCHANT, "amount": total_price, "authority": t_authority } req = requests.post(url=ZP_API_VERIFY, data=json.dumps(req_data), headers=req_header) if len(req.json()['errors']) == 0: t_status = req.json()['data']['code'] if t_status == 100: order = Order.objects.get(id=order_id) order.is_paid = True order.refrence_id = req.json()['data']['ref_id'] order.authority_id = t_authority order.pay_date = datetime.now() order.save() context = { 'verification_successful': True, 'reference_id': str(req.json()['data']['ref_id']), 'orderID': order_id, 'user_id': user_id # 可以将用户ID传入模板或后续使用 } return render(request, 'eshop_cart/verify.html', context) elif t_status == 101: context = {'verification_successful': False} return render(request, 'eshop_cart/verify.html', context) else: context = {'verification_successful': False} return render(request, 'eshop_cart/verify.html', context) else: e_code = req.json()['errors']['code'] e_message = req.json()['errors']['message'] return HttpResponse(f"Error code: {e_code}, Error Message: {e_message}") else: context = { 'verification_successful': False, 'order_id': order_id, 'user_id': user_id # 传入用户ID } return render(request, 'eshop_cart/verify.html', context)
关键修改点
- 移除了依赖
request.user.id的订单筛选逻辑,改为通过order_id直接查询未支付订单 - 增加
Order.DoesNotExist异常捕获,处理无效订单的情况 - 修复了原代码中请求头
content-type里的引号错误(多了一个单引号) - 从查询到的订单中提取
user_id,可用于后续业务逻辑或模板渲染
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

