You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django集成PayPal服务端模式前端收不到订单ID报错如何解决

问题根因与修复方案

问题1:前端Fetch未解析响应JSON

fetch请求返回的第一个参数是原生Response对象,你需要手动调用.json()方法将响应体解析为JavaScript对象,才能读取到id字段。当前代码直接返回res对象,后续拿到的orderData不是你预期的PayPal返回结构体,自然读不到id。
修正后前端代码:

// Call your server to set up the transaction
createOrder: function (data, actions) {
  return fetch("/createOrder", {
    method: "post",
    credentials: "same-origin",
    headers: {
      "X-CSRFToken": csrftoken,
    },
  })
    .then(function (res) {
      console.log("res");
      console.log(res);
      // 新增:解析响应为JSON格式
      return res.json();
    })
    .then(function (orderData) {
      console.log("orderData");
      console.log(orderData);
      return orderData.id;
    });
},

问题2:Django后端返回格式不符合要求

Django视图不能直接返回Python字典,你需要使用JsonResponse封装返回数据,才会自动设置正确的Content-Type: application/json响应头,把字典序列化为JSON字符串返回给前端。当前直接返回字典的话,Django会返回非JSON格式的响应,前端解析失败。
修正后Django代码:

from django.http import JsonResponse
import requests

def sth(request):
    logger.error('called')
    t = gettoken()
    d = {"intent": "CAPTURE","purchase_units": [{"amount": {"currency_code": "USD","value": "100.00"}}]}
    h = {"Content-Type": "application/json", "Authorization": "Bearer "+t}
    r = requests.post('https://api-m.sandbox.paypal.com/v2/checkout/orders', headers=h, json=d).json()
    logger.error(r)
    # 用JsonResponse封装返回结果
    return JsonResponse(r)

验证方式

修改完成后打开浏览器开发者工具的网络面板,查看/createOrder接口的响应头Content-Type是否为application/json,响应体是否为包含id字段的正确JSON结构即可。

内容的提问来源于stack exchange,提问作者rivercity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 13:57:03