亚马逊电商数据自动化管理接口平台JAVA SP-API接口开发(中)

亚马逊电商数据自动化管理接口平台JAVA SP-API接口开发(中)

重要说明

  • 本文章为亚马逊系列其中的一篇,具体详见 主页 中亚马逊分类
  • 该系列项目均为【CSDN轻夏】原创,未经允许禁止转载
  • 如有疑问请添加qq群聊302493982学习咨询

准备工作

我们可以封装一下请求头,当请求欧洲的国家时,所有的参数必须都是传欧洲的(吐槽:官方为什么不能自己判断一下)
为此,我们封装了一些简陋的方法,以供测试

例如访问北美:

public static ArrayList<Object> pack_US() {
  AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
            .accessKeyId(ACCESS_KEY_ID)
            .secretKey(SECRET_KEY)
            .region(US_EAST_1)//请求地区
            .build();
    AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
            .roleArn(ROLE_ARN)//IAM角色
            .roleSessionName(ROLE_NAME)
            .build();
    LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
            .clientId(LAW_CLIENT)
            .clientSecret(LWA_SECRET)
            .refreshToken(NORTH_TOKEN)
            .endpoint(LWA_URL)//LWA验证服务器URI
            .build();
    ArrayList<Object> list = new ArrayList<>();
    list.add(awsAuthenticationCredentials);
    list.add(awsAuthenticationCredentialsProvider);
    list.add(lwaAuthorizationCredentials);
    return list;
}

例如访问欧洲:

public static ArrayList<Object> pack_EUROPE() {
   AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
            .accessKeyId(ACCESS_KEY_ID)
            .secretKey(SECRET_KEY)
            .region(US_WEST_1)//请求地区
            .build();
    AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
            .roleArn(ROLE_ARN)//IAM角色
            .roleSessionName(ROLE_NAME)
            .build();
    LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
            .clientId(LAW_CLIENT)
            .clientSecret(LWA_SECRET)
            .refreshToken(EUROPE_NAME)
            .endpoint(LWA_URL)//LWA验证服务器URI
            .build();
    ArrayList<Object> list = new ArrayList<>();
    list.add(awsAuthenticationCredentials);
    list.add(awsAuthenticationCredentialsProvider);
    list.add(lwaAuthorizationCredentials);
    return list;
}

1、小技巧

List类型的数据

Arrays.asList(US_MARKETPLACE_ID)

时间数据

OffsetDateTime.parse("2022-02-01T00:00:00Z")

后面要加Z!!! 或者是下面这种格式

OffsetDateTime.parse("2022-01-28T00:00:00+08:00")

其他时间打印详见 https://blog.csdn.net/weixin_44155966/article/details/123073692

报错信息

错了是不报错的,要看报错信息,要在 e.printStackTrace();打断点,然后debug,看e里面的详细信息,或者打印message也行。

try {
    report = reportsApi.getReport(reportId.getReportId());
} catch (ApiException e) {
    e.printStackTrace();
}

2、一个获取报告的例子

  • 时间可能要改一下,因为太时间长了就不一定能访问了
package com.rss.server;

import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentialsProvider;
import com.amazon.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import io.swagger.client.ApiException;
import io.swagger.client.api.ReportsApi;
import io.swagger.client.model.CreateReportResponse;
import io.swagger.client.model.CreateReportSpecification;
import io.swagger.client.model.Report;
import io.swagger.client.model.ReportDocument;
import org.threeten.bp.OffsetDateTime;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;

