如何创建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
相关产品推荐
相关产品推荐

