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

如何在PayPal存储订单自定义数据并捕获后取回(Python)

解决方案

1. 为什么application_context不返回自定义数据

application_context参数仅用于配置PayPal结账页面的交互行为(比如跳转URL、品牌展示、付款方式限制等),PayPal不会持久化存储你添加的自定义键值对,因此查询订单时无法取回这些数据。

2. 正确存储自定义产品数据的方法

你需要将产品数据序列化后,存入purchase_units下的custom字段——这是PayPal API专门预留的自定义数据存储位,会被持久化并在后续查询/捕获接口中返回。

修改创建订单的代码如下:

import json

products = [
       {'id': 'id_1', 'price': 100, 'quantity': 2},
       {'id': 'id_2', 'price': 50, 'quantity': 2}
]

# 将产品序列化为JSON字符串
products_json = json.dumps(products)

paypal_json = {
    "intent": "CAPTURE", 
    "purchase_units": [
        {
            "amount": {"currency_code": CURRENCY, "value": total_price},
            "custom": products_json  # 存入自定义数据
        }
    ],
    # 仅保留application_context的合法配置,不要添加自定义键
    "application_context": {
        "return_url": "https://your-domain.com/success",
        "cancel_url": "https://your-domain.com/cancel"
    }
}

3. 捕获/查询订单时取回数据

调用订单查询或捕获接口时,custom字段会包含你存储的JSON字符串,只需反序列化即可:

import json

access_token = generate_access_token()
headers = {"Authorization": f"Bearer {access_token}"}
response = requests.get(f"https://api-m.paypal.com/v2/checkout/orders/{order_id}", headers=headers)
order_data = response.json()

# 取出并反序列化产品数据
products_str = order_data['purchase_units'][0]['custom']
products = json.loads(products_str)
print(products)

4. 关于服务器端存储的顾虑

你提到的“服务器端关联订单ID和产品数据存数据库”是行业标准做法,所谓的“内存浪费”可通过以下方式规避:

  • PayPal订单默认24小时后自动过期,可设置定时任务(如Celery、Linux cron),每天清理超过24小时未支付的订单记录。
  • 这种方式比仅依赖PayPal存储更灵活:可随时查询订单状态、统计未支付订单,且不受PayPal API返回字段的限制。

如果一定要完全依赖PayPal存储数据,custom字段是可靠选择,但服务器端存储依然是更推荐的方案——两者可结合使用(比如数据库存一份,PayPal存一份做校验)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:15:19