public class MyReport {
    public static void main(String[] args) throws Exception {
        ArrayList<Object> pack = pack_US();
        ReportsApi reportsApi = new ReportsApi.Builder().awsAuthenticationCredentials((AWSAuthenticationCredentials) pack.get(0))
                .awsAuthenticationCredentialsProvider((AWSAuthenticationCredentialsProvider) pack.get(1))
                .lwaAuthorizationCredentials((LWAAuthorizationCredentials) pack.get(2))
                .endpoint(REQUEST_US_EAST_1)//请求地区
                .build();
        CreateReportSpecification body = new CreateReportSpecification();
        body.setMarketplaceIds(Arrays.asList(Pack.US_MARKETPLACE_ID, Pack.CANADA_MARKETPLACE_ID, Pack.Mexico_MARKETPLACE_ID));//MarketplaceId
        body.setReportType("GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL");
        body.setDataStartTime(OffsetDateTime.parse("2022-01-28T00:00:00+08:00"));// 示例:iso_start=OffsetDateTime.parse("2021-03-16T00:00:00Z")
        body.setDataEndTime(OffsetDateTime.parse("2022-02-24T00:00:00+08:00"));
        CreateReportResponse reportId = null;
        try {
            reportId = reportsApi.createReport(body);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        System.out.println(reportId);
        String id = reportId.getReportId();
        Report report = reportsApi.getReport(reportId.getReportId());
//        Report report = reportsApi.getReport("64101019047");
        System.out.println(report);
        System.out.println(report.getProcessingStatus().getValue());
        while (true) {
            Thread.sleep(100000);

            report = reportsApi.getReport(id);
            System.out.println(report);
            System.out.println(report.getProcessingStatus().getValue());
            if (report.getProcessingStatus().getValue().equals("DONE")) {
                ReportDocument reportDocument = reportsApi.getReportDocument(report.getReportDocumentId());
                System.out.println(reportDocument);
                String urlString = reportDocument.getUrl();
                System.out.println(urlString);

                StringBuilder html = new StringBuilder();
                URL url = new URL(urlString);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                InputStreamReader isr = new InputStreamReader(conn.getInputStream());
                BufferedReader br = new BufferedReader(isr);
                String temp;
                while ((temp = br.readLine()) != null) {
                    html.append(temp).append("\n");
                }
                br.close();
                isr.close();
                System.out.println("lalala");
                System.out.println(html.toString());
                System.out.println(html.toString().split("\n")[0].split("\t")[0]);
                break;
            } else if (report.getProcessingStatus().getValue().equals("FATAL") ||
                    report.getProcessingStatus().getValue().equals("CANCELLED") ) {
                System.out.println("fatal");
                break;
            }
        }

    }
}

他会返回一堆字符串,由tab隔开
有这些列

amazon-order-id
merchant-order-id
purchase-date
last-updated-date
order-status
fulfillment-channel
sales-channel
order-channel
ship-service-level
product-name
sku
asin
item-status
quantity
currency
item-price
item-tax
shipping-price
shipping-tax
gift-wrap-price
gift-wrap-tax
item-promotion-discount
ship-promotion-discount
ship-city
ship-state
ship-postal-code
ship-country
promotion-ids
is-business-order
purchase-order-number
price-designation

这是一个例子

amazon-order-id	merchant-order-id	purchase-date	last-updated-date	order-status	fulfillment-channel	sales-channel	order-channel	ship-service-level	product-name	sku	asin	item-status	quantity	currency	item-price	item-tax	shipping-price	shipping-tax	gift-wrap-price	gift-wrap-tax	item-promotion-discount	ship-promotion-discount	ship-city	ship-state	ship-postal-code	ship-country	promotion-ids	is-business-order	purchase-order-number	price-designation
7阿巴阿巴阿巴18		2022-02-21T02:16:01+00:00	2022-02-21T02:18:03+00:00	Ca阿巴阿巴阿巴d	Me阿巴阿巴阿巴nt	Amazon.com.mx	Web阿巴阿巴阿巴el	Standard	Ta阿巴阿巴阿巴 , 阿巴阿 巴阿巴, 阿巴 阿巴 阿巴ig阿巴阿巴阿巴an, W, S	YI阿巴阿巴阿巴-S	B阿巴阿巴阿巴4		0										ZA阿巴阿巴阿巴AS	ZAC阿巴阿巴阿巴S	9阿巴阿巴阿巴0	MX		false		
7阿巴阿巴阿巴04		2022-02-14T03:23:17+00:00	2022-02-16T03:57:56+00:00	S阿巴阿巴阿巴nt	Amazon.com.mx	Webs阿巴阿巴阿巴nel	Standard	Ta阿巴阿巴阿巴 S阿巴阿巴阿巴e su阿巴 阿巴 阿巴to f阿巴阿巴阿巴or 阿巴阿巴阿巴n, W, L	Y阿巴阿巴阿巴L	阿巴阿巴阿巴M5V	Shipped	1	MXN	2496.34		80.0						CUAUTLA (CUAUTLA DE MORELOS)	MO阿巴阿巴S	62747	MX		false	

3、另一个获取报告的例子

