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

在R中调用Amazon Selling Partner API遇400错误求助

问题:使用R的httr包调用Amazon SP API获取access_token时返回400错误

已完成操作

0. 加载依赖包

library(httr)
library(httr2)
library(jsonlite)
library(lubridate)

1. 定义请求数据

data = list(
  grant_type = "refresh_token",
  refresh_token = "Atzr|...",
  client_id = "amzn1...",
  client_secret = "amzn1....")

2. 发送POST请求获取access_token(此处出错)

token_response = httr::POST(
  url = "https://api.amazon.com/auth/o2/token",
  body = data) 

access_token = fromJSON(token_response)[["access_token"]]

3. 定义请求参数(后续待执行步骤)

markentplace_endpoint = "https://sellingpartnerapi-eu.amazon.com"
marketplace_id = "A1PA6795UKMFR9"

request_params = list(
  "MarketplaceId" = marketplace_id, 
  "CreatedAfter" = as_date(Sys.Date()-30))

4. 构造请求URL(后续待执行步骤)

url = paste0(markentplace_endpoint, "/orders/v0/orders")
url$query = request_params
url = paste0(paste0(markentplace_endpoint, "/orders/v0/orders"), url_build(url))

5. 准备发送GET请求(后续待执行步骤)

httr::GET(
  url = paste0(paste0(markentplace_endpoint, "/orders/v0/orders"), url_build(url)), 
  add_headers(`x-amz-access-token` = access_token))

遇到的错误

步骤2的POST请求返回400状态码,响应信息如下:

Response [https://api.amazon.com/auth/o2/token]
  Date: 2024-01-07 12:13
  Status: 400
  Content-Type: application/json;charset=UTF-8
  Size: 392 B

解决方法

1. 修正POST请求的编码格式

Amazon OAuth2令牌接口要求请求体采用application/x-www-form-urlencoded格式,默认的httr::POST传入list会使用multipart/form-data编码,导致接口报错。修改请求代码,添加encode = "form"参数:

token_response = httr::POST(
  url = "https://api.amazon.com/auth/o2/token",
  body = data,
  encode = "form")

2. 获取详细错误信息定位问题

解析响应体的JSON内容,查看具体错误原因:

error_info = fromJSON(content(token_response, "text", encoding = "UTF-8"))
print(error_info)

常见错误原因包括:

  • refresh_token、client_id或client_secret无效、过期或格式错误
  • grant_type参数拼写错误(必须严格为refresh_token)
  • 关联账号未获得SP API的访问权限

3. 修正后续URL构造逻辑

步骤4中URL拼接存在重复基础地址的问题,使用httr::modify_url可以更安全地构造带查询参数的URL:

base_url = paste0(markentplace_endpoint, "/orders/v0/orders")
url = modify_url(base_url, query = request_params)

后续GET请求直接使用该URL即可:

httr::GET(
  url = url, 
  add_headers(`x-amz-access-token` = access_token))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:47:41