支付完成后如何在Admin后台自动创建订单?(代码求助)
问题分析与修复方案
先梳理代码中的核心问题,再给出针对性的修复:
核心问题点
- 前端JS存在两处拼写错误:
fecth应为fetch,aplication/json应为application/json - 后端视图模型引用错误:Order的
product关联的是Coinpack,但视图中误用了checkout.objects.get - 缺少异常处理逻辑:PayPal支付捕获、后端创建订单时未处理失败场景
- 未将Order模型注册到Admin后台,导致支付完成后无法在Admin中看到订单
修正后的完整代码
1. checkout.html(修复JS拼写与错误处理)
<script src="https://www.paypal.com/sdk/js?client-id=idexample¤cy=USD"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); var total = '{{checkout.price}}' var productId = '{{checkout.id}}' function completeOrder(){ var url = "{% url 'complete' %}" fetch(url, { // 修正拼写:fecth → fetch method: 'POST', headers:{ 'content-type':'application/json', // 修正拼写:aplication → application 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'productId':productId}) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Order creation failed:', error)); } // Render the PayPal button into #paypal-button-container paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: total } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(orderData) { completeOrder() console.log('Capture result', orderData, JSON.stringify(orderData, null, 2)); var transaction = orderData.purchase_units[0].payments.captures[0]; alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details'); }).catch(function(error) { console.error('Payment capture failed:', error); alert('Payment failed. Please try again.'); }); }, // 处理支付取消场景 onCancel: function(data) { alert('Payment was cancelled.'); }, // 处理PayPal端错误 onError: function(err) { console.error('PayPal error:', err); alert('An error occurred during payment.'); } }).render('#paypal-button-container'); </script> </body> </html>
2. views.py(修正模型引用与异常处理)
import json from django.http import JsonResponse from .models import Order, Coinpack def paymentComplete(request): if request.method != 'POST': return JsonResponse('Invalid request', status=400) try: body = json.loads(request.body) product_id = body.get('productId') if not product_id: return JsonResponse('Missing product ID', status=400) # 修正为关联的Coinpack模型 product = Coinpack.objects.get(id=product_id) Order.objects.create(product=product) return JsonResponse('Payment completed! Order created successfully.', safe=False) except Coinpack.DoesNotExist: return JsonResponse('Product not found', status=404) except Exception as e: return JsonResponse(f'Error creating order: {str(e)}', status=500)
3. admin.py(注册Order模型到Admin后台)
from django.contrib import admin from .models import Order admin.site.register(Order)
额外优化建议
- 生产环境请替换PayPal的
client-id为你的真实开发者ID - 建议在Order模型中添加
paypal_transaction_id字段,保存PayPal返回的交易ID,方便后续对账:class Order(models.Model): product = models.ForeignKey(Coinpack, max_length=200, null=True, blank=True, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) paypal_transaction_id = models.CharField(max_length=100, blank=True, null=True) - 确保模板中的
{{checkout}}是Coinpack模型的实例,否则{{checkout.id}}会传递错误的商品ID
内容的提问来源于stack exchange,提问作者mika
相关产品推荐
相关产品推荐