  • 获取订单需要提交订单编号,就离谱,后来才发现是可选参数,不传也行,那为什么不重载,哎~~
package com.rss.server;

import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentialsProvider;
import com.amazon.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import io.swagger.client.ApiException;
import io.swagger.client.api.OrdersV0Api;
import io.swagger.client.model.GetOrderAddressResponse;
import io.swagger.client.model.GetOrderBuyerInfoResponse;
import io.swagger.client.model.GetOrderItemsBuyerInfoResponse;
import io.swagger.client.model.GetOrderItemsResponse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 ArrayList<Object> pack = pack_US();
 OrdersV0Api ordersV0Api = new OrdersV0Api.Builder().awsAuthenticationCredentials((AWSAuthenticationCredentials) pack.get(0))
           .awsAuthenticationCredentialsProvider((AWSAuthenticationCredentialsProvider) pack.get(1))
           .lwaAuthorizationCredentials((LWAAuthorizationCredentials) pack.get(2))
           .endpoint("https://sellingpartnerapi-na.amazon.com")//请求地区
           .build();

下面是三个例子

例子1

GetOrderAddressResponse orderAddress = ordersV0Api.getOrderAddress("11阿巴-阿巴阿巴-阿巴-阿巴407");

返回结果

class GetOrderAddressResponse {
    payload: class OrderAddress {
        amazonOrderId: 1阿巴-阿巴阿巴阿巴-阿巴阿巴阿巴
        shippingAddress: class Address {
            name:
            addressLine1: null
            addressLine2: null
            addressLine3: null
            city: MILWAUKEE
            county: null
            district: null
            stateOrRegion: WI
            municipality: null
            postalCode: 53204-1833
            countryCode: US
            phone: null
            addressType: null
        }
    }
    errors: null
}

例子2

GetOrderBuyerInfoResponse orderBuyerInfo = ordersV0Api.getOrderBuyerInfo("1阿巴-阿巴阿巴阿巴-阿巴阿巴阿巴");
class GetOrderBuyerInfoResponse {
    payload: class OrderBuyerInfo {
        amazonOrderId: 1阿巴-阿巴阿巴阿巴-阿巴阿巴阿巴
        buyerEmail: mv阿巴阿巴阿巴3r@marketplace.amazon.com
        buyerName: null
        buyerCounty: null
        buyerTaxInfo: null
        purchaseOrderNumber: null
    }
    errors: null
}

例子3

GetOrderItemsBuyerInfoResponse orderItemsBuyerInfo = ordersV0Api.getOrderItemsBuyerInfo("1阿巴-阿巴阿巴阿巴-阿巴阿巴阿巴", null);
class GetOrderItemsBuyerInfoResponse {
    payload: class OrderItemsBuyerInfoList {
        orderItems: class OrderItemBuyerInfoList {
            [class OrderItemBuyerInfo {
                orderItemId: 阿巴阿巴阿巴阿巴阿巴
                buyerCustomizedInfo: null
                giftWrapPrice: null
                giftWrapTax: null
                giftMessageText: null
                giftWrapLevel: null
            }]
        }
        nextToken: null
        amazonOrderId: 1阿巴-阿巴阿巴阿巴-阿巴阿巴阿巴
    }
    errors: null
}

例子4

getOrderItems的返回结果

class GetOrderItemsResponse {
    payload: class OrderItemsList {
        orderItems: class OrderItemList {
            [class OrderItem {
                ASIN: B阿巴阿巴阿巴M
                sellerSKU: Y阿巴阿巴阿巴XL
                orderItemId: 阿巴阿巴阿巴阿巴阿巴阿巴
                title: XR阿巴阿巴阿巴ie Jac阿巴阿 巴阿巴vis Pri阿巴阿巴阿巴l W阿巴阿巴阿巴hing阿巴阿巴阿巴Ho阿巴阿巴阿巴ng Sle阿巴阿巴阿巴S阿巴阿巴阿巴irt (A,XXL)
                quantityOrdered: 1
                quantityShipped: 1
                productInfo: class ProductInfoDetail {
                    numberOfItems: 1
                }
                pointsGranted: null
                itemPrice: class Money {
                    currencyCode: null
                    amount: null
                }
                shippingPrice: class Money {
                    currencyCode: null
                    amount: null
                }
                itemTax: class Money {
                    currencyCode: null
                    amount: null
                }
                shippingTax: class Money {
                    currencyCode: null
                    amount: null
                }
                shippingDiscount: class Money {
                    currencyCode: null
                    amount: null
                }
                shippingDiscountTax: class Money {
                    currencyCode: null
                    amount: null
                }
                promotionDiscount: class Money {
                    currencyCode: null
                    amount: null
                }
                promotionDiscountTax: class Money {
                    currencyCode: null
                    amount: null
                }
                promotionIds: null
                coDFee: null
                coDFeeDiscount: null
                isGift: false
                conditionNote: null
                conditionId: New
                conditionSubtypeId: New
                scheduledDeliveryStartDate: null
                scheduledDeliveryEndDate: null
                priceDesignation: null
                taxCollection: class TaxCollection {
                    model: MarketplaceFacilitator
                    responsibleParty: Am阿巴阿巴阿巴s, Inc.
                }
                serialNumberRequired: null
                isTransparency: false
                iossNumber: null
                storeChainStoreId: null
                deemedResellerCategory: null
                buyerInfo: class ItemBuyerInfo {
                    buyerCustomizedInfo: null
                    giftWrapPrice: null
                    giftWrapTax: null
                    giftMessageText: null
                    giftWrapLevel: null
                }
            }]
        }
        nextToken: null
        amazonOrderId: 1阿巴阿-阿巴阿巴阿巴-阿巴阿巴阿巴
    }
    errors: null
}

例子5

GetOrdersResponse result = ordersV0Api.getOrders(marketplaceIds, createdAfter, null, null, null, null, null, null, null, null, maxResultsPerPage, null, null, null, null, null, null);

返回结果


class Order {
....省略一些,结构同下
                 amazonOrderId: 1阿巴-阿阿巴巴-阿巴阿巴 
                 sellerOrderId: null
                 purchaseDate: 2022-02-18T00:56:36Z
                 lastUpdateDate: 2022-02-21T02:18:49Z
                 orderStatus: Shipped
                 fulfillmentChannel: MFN
                 salesChannel: Amazon.com
                 orderChannel: null
                 shipServiceLevel: Std US D2D Dom
                 orderTotal: class Money {
                     currencyCode: null
                     amount: null
                 }
                 numberOfItemsShipped: 1
                 numberOfItemsUnshipped: 0
                 paymentExecutionDetail: null
                 paymentMethod: Other
                 paymentMethodDetails: class PaymentMethodDetailItemList {
                     [Standard]
                 }
                 marketplaceId: ATVPDKIKX0DER
                 shipmentServiceLevelCategory: Standard
                 easyShipShipmentStatus: null
                 cbaDisplayableShippingLabel: null
                 orderType: StandardOrder
                 earliestShipDate: 2022-02-18T08:00:00Z
                 latestShipDate: 2022-02-23T07:59:59Z
                 earliestDeliveryDate: 2022-03-11T08:00:00Z
                 latestDeliveryDate: 2022-04-02T06:59:59Z
                 isBusinessOrder: false
                 isPrime: false
                 isPremiumOrder: false
                 isGlobalExpressEnabled: false
                 replacedOrderId: null
                 isReplacementOrder: false
                 promiseResponseDueDate: null
                 isEstimatedShipDateSet: null
                 isSoldByAB: false
                 defaultShipFromLocationAddress: class Address {
                     name: null
                     addressLine1: null
                     addressLine2: null
                     addressLine3: null
                     city: 阿巴
                     county: 阿巴
                     district: null
                     stateOrRegion: 北京
                     municipality: null
                     postalCode: 0阿巴
                     countryCode: CN
                     phone: null
                     addressType: null
                 }
                 buyerInvoicePreference: null
                 buyerTaxInformation: null
                 fulfillmentInstruction: null
                 isISPU: false
                 marketplaceTaxInfo: null
                 sellerDisplayName: null
                 shippingAddress: class Address {
                     name: null
                     addressLine1: null
                     addressLine2: null
                     addressLine3: null
                     city: MIAMI
                     county: null
                     district: null
                     stateOrRegion: FL
                     municipality: null
                     postalCode: 3阿巴0-1阿巴
                     countryCode: US
                     phone: null
                     addressType: null
                 }
                 buyerInfo: class BuyerInfo {
                     buyerEmail: null
                     buyerName: null
                     buyerCounty: null
                     buyerTaxInfo: null
                     purchaseOrderNumber: null
                 }
                 automatedShippingSettings: class AutomatedShippingSettings {
                     hasAutomatedShippingSettings: false
                     automatedCarrier: null
                     automatedShipMethod: null
                 }
             }]
         }
         nextToken: null
         lastUpdatedBefore: null
         createdBefore: 2022-02-22T10:23:57Z
     }
     errors: null
 }

参考文献

https://gitee.com/penghaiping/amazon-sp-api/tree/master/docs/catalogitems

http://events.jianshu.io/p/59affdb25d53

https://github.com/penghaiping/amazon-sp-api/tree/master/docs

https://segmentfault.com/a/1190000040005829?utm_source=sf-similar-article

https://blog.csdn.net/Sanzhutech/article/details/118637423

https://blog.csdn.net/penghaiping1001/article/details/113524366

https://www.spapi.org.cn/cn/model2/_4_appstore.html

http://blog.sina.com.cn/s/blog_7cb308650102w2lm.html

https://developer-docs.amazon.com/sp-api/docs/the-selling-partner-api-sandbox

https://mp.weixin.qq.com/s/fse3FTBNWfY2nDVbpmeG9w

https://www.amazon.com/gp/help/customer/display.html?nodeId=GGGMZK378RQPATDJ

https://www.51tracking.com/api-index?language=Java#%E5%88%9B%E5%BB%BA%E5%A4%9A%E4%B8%AA%E6%9F%A5%E8%AF%A2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值