对接亚马逊 SP-API(Amazon Selling Partner API) 第五章:Reports 模块

目录

1. 前提概要

1.1. 官方文档

1.1.1. ReportType Values

1.1.2. ReportType 请求体

1.1.3. 请求教程

1.2. 下面内容会以 ALL_ORDERS 为案例

2. 流程对比

2.1. MWS 流程

2.2. SP-API 流程

3. HTTP 对接

官方案例(Java & C #)

Step 1. Request a report

3.1.1. Headers

3.1.2. Body

3.1.3. 完整请求 URL

Step 2. Confirm report processing has completed

Step 3. Retrieve the report

4. SDK 对接

4.1. 下载对应的 SDK

4.1.1. model.json

4.1.2. 引入 aa 库

4.1.3. 引入 documents-helper  库

4.2. 创建 getReportsApi()

4.3. 创建报告(获取 reportId)

Bug 1. Bad Request

Bug 1.1. One or more required parameters missing

Bug 1.2. Report rejected for this client. Some of the marketplaces are not allowed for this Report

 Bug 2. io.swagger.client.ApiException: Forbidden

Bug 2.1. 无效帐号 

Bug 2.2. 传参错误

Bug 2.3. 枚举不对 或者 不支持的区域。

4.4. 检查报告申请状态(获取 reportDocumentId)

Bug 1. CANCELLED

4.5. 获取下载链接

4.6. 使用 DownloadExample.java 下载 report

Bug 1. java.lang.NoClassDefFoundError: com/google/common/base/Preconditions

Bug 2. java.lang.NoClassDefFoundError: org/apache/commons/io/IOUtils 

Bug 3. java.lang.IllegalArgumentException: No enum constant com.amazon.spapi.documents.CompressionAlgorithm.AES 

Bug 3.1. 乱码(峰兄提供)

Bug 4. com.amazon.spapi.documents.exception.CryptoException: java.security.InvalidKeyException: Illegal key size

总结


这一章我将会展示完整的流程,其他模块将不再重复相似的步骤了。

1. 前提概要

1.1. 官方文档

1.1.1. ReportType Values

这部分介绍了有哪些枚举类。

https://github.com/amzn/selling-partner-api-docs/blob/main/references/reports-api/reportType_string_array_values.md

1.1.2. ReportType 请求体

这部分介绍了 HTTP 请求的 body 的参数有哪些。

https://github.com/amzn/selling-partner-api-docs/blob/main/references/reports-api/reports_2020-09-04.md

1.1.3. 请求教程

https://github.com/amzn/selling-partner-api-docs/blob/main/guides/en-US/use-case-guides/reports-api-use-case-guide/reports-api-use-case-guide-2020-09-04.md

1.2. 下面内容会以 ALL_ORDERS 为案例

2. 流程对比

2.1. MWS 流程

RequestReport ==> GetReportRequestList ==> GetReport

2.2. SP-API 流程

createReport ==> getReport ==> getReportDocument ==> Download and decrypt

官网介绍:https://github.com/amzn/selling-partner-api-docs/blob/main/guides/en-US/use-case-guides/reports-api-use-case-guide/reports-api-use-case-guide-2020-09-04.md#tutorial-request-and-retrieve-a-report

简单来说就是:

1. createReport() 获取 reportId

2. 通过 reportId 调用 getReport() 检查报告状态。DONE 的情况会返回 reportDocumentId

3. 通过 reportDocumentId 调用 getReportDocument() 获取下载 url 和 文件解码

3. HTTP 对接

官方案例(Java & C #)

https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-examples-using-sdks.html#sig-v4-examples-using-sdk-java

AWSS3SigV4JavaSamples

这个 demo 对拼接 http 请求非常好用。

Step 1. Request a report

3.1.1. Headers

Authorization: AWS4-HMAC-SHA256 Credential=ABCXXXXXXX/20210423/us-east-1/execute-api/aws4_request, SignedHeaders=host;user-agent;x-amz-access-token, Signature=5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924aEXAMPLE
user-agent: My Selling Tool/2.0 (Language=Java/1.8.0.221;Platform=Windows/10)
x-amz-access-token=Atza|IQEBLjAsAhRmHjNgHpi0U-Dme37rR6CuUpSREXAMPLE
x-amz-date: 20210423T123400Z

NameDescription
x-amz-dateThe date and time of your request.
user-agent

Your application name and version number, platform, and programming language. These help Amazon diagnose and fix problems you might encounter with the service. See Include a User-Agent header in all requests.

应用程序名称和版本号、平台和编程语言

3.1.1.1. x-amz-access-token

access token 有效期为一个小时。我们可以通过 refresh token 获取最新的 access token。

cURL

curl --location --request POST 'https://api.amazon.com/auth/o2/token' \
--header 'Content-Type: application/x-www-form-urlencoded;charset=UTF-8' \
--data-raw 'grant_type=refresh_token&refresh_token={refresh_token}&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}'

3.1.1.2. x-amz-security-token

使用 AWS Security Token Service (AWS STS) 提供的临时安全证书对请求进行签名。其过程与使用长期凭证相同,但在您添加签名信息到查询字符串时,您必须为安全令牌添加额外的查询参数。参数名称为 X-Amz-Security-Token,参数值为 URI 编码的会话令牌(在您获取临时安全凭证时从 AWS STS 收到的字符串)。

3.1.1.3. Authorization

对接亚马逊 SP-API(Selling Partner API) 第四章:签名

3.1.2. Body

NameDescriptionRequired
reportOptionsAdditional information passed to reports. This varies by report type.

Type: ReportOptions

No
reportTypeThe report type. For more information, see reportType values.

Type: string

Yes
dataStartTimeThe start of a date and time range, in ISO 8601 date time format, used for selecting the data to report. The default is now. The value must be prior to or equal to the current date and time. Not all report types make use of this.

Type: string (date-time)

No
dataEndTimeThe end of a date and time range, in ISO 8601 date time format, used for selecting the data to report. The default is now. The value must be prior to or equal to the current date and time. Not all report types make use of this.

Type: string (date-time)

No
marketplaceIdsA list of marketplace identifiers. The report document's contents will contain data for all of the specified marketplaces, unless the report type indicates otherwise.

Type: < string > array

Yes

{
  "reportType": "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL",
  "dataStartTime": "2021-04-20T00:00:00.000Z",
  "marketplaceIds": [
    "A1PA6795UKMFR9",
    "ATVPDKIKX0DER"
  ]
}

3.1.3. 完整请求 URL

cUrl

curl --location --request POST 'https://sellingpartnerapi-na.amazon.com/reports/2020-09-04/reports' \
--header 'Authorization: Authorization' \
--header 'user-agent: My Selling Tool/2.0 (Language=Java/1.8.0.221;Platform=Windows/10)' \
--header 'x-amz-access-token: Atza|XXX' \
--header 'x-amz-date: 20210423T123400' \
--header 'Content-Type: application/json' \
--data-raw '{
  "reportType": "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL",
  "dataStartTime": "2021-04-20T00:00:00.000Z",
  "marketplaceIds": [
    "A1PA6795UKMFR9",
    "ATVPDKIKX0DER"
  ]
}'

Step 2. Confirm report processing has completed

Step 3. Retrieve the report

4. SDK 对接

 前提概要:

使用 sellers-api 模块的 getMarketplaceParticipations(),获取帐号所启用的站点(因为reports-api 的 marketplace 是必填项)。否则会提示站点不可用。

4.1. 下载对应的 SDK

对接亚马逊 SP-API(Selling Partner API) 第三章:对接 SDK

4.1.1. model.json

暂时使用 2020-09-04 版本。

4.1.2. 引入 aa 库

4.1.3. 引入 documents-helper  库

官方提供了 Java 解压的 demo(DownloadExample.java)。不需要的可以不引入 documents-helper  库。

Bug 1. 打包的时候会发现 test 包下面报错。

解决方法

打包的时候把测试类跳过就好。(解决不了出问题,就把出问题的地方解决掉)

4.2. 创建 getReportsApi()

public static ReportsApi getReportsApi() {
        AWSAuthenticationCredentials awsAuthenticationCredentials;
        AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider;
        LWAAuthorizationCredentials lwaAuthorizationCredentials;

        awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                .accessKeyId(USER_ACCESS_KEY_ID)
                .secretKey(USER_SECRET_ACCESS_KEY)
                .region(REGION)
                .build();

        awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                .roleArn(ROLE_ARN)
                .roleSessionName(ROLE_SESSION_NAME)
                .build();

        lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                .clientId(APP_CLIENT_ID)
                .clientSecret(APP_CLIENT_SECRET)
                .refreshToken(REFRESH_TOKEN)
                .endpoint(LWA_ENDPOINT)
                .build();

        ReportsApi reportsApi = new ReportsApi.Builder()
                .awsAuthenticationCredentials(awsAuthenticationCredentials)
                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                .endpoint(REGION_ENDPOINT)
                .build();

        if (null == reportsApi) {
            throw new RuntimeException();
        }
        return reportsApi;
    }

4.3. 创建报告(获取 reportId)

 请求限制:

 最大请求为10个点数,以每秒 0.0222 个恢复,即 45 秒恢复一个请求点数。

对比 MWS 最大限额小了,恢复速度快了。

4.3. 1. Bad Request

错误提示不太友好。这个我查了半天才发现 Body 中 Marketplace ID 是个必填项。

Bug 1. One or more required parameters missing

{
  "errors": [
    {
      "code": "InvalidInput",
      "message": "One or more required parameters missing",
      "details": "marketplaceIds;"
    }
  ]
}

解决办法

参考文档把必填项补充进去就好了。

Bug 2. Report rejected for this client. Some of the marketplaces are not allowed for this Report

{
	"errors": [{
		"code": "InvalidInput",
		"message": "Report rejected for this client. Some of the marketplaces are not allowed for this Report",
		"details": ""
	}]
}

 解决办法

1. 确定自己的 marketplaceId 没有填错。

2. 去文档找这个 report type 是否支持当前站点。

 问题倒是找到了。但是其他北美的帐号可以正常申请这个类型.. 很迷 - -。

最后在 Github issues 发现答案。

https://github.com/amzn/selling-partner-api-docs/issues/911

4.3.2. io.swagger.client.ApiException: Forbidden

备注:2021-06-30 之前,SP-API 麻烦使用 2020-09-04 这个版本。 

Bug 1. 无效帐号 

 我们首先确定一点,这个帐号是有效的。登录亚马逊后台,你会发现首页就显示这个帐号挂掉了。

备注:当这个帐号被冻结了,我们依然是可以正常进入后台且可以拿到 refresh_token 的,也可以通过 refresh_token 拿到 access_token。只是无法再进行下一步的 Api 操作了。

Bug 2. 传参错误

解决办法

找到你报错的地方,打上断点。在异常的 Message 有写明是因为什么报错。

Bug 3. 枚举不对 或者 不支持的区域。

{
  "errors": [
    {
      "code": "Unauthorized",
      "message": "Access to the resource is forbidden",
      "details": ""
    }
  ]
}

  由于我请求的报告是 Amazon Fulfilled Shipments。并且确信授权了这个模块。所以权限是没问题的。

枚举类:因为我发现 MWS 和 SP-API 的枚举类都是一样的,只是前后的 _ 取消了。所以我理所当然的使用了:GET_AMAZON_FULFILLED_SHIPMENTS_DATA

然后跑去官网查看。你就会发现,正确的枚举类长这样:GET_AMAZON_FULFILLED_SHIPMENTS_DATA_GENERAL

官方解释 

4.4. 检查报告申请状态(获取 reportDocumentId)

 Processing Statuses

Bug 1. CANCELLED

请求了大量的报告你会发现,很多报告会出现 Cancelled 状态。以我多年的 MWS 经验,我断定是我发送请求太频繁了导致的。然后我就不断的重新发起请求.. 不断的 Cancelled。

最后我跑去后台查,发现没数据也会显示 Cancelled。这就很尴尬了。

去官方文档查询,你会发现 

大概的意思是:有两种可能会出现 Cancelled 状态,1. 自己取消。2. 没数据。

 我还是怀念 MWS 的 _DONE_NO_DATA_,简单明了。而且从 MWS 升级过来,有好多坑都是经验式 Bug..

猜想)状态变更:SP-API 请求数据太频繁的报告状态是 FATAL。

