我如何从 R 调用亚马逊销售合作伙伴 API?

问题描述 投票:0回答:1

我正在尝试使用 httr 包从 amazon sp api 检索数据。 到目前为止我所做的是:

(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) 'access_token' 值作为 POST 请求响应:

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-acess-token` = access_token))

最后,我已经陷入了第 2 步,因为我从 POST 请求中得到了以下响应:

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

我基本上遵循这个 https://www.youtube.com/watch?v=gp5kTI8I3pU 教程,并试图适应 R/R Studio。

有谁有更多经验并愿意分享吗?

r httr amazon-selling-partner-api
1个回答
0
投票

400 响应代码通常意味着您发送的请求格式错误。默认情况下,

httr::POST
函数会将主体编码为
multipart/form-data
(“多部分”)。亚马逊 API 特别要求数据使用
application/x-www-form-urlencoded
(“表单”)进行编码。因此,为了获得正确的响应,您可以使用

token_response <- httr::POST(
  url = "https://api.amazon.com/auth/o2/token",
  encode = "form",
  body = data) 
© www.soinside.com 2019 - 2024. All rights reserved.