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

Square API v42+发票附件上传报错求助

升级Square API v42+沙箱环境附件上传失败解决方案

问题背景

升级Square API至v42及以上版本后,在沙箱环境调用Invoice API上传约800字节的JPEG文件时,遇到两类400错误:

错误1:请求内容类型无效

square.core.api_error.ApiError: status_code: 400, body: {'errors': [{'category': 'INVALID_REQUEST_ERROR', 'code': 'INVALID_CONTENT_TYPE', 'detail': 'Received multiple request parts. Please only supply zero or one `parts` of type application/json.'}]}

错误2:附件总大小超限

// cache-control: no-cache
// content-type: application/json
// date: Wed, 30 Apr 2025 13:35:06 GMT
// square-version: 2025-04-16

{
  "errors": [
    {
      "code": "BAD_REQUEST",
      "detail": "Total size of all attachments exceeds Sandbox limit: 1000 bytes",
      "category": "INVALID_REQUEST_ERROR"
    }
  ]
}

原调用代码:

pdf_filepath = 'local/path/to/file.jpg'
idem_key = 'some-unique_key_like_square_invoice_id'
f_stream = open(pdf_filepath, "rb")
try:
    # I have tried using a stream as well, still the same error
    invoice_pdf = SQUARE_CLIENT.invoices.create_invoice_attachment(
        invoice_id=square_original_invoice.id,
        # this also does not work
        # image_file=f_stream, 
        image_file=pdf_filepath,
        request={
            "description": f"Invoice-{pdf_filepath}",
            "idempotency_key": idem_key,
        },
    )
except ApiError as e:
    print(f"ERROR _attach_pdf_to_vendor_payment with errors {e}")

问题分析

  1. 请求参数冲突:对比API Explorer成功请求与SDK失败请求,发现成功请求使用file作为文件字段名,而SDK调用用了image_file;同时失败请求额外传递了application/json类型的request参数,导致多部分请求冲突,触发INVALID_CONTENT_TYPE错误。
  2. 沙箱大小限制:沙箱环境对发票附件总大小限制为1000字节,即使单个文件800字节,若目标发票已有其他附件,可能导致总大小超限。

解决方案

1. 修正SDK调用参数,避免多部分请求冲突

移除request参数,将描述、幂等键等参数直接作为接口参数传递,同时将文件字段名从image_file改为file,确保以二进制流形式传递文件:

pdf_filepath = 'local/path/to/file.jpg'
idem_key = 'some-unique_key_like_square_invoice_id'
# 使用with语句确保文件流正确关闭
with open(pdf_filepath, "rb") as f_stream:
    try:
        invoice_pdf = SQUARE_CLIENT.invoices.create_invoice_attachment(
            invoice_id=square_original_invoice.id,
            file=f_stream,
            description=f"Invoice-{pdf_filepath}",
            idempotency_key=idem_key
        )
    except ApiError as e:
        print(f"ERROR _attach_pdf_to_vendor_payment with errors {e}")

若SDK不支持直接传递description和idempotency_key作为独立参数,需查阅SDK文档确认正确的表单字段名,将这些参数作为multipart/form-data的表单部分传递,而非JSON请求体。

2. 检查并清理沙箱发票现有附件

调用list_invoice_attachments接口查询目标发票下的所有附件,计算总大小。若总大小接近或超过1000字节,先删除不必要的附件,再尝试上传新文件。

3. 验证请求格式

确保请求为multipart/form-data类型,仅包含一个文件部分和必要的表单字段,不附带额外的JSON请求体,避免触发多部分请求错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:19:55