4.5. 获取下载链接

4.6. 使用 DownloadExample.java 下载 report

Bug 1. java.lang.NoClassDefFoundError: com/google/common/base/Preconditions

解决方法

        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>30.1.1-jre</version>
        </dependency>

Bug 2. java.lang.NoClassDefFoundError: org/apache/commons/io/IOUtils 

解决方法

        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

Bug 3. java.lang.IllegalArgumentException: No enum constant com.amazon.spapi.documents.CompressionAlgorithm.AES 

 

CompressionAlgorithm.java 还真没有.. 就很尴尬了..

解决办法
构建 DownloadSpecification 的时候,不加这个算法。

Bug 3.1. 乱码(峰兄提供)

情景:

某些报告下载下来是正常的,某些报告是乱码。

 原因:

1)、正常报告 Response:

2)、乱码报告 Response:

导致乱码的原因是我们在 BUG 3 中把算法去掉了。而数据量如果比较大的情况,亚马逊会返回一个 GZIP 文件,而我们又没解析。

解决办法

Bug 4. com.amazon.spapi.documents.exception.CryptoException: java.security.InvalidKeyException: Illegal key size

原因:JAVA默认支持AES 128 Bit 的key, 如果你计划使用 192 Bit 或者 256 Bit key, java complier 会抛出 Illegal key size Exception

