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

如何创建PayPal草稿发票?Python代码请求格式报错求助

PayPal草稿发票创建问题修复

一、报错原因与格式修复

你的请求报错核心是JSON语法错误:将本该使用对象({})的字段错误写成了数组([]),数组内不能直接放置键值对,必须嵌套对象。具体错误点:

  • primary_recipients 是数组,每个收件人需用对象包裹:[{"billing_info": {...}}]
  • items 数组内的每个商品项需用对象包裹:[{"name": "...", ...}]
  • detail、invoicer、configuration、amount 均为单一对象,需用{}而非[]

修正后的完整代码:

async def create_invoice(client_email: str, item_name: str, item_price: int):
    payload = """{{
        "primary_recipients": [
            {{
                "billing_info": {{
                    "email_address": "{client_email}"
                }}
            }}
        ],
        "items": [
            {{
                "name": "{name}",
                "quantity": 1,
                "unit_amount": {{
                    "currency_code": "USD",
                    "value": {price}
                }}
            }}
        ],
        "detail": {{
            "currency_code": "USD"
        }},
        "invoicer": {{
            "business_name": "[REDACTED]",
            "email_address": "[REDACTED]"
        }},
        "configuration": {{
            "template_id": "[REDACTED]"
        }},
        "amount": {{
            "currency_code": "USD",
            "value": {price}
        }}
    }}"""
    payload = payload.format(client_email=client_email, price=str(item_price), name=item_name)

    headers = {{
        'Authorization': 'Bearer [REDACTED]',
        'Content-Type': 'application/json',
        'Prefer': 'return=representation',
    }}

    async with aiohttp.ClientSession() as session:
        resp = await session.post("https://api-m.sandbox.paypal.com/v2/invoicing/invoices", data=payload, headers=headers)
        if resp.status != 200:
            print(resp.status)
        print(await resp.json())

二、合规处理缺少客户信息的问题

如果你无法获取客户的全名和地址,绝对不要填写虚假数据,直接省略name、business_name等非必填字段即可。根据PayPal发票API规范:

  • primary_recipients[0].billing_info.email_address 是唯一必填的收件人信息
  • 其他如姓名、地址、公司名称均为可选字段,不填写不会触发合规或API报错

报错信息翻译

{'name': 'INVALID_REQUEST', 'message': '请求格式不正确、语法错误或违反架构。', 'debug_id': 'db080ca002d1d', 'details': [{'field': 'primary_recipients/0', 'location': 'body', 'description': "无法构造com.paypal.invoicing.v2.model.RecipientInfo实例(尽管至少存在一个构造函数):无法从字符串值('billing_info')反序列化,位置:第3行,第13列"}], 'links': [{'href': 'https://developer.paypal.com/docs/api/invoicing/#errors', 'method': 'GET'}]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:26:08