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

Django电商网站:如何向PayPal智能按钮传递订单详情

解决方案:向商家账户传递订单详情(Django + PayPal)

嘿,我来帮你搞定这个问题!你碰到的核心问题是PayPal的description字段只支持字符串类型,直接传数组肯定会失败。下面给你几个实用的解决思路:

方案1:将列表转为JSON字符串传递

既然description只认字符串,我们可以把订单详情列表转成JSON格式的字符串,商家后端拿到后再解析回列表就行。

前端代码修改:

createOrder: function(data, actions) {
  // 定义你的订单详情列表
  const orderDetails = [{ order: "dress5", price: "30" }];
  // 转成JSON字符串
  const descriptionStr = JSON.stringify(orderDetails);
  
  return actions.order.create({
    purchase_units: [{
      amount: {
        value: '30.11',
      },
      description: descriptionStr
    }]
  });
}

Django后端解析:

import json

# 假设从PayPal的回调/API响应中获取description字段
order_desc = request.POST.get('description')
try:
    # 解析回Python列表
    order_details = json.loads(order_desc)
    # 处理每个商品
    for item in order_details:
        print(f"商品:{item['order']},价格:{item['price']}")
except json.JSONDecodeError:
    # 处理解析失败的情况
    print("订单详情解析出错")

方案2:使用PayPal官方的items字段(推荐)

其实PayPal的purchase_units里专门有个items数组字段,就是用来传递商品详情的,这比用description更规范,而且PayPal的订单页面也会显示这些商品信息,用户体验更好。

前端代码示例:

createOrder: function(data, actions) {
  return actions.order.create({
    purchase_units: [{
      amount: {
        value: '30.11',
        // 金额拆分要和items总和匹配
        breakdown: {
          item_total: {
            currency_code: 'USD', // 币种要统一
            value: '30.00'
          },
          tax_total: {
            currency_code: 'USD',
            value: '0.11'
          }
        }
      },
      // 商品详情数组
      items: [
        {
          name: 'Dress 5',
          description: '夏季新款连衣裙',
          quantity: '1',
          unit_amount: {
            currency_code: 'USD',
            value: '30.00'
          }
        }
      ]
    }]
  });
}

Django后端获取:

当PayPal回调到你的Django接口时,直接从响应数据的purchase_units[0].items字段就能拿到结构化的商品列表,不用额外解析,非常方便。

方案3:用custom字段传递自定义数据

如果需要传递订单ID、商家内部编码这类额外信息,可以用purchase_units里的custom字段(同样是字符串类型),和items配合使用:

createOrder: function(data, actions) {
  return actions.order.create({
    purchase_units: [{
      amount: {
        value: '30.11',
      },
      items: [/* 商品详情 */],
      // 传递自定义的订单ID(转成字符串)
      custom: JSON.stringify({ order_id: "DJ20240520001" })
    }]
  });
}

总结:优先选方案2,符合PayPal的API设计规范;如果只是临时传递简单结构,方案1也能快速解决问题;方案3适合补充传递自定义业务数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:14:54