解决办法

Plan A
替换 Policy 文件(选择对应 Java 版本下载)(需要注册个 Oracle 帐号)

https://www.oracle.com/java/technologies/javase-jce-all-downloads.html

替换 JDK 与 JRE 下两个 jar 包:local_policy.jar 和 US_export_policy.jar
JDK 对应 jar 包路径:%JAVA_HOME%\jre\lib\security
JRE 对应 jar 包路径:%JAVA_JRE%\lib\security
Plan B
升级 Java 版本

总结

1. SDK 比 自己发送 HTTP 请求要简单一些。

  • 7
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 84
    评论
com.jd.open.api:open-api-sdk:2.0是京东开放平台的Java开发工具包,用于开发者与京东开放平台进行对接和交互的SDK。 京东开放平台是京东商城提供给商家和开发者的一套开放平台服务,包括商品查询、订单管理、用户授权、营销推广等功能。开发者通过使用open-api-sdk可以方便地使用京东开放平台的各种接口,节省开发时间和精力。 open-api-sdk的版本号为2.0,表示这已经是该工具包的第二个大版本,在之前版本的基础上进行了更新和改进。新版本的sdk通常包含更多功能、修复了之前版本中的bug,并提供更好的兼容性和稳定性。 使用com.jd.open.api:open-api-sdk:2.0可以通过调用相应的接口实现与京东开放平台的连接和数据交互。例如,开发者可以使用该工具包中提供的接口发送商品查询请求,获取商品的详细信息;也可以使用接口进行订单管理,包括订单创建、取消、查询等操作。 此外,open-api-sdk还提供了其他一些功能,如用户授权、优惠券领取与使用、营销推广等。开发者可以根据自己的需求选择使用相应的接口,与京东开放平台进行集成开发。 总之,com.jd.open.api:open-api-sdk:2.0是京东开放平台提供给开发者的Java开发工具包,可以方便地与京东开放平台进行对接和交互,实现商品查询、订单管理、用户授权等功能。开发者可以根据具体需求使用该工具包中提供的接口,进行开发和集成。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 84
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值