对接Walmart平台API

参考 :

企业对接Walmart平台API流程(一) - 掘金 (juejin.cn)

沃尔玛(walmart)开放API接口_对接沃尔玛api_zhangfeng1133的博客-CSDN博客

[如何从沃尔玛Marketplace电商平台获得API接口和密钥?-蓝海亿观网 (egainnews.com)](https://www.egainnews.com/article/4502#:~:text=登录沃尔玛卖家中心。 2. 点击“设置”按钮。 3.,然后单击API。 4. 单击API后,将出现API密钥。 注意:如果未出现密钥,则单击“重新生成密钥”即可。)

Walmart API 授权流程解析_https://marketplace.walmartapis.com/v3/token-CSDN博客

开发人员门户Marketplace文档

沃尔玛api接口 - 天心PHP - 博客园 (cnblogs.com)

沃尔玛api验证

使用OAuth(开放验证)基于token验证和授权。

整体思路:首先先将获取到Client ID/Client Secret,将Client ID/Client Secret转码成Base64编码(Authorization),调用获取token的api,获取到WM_SEC.ACCESS_TOKEN

token验证(V3)

验证 authenticaton

  • 登录开发者中心
  • 获取Client ID/Client Secret,从API keys页面。(这个页面是需要先区分你是属于沃尔玛的那个类别的账号;登录进去后获取到Client ID/Client Secret,如果进去里面没法新增和查看就是没有权限,需找人添加)
  • 根据Client ID/Client Secret,通过沃尔玛的Token API,获取token,token有效时长15分钟。
  • 使用下面的头部验证信息来验证API调用,所有的API都需要进行验证。

头部共同验证参数

所有接口必须包含的头部验证参数。

名称 描述 必须 示例
WM_SVC.NAME 沃尔玛服务名称 Yes Walmart Marketplace
WM_QOS.CORRELATION_ID 唯一ID,标识API的调用,用来追踪和调试问题。使用GUID生成随机ID Yes 1234hfvgtr
WM_CONSUMER.CHANNEL.TYPE 唯一ID用来追踪用户请求的频道(美国,加拿大) No 0f3e4dd4-0514-4346-b39d-…使用用户在登录时收到的用户频道
Authorization 基础授权头部。Client ID和Client secret的64位编码 Yes Basic YzcyOTFjNmItNzI5MC00….
WM_SEC.ACCESS_TOKEN 通过Token API获取的token Yes eyJraWQiOiIzZjVhYTFmNS1hYWE5LTQzM…..

授权 authorization

沃尔玛提供了委托访问授权。

委托访问 Delegated Access

  • 在开发中心,选择“API Keys”。
  • 添加方案供应商,设置供应商的权限。每个供应商都会有不同的Client ID/Client Secret
  • 将相应的Client ID/Client Secret信息发给方案供应商。
  • 方案供应商使用Client ID/Client Secret通过Token API来获取访问token。 如果你的方案供应商不在列表,联系沃尔玛。

打开沃尔玛开发者https://developer.walmart.com/

进来之后,根据我们为顾客调用的人那边的账号是什么类别的,总共有四个类别的用户类型(Marketplace Partners1P SuppliersContent ProvidersAdvertising Partners);

正常是 市场合作伙伴-Marketplace Partners

Get started进去的对应的类别进到对应的开发文档里面

首先先理解整体的对接思路:先找到api文档,点击My Account登录找到获取到Client ID/Client Secret(注意这个有权限问题,如果登录进去没法添加或者查看的话,那就是没有权限,或者是登录到账号里面去的setting没有API模块也是没有权限,需找对应的人给你添加权限)

进去后里面有生产模式(真正的生产,谨慎操作)和沙箱模式(测试环境)

重点:可以看到Client ID和 Client Secret

通过Client ID/Client Secret获取到Authorization(基础授权头部。Client ID和Client secret的64位编码)

拼接方式

/**
* 对密钥进行64位编码
*
* @return
*/
private static String getAuthorization(String clientSecret, String clientId) {
//这里注意是clientId在前,clientSecret在后
String str = clientId + ":" + clientSecret;
return "Basic " + Base64.encodeBase64String(str.getBytes());
}

获取到之后再进去对应的api文档,

https://developer.walmart.com/api/us/mp/auth#tag/Authorization

注意这里要获取accesstoken 这个 grant_type=client_credentials;不是refresh_token

进行调用,获取到WM_SEC.ACCESS_TOKEN,用这个WM_SEC.ACCESS_TOKEN就可以去调用其他的API了(查订单,库存…)

在去其他模块进行获取

https://developer.walmart.com/api/us/mp/orders#operation/getAllReleasedOrders

代码模块

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;

import java.util.*;

public class AmazonApi {

static String clientId = "xxxxxxxxx你的clientIdxxxx";

static String clientSecret = "xxxxxxxxx你的clientSecretxxxx";

static String accountName = "Walmart Marketplace"; // WM_SVC.NAME

static String tokenUrl = "https://marketplace.walmartapis.com/v3/token"; //获取token的url

/**
* 对密钥进行编码
*
* @return
*/
private static String getAuthorization(String clientSecret, String clientId) {
String str = clientId + ":" + clientSecret;
return "Basic " + Base64.encodeBase64String(str.getBytes());
}

/**
* 获取accessToken(WM_SEC.ACCESS_TOKEN)
*
* @return
*/
public static String getUSAAccessToken() {
String accessToken;
String authorization = getAuthorization(clientSecret, clientId);
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", authorization);
headers.put("WM_SVC.NAME", accountName);
headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString());

try {
HttpResponse response = HttpRequest.post(tokenUrl)
.addHeaders(headers)
.body("grant_type=client_credentials", "application/x-www-form-urlencoded")
.execute();
JSONObject jsonObject = JSONObject.parseObject(response.body());
accessToken = jsonObject.getString("access_token");
if (accessToken == null) {
System.out.println("获取沃尔玛接口调用凭证失败");
}
} catch (Exception e) {
System.out.println("请求异常");
return null;
}

return accessToken;
}


/**
* 获取所有的未发货订单
* @return
*/
public static void getOrderReleased(){
String usaAccessToken = getUSAAccessToken();
Map<String, String> headers = new HashMap<>();
headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken);
headers.put("WM_SVC.NAME", accountName);
headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString());
//执行请求,获取数据
HttpResponse response = HttpRequest.get("https://marketplace.walmartapis.com/v3/orders/released")
.addHeaders(headers)
.execute();
if (200 == response.getStatus()) {
JSONObject jsonObject = JSONObject.parseObject(response.body());
System.out.println(jsonObject);
}
}

public static void main(String[] args) {
getOrderReleased();
}
}

实战代码:

package com.xinghuo.service.api.walmart;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import com.xinghuo.framework.auth.util.UserUtils;
import com.xinghuo.framework.core.util.HttpUtil;
import com.xinghuo.framework.core.util.ResultData;
import com.xinghuo.service.api.eagle.EagleApi;
import com.xinghuo.service.basic.entity.*;
import com.xinghuo.service.basic.server.mapper.*;
import com.xinghuo.service.basic.server.service.BasOrderGenerationRuleService;
import com.xinghuo.service.common.util.HttpRequestMethedEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/walmart")
public class WalmartApi {

@Value("${walmart.clientId}")
private String clientId;

@Value("${walmart.clientSecret}")
private String clientSecret;

@Value("${walmart.accountName}")
private String accountName;

@Value("${walmart.tokenUrl}")
private String tokenUrl;

@Value("${walmart.sandboxClientId}")
private String sandboxClientId;

@Value("${walmart.sandboxClientSecret}")
private String sandboxClientSecret;

// @Value("${walmart.accountName}")
// private String accountName;

@Value("${walmart.sandboxTokenUrl}")
private String sandboxTokenUrl;

@Autowired
private OrderApiMapper orderApiMapper;
@Autowired
private OrderDetailApiMapper orderDetailApiMapper;
@Autowired
private ReturnApiMapper returnApiMapper;
@Autowired
private ReturnDetailApiMapper returnDetailApiMapper;
@Autowired
private BasOrderGenerationRuleService basOrderGenerationRuleService;
@Autowired
private OutboundMasterMapper outboundMasterMapper;
@Autowired
private OutboundDetailMapper outboundDetailMapper;
@Autowired
private EagleApi eagleApi;

/**
* 对密钥进行编码
*
* @return
*/
private String getAuthorization(String clientId, String clientSecret) {
String str = clientId + ":" + clientSecret;
return "Basic " + Base64.encodeBase64String(str.getBytes());
}

/**
* 获取美国店铺的token
*
* @return
*/
private String getUSAAccessToken(String clientId, String clientSecret, String accountName, String tokenUrl) {
String accessToken;
String authorization = getAuthorization(clientId, clientSecret);
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", authorization);
headers.put("WM_SVC.NAME", accountName);
headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString());
try {
HttpResponse response = HttpRequest.post(tokenUrl)
.addHeaders(headers)
.body("grant_type=client_credentials", "application/x-www-form-urlencoded")
.execute();
JSONObject jsonObject = JSONObject.parseObject(response.body());
accessToken = jsonObject.getString("access_token");
if (accessToken == null) {
System.out.println("获取沃尔玛接口调用凭证失败");
}
} catch (Exception e) {
System.out.println("请求异常");
return null;
}
return accessToken;
}


/**
* 获取所有的刚下单未接单的订单
*/
@RequestMapping("/getOrdersCreated")
@Transactional
public ResultData getOrdersCreated() throws URISyntaxException {
//获取授权token
String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl);
//设置请求头
Map<String, String> headers = new HashMap<>();
headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken);
headers.put("WM_SVC.NAME", accountName);
headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString());
headers.put("Accept", "application/json");
// 获取数据库中沃尔玛平台的时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
//设置参数
HashMap<String, Object> objectObjectHashMap = new HashMap<>();
OrderApi orderApi1 = new OrderApi();
orderApi1.setPlatform("Walmart");
List<OrderApi> orders = orderApiMapper.query(orderApi1);
Date date1 = orderApiMapper.orderMaxDate(orderApi1);
if (null != date1) {
String createdStartDate = simpleDateFormat.format(date1);
objectObjectHashMap.put("createdStartDate", createdStartDate);
}
// objectObjectHashMap.put("status", "Created");
objectObjectHashMap.put("limit", "200");
String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpGet, "https://marketplace.walmartapis.com/v3/orders", objectObjectHashMap, headers);
JSONObject resultObject = JSONObject.parseObject(response);
Map map = (Map) resultObject.get("list");
Map elements = (Map) map.get("elements");
List<Map<String, Object>> orderList = (List<Map<String, Object>>) elements.get("order");
List<OrderApi> orderApiList = new ArrayList<>();
List<OrderDetailApi> orderDetailApiList = new ArrayList<>();
if (!CollectionUtils.isEmpty(orderList)) {
Date date = new Date();
String userCode = UserUtils.getUserCode();
for (Map<String, Object> order : orderList) {
OrderApi orderApi = new OrderApi();
String purchaseOrderId = (String) order.get("purchaseOrderId");
Optional<OrderApi> first = orders.stream().filter(he -> he.getPo().equals(purchaseOrderId)).findFirst();
if (first.isPresent()) {
continue;
}
String customerOrderId = (String) order.get("customerOrderId");
String customerEmailId = (String) order.get("customerEmailId");
long orderDateLong = (long) order.get("orderDate");
Map shippingInfo = (Map) order.get("shippingInfo");
String phone = (String) shippingInfo.get("phone");
long estimatedDeliveryDateLong = (long) shippingInfo.get("estimatedDeliveryDate");
long estimatedShipDateLong = (long) shippingInfo.get("estimatedShipDate");
String methodCode = (String) shippingInfo.get("methodCode");
Map postalAddress = (Map) shippingInfo.get("postalAddress");
String name = (String) postalAddress.get("name");
String address1 = (String) postalAddress.get("address1");
String address2 = (String) postalAddress.get("address2");
String city = (String) postalAddress.get("city");
String state = (String) postalAddress.get("state");
String postalCode = (String) postalAddress.get("postalCode");
String country = (String) postalAddress.get("country");
Map orderLines = (Map) order.get("orderLines");
orderApi.setPo(purchaseOrderId);
orderApi.setPlatform("Walmart");
Date orderDate = new Date(orderDateLong);
orderApi.setPoDate(orderDate);
orderApi.setShipToPhone(phone);
Date estimatedDeliveryDate = new Date(estimatedDeliveryDateLong);
orderApi.setMustShipBy(estimatedDeliveryDate);
orderApi.setShipMethod(methodCode);
orderApi.setShipToName(name);
orderApi.setShipToAddressOne(address1);
orderApi.setShipToAddressTwo(address2);
orderApi.setShipToCity(city);
orderApi.setShipToState(state);
orderApi.setShipToCountry(country);
orderApi.setShipToZip(postalCode);
orderApi.setCreateTime(date);
orderApi.setCreateUser(userCode);
orderApi.setIsHistory("0");
orderApi.setIsOperation("0");
List<Map<String, Object>> orderLine = (List<Map<String, Object>>) orderLines.get("orderLine");
if (!CollectionUtils.isEmpty(orderLine)) {
// List<OrderDetailApi> orderDetailApis = new ArrayList<>();
// List<String> skus = new ArrayList<>();
for (Map<String, Object> line : orderLine) {
OrderDetailApi orderDetailApi = new OrderDetailApi();
orderDetailApi.setCreateTime(date);
orderDetailApi.setCreateUser(userCode);
orderDetailApi.setPo(purchaseOrderId);
orderDetailApi.setIsHistory("0");
String rowNum = (String) line.get("lineNumber");
Map item = (Map) line.get("item");
String sku = (String) item.get("sku");
String productName = (String) item.get("productName");
// if (!skus.contains(sku)) {
// skus.add(sku);
// }
Map charges = (Map) line.get("charges");
orderDetailApi.setRowNum(rowNum);
orderDetailApi.setSku(sku);
List<Map<String, Object>> charge = (List<Map<String, Object>>) charges.get("charge");
if (!CollectionUtils.isEmpty(charge)) {
Map<String, Object> itemPrice = charge.get(0);
Map chargeAmount = (Map) itemPrice.get("chargeAmount");
BigDecimal price = (BigDecimal) chargeAmount.get("amount");
double v = price.doubleValue();
orderDetailApi.setPrice(v);
}
Map orderLineQuantity = (Map) line.get("orderLineQuantity");
String quantity = (String) orderLineQuantity.get("amount");
int qty = Integer.parseInt(quantity);
Map fulfillment = (Map) line.get("fulfillment");
String vendor = (String) fulfillment.get("fulfillmentOption");
Map orderLineStatuses = (Map) line.get("orderLineStatuses");
List<Map<String, Object>> orderLineStatus = (List<Map<String, Object>>) orderLineStatuses.get("orderLineStatus");
if (!CollectionUtils.isEmpty(orderLineStatus)) {
Map<String, Object> itemPrice = orderLineStatus.get(0);
String status = (String) itemPrice.get("status");
orderApi.setStatus(status);
orderDetailApi.setStatus(status);
if (status.equals("Created")) {
orderApi.setIsOperation("0");
} else {
orderApi.setIsOperation("1");
}
}
orderDetailApi.setVendor(vendor);
orderDetailApi.setPoQty(qty);
// orderDetailApis.add(orderDetailApi);
orderDetailApiList.add(orderDetailApi);
}
// for (String sku : skus) {
// List<OrderDetailApi> collect = orderDetailApis.stream().filter(he -> he.getSku().equals(sku)).collect(Collectors.toList());
// if (!CollectionUtils.isEmpty(collect)) {
// OrderDetailApi orderDetailApi = collect.get(0);
// int sum = collect.stream().mapToInt(OrderDetailApi::getPoQty).sum();
// orderDetailApi.setPoQty(sum);
// orderDetailApiList.add(orderDetailApi);
// }
// }
}
orderApiList.add(orderApi);
}
}
try {
if (!CollectionUtils.isEmpty(orderApiList)) {
orderApiMapper.insertBatch(orderApiList);
}
if (!CollectionUtils.isEmpty(orderDetailApiList)) {
orderDetailApiMapper.insertBatch(orderDetailApiList);
}
} catch (Exception exception) {
exception.getMessage();
exception.printStackTrace();
System.out.println(exception.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return ResultData.fail("获取异常" + exception.getMessage());
}
return ResultData.succeed("api获取数据成功总共" + orderApiList.size() + "个订单");
}

/**
* 获取所有的订单
*/
@RequestMapping("/getOrdersAll")
@Transactional
public ResultData getOrdersAll() throws URISyntaxException {
//获取授权token
String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl);
//设置请求头
Map<String, String> headers = new HashMap<>();
headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken);
headers.put("WM_SVC.NAME", accountName);
headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString());
headers.put("Accept", "application/json");
OrderApi orderApi1 = new OrderApi();
orderApi1.setPlatform("Walmart");
List<OrderApi> orders = orderApiMapper.query(orderApi1);
// 获取数据库中沃尔玛平台的时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
//半年前
Calendar instance = Calendar.getInstance();
instance.setTime(new Date());
instance.add(Calendar.MONTH, -6);
Date time = instance.getTime();
String createdStartDate = simpleDateFormat.format(time);
// 设置参数
HashMap<String, Object> objectObjectHashMap = new HashMap<>();
// objectObjectHashMap.put("status","Created");
objectObjectHashMap.put("createdStartDate", createdStartDate);
objectObjectHashMap.put("limit", "200");
String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpGet, "https://marketplace.walmartapis.com/v3/orders", objectObjectHashMap, headers);
JSONObject resultObject = JSONObject.parseObject(response);
Map map = (Map) resultObject.get("list");
Map elements = (Map) map.get("elements");
List<Map<String, Object>> orderList = (List<Map<String, Object>>) elements.get("order");
List<OrderApi> orderApiList = new ArrayList<>();
List<OrderDetailApi> orderDetailApiList = new ArrayList<>();
if (!CollectionUtils.isEmpty(orderList)) {
Date date = new Date();
String userCode = UserUtils.getUserCode();
for (Map<String, Object> order : orderList) {
OrderApi orderApi = new OrderApi();
//采购单号
String purchaseOrderId = (String) order.get("purchaseOrderId");
//订单号
String customerOrderId = (String) order.get("customerOrderId");
Optional<OrderApi> first = orders.stream().filter(he -> he.getPo().equals(purchaseOrderId)).findFirst();
if (first.isPresent()) {
continue;
}
String customerEmailId = (String) order.get("customerEmailId");
long orderDateLong = (long) order.get("orderDate");
Map shippingInfo = (Map) order.get("shippingInfo");
String phone = (String) shippingInfo.get("phone");
long estimatedDeliveryDateLong = (long) shippingInfo.get("estimatedDeliveryDate");
long estimatedShipDateLong = (long) shippingInfo.get("estimatedShipDate");
String methodCode = (String) shippingInfo.get("methodCode");
Map postalAddress = (Map) shippingInfo.get("postalAddress");
String name = (String) postalAddress.get("name");
String address1 = (String) postalAddress.get("address1");
String address2 = (String) postalAddress.get("address2");
String city = (String) postalAddress.get("city");
String state = (String) postalAddress.get("state");
String postalCode = (String) postalAddress.get("postalCode");
String country = (String) postalAddress.get("country");
Map orderLines = (Map) order.get("orderLines");
orderApi.setPo(purchaseOrderId);
orderApi.setPlatform("Walmart");
Date orderDate = new Date(orderDateLong);
orderApi.setPoDate(orderDate);
orderApi.setShipToPhone(phone);
Date estimatedDeliveryDate = new Date(estimatedDeliveryDateLong);
orderApi.setMustShipBy(estimatedDeliveryDate);
orderApi.setShipMethod(methodCode);
orderApi.setShipToName(name);
orderApi.setShipToAddressOne(address1);
orderApi.setShipToAddressTwo(address2);
orderApi.setShipToCity(city);
orderApi.setShipToState(state);
orderApi.setShipToCountry(country);
orderApi.setShipToZip(postalCode);
orderApi.setCreateTime(date);
orderApi.setCreateUser(userCode);
orderApi.setIsHistory("0");
orderApi.setIsOperation("0");
List<Map<String, Object>> orderLine = (List<Map<String, Object>>) orderLines.get("orderLine");
if (!CollectionUtils.isEmpty(orderLine)) {
// List<OrderDetailApi> orderDetailApis = new ArrayList<>();
// List<String> skus = new ArrayList<>();
for (Map<String, Object> line : orderLine) {
OrderDetailApi orderDetailApi = new OrderDetailApi();
orderDetailApi.setCreateTime(date);
orderDetailApi.setCreateUser(userCode);
orderDetailApi.setPo(purchaseOrderId);
orderDetailApi.setIsHistory("0");
String rowNum = (String) line.get("lineNumber");
Map item = (Map) line.get("item");
String sku = (String) item.get("sku");
String productName = (String) item.get("productName");
// if (!skus.contains(sku)) {
// skus.add(sku);
// }
Map charges = (Map) line.get("charges");
orderDetailApi.setRowNum(rowNum);
orderDetailApi.setSku(sku);
List<Map<String, Object>> charge = (List<Map<String, Object>>) charges.get("charge");
if (!CollectionUtils.isEmpty(charge)) {
Map<String, Object> itemPrice = charge.get(0);
Map chargeAmount = (Map) itemPrice.get("chargeAmount");
BigDecimal price = (BigDecimal) chargeAmount.get("amount");
double v = price.doubleValue();
orderDetailApi.setPrice(v);
}
Map orderLineQuantity = (Map) line.get("orderLineQuantity");
String quantity = (String) orderLineQuantity.get("amount");
int qty = Integer.parseInt(quantity);
Map fulfillment = (Map) line.get("fulfillment");
String vendor = (String) fulfillment.get("fulfillmentOption");
Map orderLineStatuses = (Map) line.get("orderLineStatuses");
List<Map<String, Object>> orderLineStatus = (List<Map<String, Object>>) orderLineStatuses.get("orderLineStatus");
if (!CollectionUtils.isEmpty(orderLineStatus)) {
Map<String, Object> itemPrice = orderLineStatus.get(0);
String status = (String) itemPrice.get("status");
orderApi.setStatus(status);
orderDetailApi.setStatus(status);
if (status.equals("Created")) {
orderApi.setIsOperation("0");
} else {
orderApi.setIsOperation("1");
}
}
orderDetailApi.setVendor(vendor);
orderDetailApi.setPoQty(qty);
// orderDetailApis.add(orderDetailApi);
orderDetailApiList.add(orderDetailApi);
}
// for (String sku : skus) {
// List<OrderDetailApi> collect = orderDetailApis.stream().filter(he -> he.getSku().equals(sku)).collect(Collectors.toList());
// if (!CollectionUtils.isEmpty(collect)) {
// OrderDetailApi orderDetailApi = collect.get(0);
// int sum = collect.stream().mapToInt(OrderDetailApi::getPoQty).sum();
// orderDetailApi.setPoQty(sum);
// orderDetailApiList.add(orderDetailApi);
// }
// }
}
orderApiList.add(orderApi);
}
}
try {
if (!CollectionUtils.isEmpty(orderApiList)) {
orderApiMapper.insertBatch(orderApiList);
}
if (!CollectionUtils.isEmpty(orderDetailApiList)) {
orderDetailApiMapper.insertBatch(orderDetailApiList);
}
} catch (Exception exception) {
exception.getMessage();
exception.printStackTrace();
System.out.println(exception.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return ResultData.fail("获取异常" + exception.getMessage());
}
return ResultData.succeed("api获取数据成功总共" + orderApiList.size() + "个订单");
}


/**
* 确定接受订单
*/
@RequestMapping("/acknowledge")
@Transactional
public ResultData acknowledge(OrderApi orderApi) throws URISyntaxException {
//获取授权token
// String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl);
String usaAccessToken = getUSAAccessToken(sandboxClientId, sandboxClientSecret, accountName, sandboxTokenUrl);
//设置请求头
Map<String, String> headers = new HashMap<>();
headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken);
headers.put("WM_SVC.NAME", accountName);
headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString());
headers.put("Accept", "application/json");
// 设置参数
String purchaseOrderId = orderApi.getPo();
if (null == purchaseOrderId || StringUtils.isBlank(purchaseOrderId)) {
return ResultData.fail("请传入订单号");
}
List<OrderApi> orders = orderApiMapper.query(orderApi);
if (orders.size() > 1) {
return ResultData.fail("抓取API的订单" + purchaseOrderId + "出现重复,请仔细核对");
}
if (CollectionUtils.isEmpty(orders)) {
return ResultData.fail("系统没有查到有关于这个" + purchaseOrderId + "的信息");
}
OrderApi orderApi1 = orders.get(0);
OrderDetailApi detailApi = new OrderDetailApi();
detailApi.setPo(purchaseOrderId);
List<OrderDetailApi> orderDetailApiList = orderDetailApiMapper.query(detailApi);
if (CollectionUtils.isEmpty(orderDetailApiList)) {
return ResultData.fail("系统没有查到有关于这个" + purchaseOrderId + "的明细信息");
}
String status = orderApi1.getStatus();
String url = "https://sandbox.walmartapis.com/v3/orders/" + purchaseOrderId + "/acknowledge";
// String url = "https://walmartapis.com/v3/orders/" + purchaseOrderId + "/acknowledge";
if (status.equals("Created")) {
HashMap<String, Object> objectObjectHashMap = new HashMap<>();
String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpPost, url, objectObjectHashMap, headers);
JSONObject resultObject = JSONObject.parseObject(response);
if (null != resultObject) {
List<Map<String, Object>> order = (List<Map<String, Object>>) resultObject.get("order");
if (order.size() == 0) {
return ResultData.fail(purchaseOrderId + "接单失败" + "返回错误结果" + response);
}
Map<String, Object> map = order.get(0);
String apiReturnPurchaseOrderId = (String) map.get("purchaseOrderId");
if (purchaseOrderId.equals(apiReturnPurchaseOrderId)) {
Date date = new Date();
String userCode = UserUtils.getUserCode();
// OrderApi orderApi2 = new OrderApi();
orderApi1.setStatus("Acknowledged");
orderApi1.setUpdateTime(date);
orderApi1.setUpdateUser(userCode);
orderApi1.setIsOperation("1");
OrderDetailApi orderDetailApi = new OrderDetailApi();
orderDetailApi.setPo(purchaseOrderId);
orderDetailApi.setStatus("Acknowledged");
orderDetailApi.setUpdateTime(date);
orderDetailApi.setUpdateUser(userCode);
try {
orderApiMapper.update(orderApi1);
orderDetailApiMapper.update(orderDetailApi);
List<OutboundMaster> outboundMasters = new ArrayList<>();
List<OutboundDetail> outboundDetails = new ArrayList<>();
int i = 0;
for (OrderDetailApi detail : orderDetailApiList) {
i = i + 1;
OutboundMaster outboundMaster1 = new OutboundMaster();
ResultData<String> orderData = basOrderGenerationRuleService.orderGeneration("out_warehousing_order", UserUtils.getUserCode());
if (orderData.getCode() != 200) return orderData;
String orderNum = orderData.getData();
outboundMaster1.setOrder(orderNum);
outboundMaster1.setPo(purchaseOrderId + "-" + i);
outboundMaster1.setOrderType("API");
outboundMaster1.setPoDate(orderApi1.getPoDate());
outboundMaster1.setPlatform(orderApi1.getPlatform());
outboundMaster1.setMustShipBy(orderApi1.getMustShipBy());
outboundMaster1.setStatus("0");
outboundMaster1.setShipMethod(orderApi1.getShipMethod());
outboundMaster1.setCarrierName(orderApi1.getCarrierName());
outboundMaster1.setShippingAccountNumber(orderApi1.getShippingAccountNumber());
outboundMaster1.setShipToName(orderApi1.getShipToName());
outboundMaster1.setShipToAddressOne(orderApi1.getShipToAddressOne());
outboundMaster1.setShipToAddressTwo(orderApi1.getShipToAddressTwo());
outboundMaster1.setShipToAddressThree(orderApi1.getShipToAddressThree());
outboundMaster1.setShipToCity(orderApi1.getShipToCity());
outboundMaster1.setShipToZip(orderApi1.getShipToZip());
outboundMaster1.setShipToPhone(orderApi1.getShipToPhone());
outboundMaster1.setShipToCountry(orderApi1.getShipToCountry());
outboundMaster1.setShipToState(orderApi1.getShipToState());
outboundMaster1.setTrackingNumber(orderApi1.getTrackingNumber());
outboundMaster1.setRemark(orderApi1.getRemark());
outboundMaster1.setCreateTime(date);
outboundMaster1.setCreateUser(userCode);
outboundMaster1.setIsHistory("0");
outboundMaster1.setAuditBatch(1);
OutboundDetail outboundDetail = new OutboundDetail();
outboundDetail.setOrder(orderNum);
outboundDetail.setSku(detail.getSku());
outboundDetail.setPrice(detail.getPrice());
outboundDetail.setWarehouse("WH231215001");
outboundDetail.setOutQty(0);
outboundDetail.setDifferenceQty(0);
outboundDetail.setPoQty(1);
outboundDetail.setVendor(detail.getVendor());
outboundDetail.setRemark(detail.getRemark());
outboundDetail.setCreateUser(userCode);
outboundDetail.setCreateTime(date);
outboundDetail.setIsHistory("0");
outboundMasters.add(outboundMaster1);
outboundDetails.add(outboundDetail);
List<OutboundDetail> outboundDetailList = new ArrayList<>();
outboundDetailList.add(outboundDetail);
outboundMaster1.setDetailList(outboundDetailList);
ResultData order1 = eagleApi.createWalmartOrder(outboundMaster1);
if (order1.getCode() != 200) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return ResultData.fail("将数据回写到鹰仓时出现了异常" + order1.getData());
}
System.out.println(order1);
}
outboundMasterMapper.insertBatch(outboundMasters);
outboundDetailMapper.insertBatch(outboundDetails);
} catch (Exception exception) {
exception.getStackTrace();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return ResultData.fail("接单成功,但是数据在转成销售出库单的时候出现了异常,请联系管理员" + exception.getMessage());
}
} else {
return ResultData.fail("接单的订单号" + purchaseOrderId + "跟接单请求返回的订单号" + apiReturnPurchaseOrderId + "不一样");
}
} else {
return ResultData.fail(purchaseOrderId + "接单请求返回数据为空");
}
} else {
if (status.equals("Cancelled")) {
return ResultData.fail(purchaseOrderId + "订单已被取消");
}
if (status.equals("Acknowledged")) {
return ResultData.fail(purchaseOrderId + "订单已经接单,无需重复接单");
}
}
return ResultData.succeed(purchaseOrderId + "接单成功");
}

/**
* 取消订单
*/
@RequestMapping("/cancel")
@Transactional
public ResultData cancel(OrderApi orderApi) throws URISyntaxException {
//获取授权token
// String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl);
String usaAccessToken = getUSAAccessToken(sandboxClientId, sandboxClientSecret, accountName, sandboxTokenUrl);
//设置请求头
Map<String, String> headers = new HashMap<>();
headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken);
headers.put("WM_SVC.NAME", accountName);
headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString());
headers.put("Accept", "application/json");
// 设置参数
String purchaseOrderId = orderApi.getPo();
if (null == purchaseOrderId || StringUtils.isBlank(purchaseOrderId)) {
return ResultData.fail("请传入订单号");
}
String detailStr = orderApi.getDetailStr();
// List<OrderDetailApi> detail = JSONArray.parseArray(detailStr, OrderDetailApi.class);
// if (CollectionUtils.isEmpty(detail)) {
// return ResultData.fail("请传入要取消的要取消的明细数据");
// }
List<OrderApi> orders = orderApiMapper.query(orderApi);
if (orders.size() > 1) {
return ResultData.fail("抓取API的订单" + purchaseOrderId + "出现重复,请仔细核对");
}
if (CollectionUtils.isEmpty(orders)) {
return ResultData.fail("系统没有查到有关于这个" + purchaseOrderId + "的信息");
}
OrderDetailApi detailApi1 = new OrderDetailApi();
detailApi1.setPo(purchaseOrderId);
List<OrderDetailApi> detailApiList = orderDetailApiMapper.query(detailApi1);
if (CollectionUtils.isEmpty(detailApiList)) {
return ResultData.fail("请传入要取消的要取消的明细数据");
}
OrderApi orderApi1 = orders.get(0);
String status = orderApi1.getStatus();
String url = "https://sandbox.walmartapis.com/v3/orders/" + purchaseOrderId + "/cancel";
// String url = "https://walmartapis.com/v3/orders/" + purchaseOrderId + "/cancel";
if (status.equals("Created")) {
Map<String, Object> objectObjectHashMap = new HashMap<>();
Map<String, Object> orderCancellation = new HashMap<>();
Map<String, Object> orderLines = new HashMap<>();
List<Map<String, Object>> orderLine = new ArrayList<>();
for (OrderDetailApi detailApi : detailApiList) {
detailApi.setCancellationReason("SELLER_CANCEL_OUT_OF_STOCK");
Map<String, Object> orderLineItem = new HashMap<>();
orderLineItem.put("lineNumber", detailApi.getRowNum());
Map<String, Object> orderLineStatuses = new HashMap<>();
List<Map<String, Object>> orderLineStatus = new ArrayList<>();
Map<String, Object> orderLineStatusItem = new HashMap<>();
Map<String, Object> statusQuantity = new HashMap<>();
statusQuantity.put("unitOfMeasurement", "EA");
statusQuantity.put("amount", detailApi.getPoQty().toString());
orderLineStatusItem.put("status", "Cancelled");
//取消订单的原因
orderLineStatusItem.put("cancellationReason", detailApi.getCancellationReason());
orderLineStatusItem.put("statusQuantity", statusQuantity);
orderLineStatus.add(orderLineStatusItem);
orderLineStatuses.put("orderLineStatus", orderLineStatus);
orderLineItem.put("orderLineStatuses", orderLineStatuses);
orderLine.add(orderLineItem);
}
orderLines.put("orderLine", orderLine);
orderCancellation.put("orderLines", orderLines);
objectObjectHashMap.put("orderCancellation", orderCancellation);
String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpPost, url, objectObjectHashMap, headers);
JSONObject resultObject = JSONObject.parseObject(response);
if (null != resultObject) {
List<Map<String, Object>> order = (List<Map<String, Object>>) resultObject.get("order");
if (CollectionUtils.isEmpty(order)) {
return ResultData.fail(purchaseOrderId + "拒单失败" + "返回错误结果" + response);
}
Map<String, Object> map = order.get(0);
String apiReturnPurchaseOrderId = (String) map.get("purchaseOrderId");
if (purchaseOrderId.equals(apiReturnPurchaseOrderId)) {
Date date = new Date();
String userCode = UserUtils.getUserCode();
// OrderApi orderApi2 = new OrderApi();
try {
orderApi1.setStatus("Cancelled");
orderApi1.setUpdateTime(date);
orderApi1.setUpdateUser(userCode);
orderApi1.setIsOperation("1");
OrderDetailApi orderDetailApi = new OrderDetailApi();
orderDetailApi.setPo(purchaseOrderId);
orderDetailApi.setStatus("Cancelled");
orderDetailApi.setUpdateTime(date);
orderDetailApi.setUpdateUser(userCode);
orderApiMapper.update(orderApi1);
orderDetailApiMapper.update(orderDetailApi);
} catch (Exception exception) {
exception.getStackTrace();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return ResultData.fail("拒单成功,但是数据在转成销售出库单的时候出现了异常,请联系管理员" + exception.getMessage());
}
} else {
return ResultData.fail("接单的订单号" + purchaseOrderId + "跟接单请求返回的订单号" + apiReturnPurchaseOrderId + "不一样");
}
} else {
return ResultData.fail(purchaseOrderId + "接单请求返回数据为空");
}
} else {
if (status.equals("Acknowledged")) {
return ResultData.fail(purchaseOrderId + "订单已接单了,无法进行取消");
}
if (status.equals("Cancelled")) {
return ResultData.fail(purchaseOrderId + "订单已取消,无需重复取消");
}
}
return ResultData.succeed(purchaseOrderId + "取消订单成功");
}


/**
* 获取全部退货单
*/
@RequestMapping("/getReturnAll")
@Transactional
public ResultData getReturnAll() throws URISyntaxException, ParseException {
//获取授权token
String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl);
//设置请求头
Map<String, String> headers = new HashMap<>();
headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken);
headers.put("WM_SVC.NAME", accountName);
headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString());
headers.put("Accept", "application/json");
ReturnApi returnApi1 = new ReturnApi();
returnApi1.setPlatform("Walmart");
List<ReturnApi> returnApis = returnApiMapper.query(returnApi1);
// 获取数据库中沃尔玛平台的时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date now = new Date();
//半年前
Calendar instance = Calendar.getInstance();
instance.setTime(new Date());
instance.add(Calendar.MONTH, -6);
Date time = instance.getTime();
String returnCreationStartDate = simpleDateFormat.format(time);
String returnCreationEndDate = simpleDateFormat.format(now);
// 设置参数
HashMap<String, Object> objectObjectHashMap = new HashMap<>();
// objectObjectHashMap.put("status","Created");
objectObjectHashMap.put("returnCreationStartDate", returnCreationStartDate);
objectObjectHashMap.put("returnCreationEndDate", returnCreationEndDate);
objectObjectHashMap.put("limit", "200");
String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpGet, "https://marketplace.walmartapis.com/v3/returns", objectObjectHashMap, headers);
JSONObject resultObject = JSONObject.parseObject(response);
List<Map<String, Object>> returnOrders = (List<Map<String, Object>>) resultObject.get("returnOrders");
List<ReturnApi> returnApiList = new ArrayList<>();
List<ReturnDetailApi> returnDetailApiList = new ArrayList<>();
if (!CollectionUtils.isEmpty(returnOrders)) {
String userCode = UserUtils.getUserCode();
for (Map<String, Object> order : returnOrders) {
ReturnApi returnApi = new ReturnApi();
//退货单号
String returnOrderId = (String) order.get("returnOrderId");
Optional<ReturnApi> first1 = returnApis.stream().filter(he -> he.getReturnNum().equals(returnOrderId)).findFirst();
if (first1.isPresent()) {
continue;
}
//客户邮箱地址
String customerEmailId = (String) order.get("customerEmailId");
//客户信息
Map customerName = (Map) order.get("customerName");
String firstName = (String) customerName.get("firstName");
String lastName = (String) customerName.get("lastName");
//客户订单号
String customerOrderId = (String) order.get("customerOrderId");
//退货时间
String orderDateStr = (String) order.get("returnOrderDate");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
orderDateStr = orderDateStr.replace("Z", " UTC");
Date orderDate = format.parse(orderDateStr);
String returnByDateStr = (String) order.get("returnByDate");
returnByDateStr = returnByDateStr.replace("Z", " UTC");
Date returnByDate = format.parse(returnByDateStr);
returnApi.setReturnNum(returnOrderId);
returnApi.setIssueDate(orderDate);
returnApi.setReturnConfirmationTime(returnByDate);
List<Map<String, String>> tackInfos = new ArrayList<>();
List<Map<String, Object>> returnLineGroups = (List<Map<String, Object>>) order.get("returnLineGroups");
if (!CollectionUtils.isEmpty(returnLineGroups)) {
Map<String, String> tack = new HashMap<>();
for (Map<String, Object> returnLineGroup : returnLineGroups) {
List<Map<String, Object>> returnLines = (List<Map<String, Object>>) returnLineGroup.get("returnLines");
if (!CollectionUtils.isEmpty(returnLines)) {
Map<String, Object> map = returnLines.get(0);
Integer returnOrderLineNumber = (Integer) map.get("returnOrderLineNumber");
tack.put("returnOrderLineNumber", returnOrderLineNumber.toString());
}
List<Map<String, Object>> labels = (List<Map<String, Object>>) returnLineGroup.get("labels");
if (!CollectionUtils.isEmpty(labels)) {
Map<String, Object> map = labels.get(0);
List<Map<String, Object>> carrierInfoList = (List<Map<String, Object>>) map.get("carrierInfoList");
if (!CollectionUtils.isEmpty(carrierInfoList)) {
Map<String, Object> carrierInfo = carrierInfoList.get(0);
String carrierName = (String) carrierInfo.get("carrierName");
String trackingNo = (String) carrierInfo.get("trackingNo");
tack.put("carrierName", carrierName);
tack.put("trackingNo", trackingNo);
}
}
}
tackInfos.add(tack);
}
List<Map<String, Object>> returnOrderLines = (List<Map<String, Object>>) order.get("returnOrderLines");
if (!CollectionUtils.isEmpty(returnOrderLines)) {
for (Map<String, Object> returnOrderLine : returnOrderLines) {
//退料行号
Integer returnOrderLineNumber = (Integer) returnOrderLine.get("returnOrderLineNumber");
//采购单号行号
Integer rowNum = (Integer) returnOrderLine.get("purchaseOrderLineNumber");
//采购单号
String purchaseOrderId = (String) returnOrderLine.get("purchaseOrderId");
//退货原因
String returnReason = (String) returnOrderLine.get("returnReason");
Map item = (Map) returnOrderLine.get("item");
//sku
String sku = (String) item.get("sku");
Map unitPrice = (Map) returnOrderLine.get("unitPrice");
//价格
BigDecimal currencyAmount = (BigDecimal) unitPrice.get("currencyAmount");
double price = currencyAmount.doubleValue();
Map quantity = (Map) returnOrderLine.get("quantity");
BigDecimal measurementValue = (BigDecimal) quantity.get("measurementValue");
//数量
int qty = measurementValue.intValue();
//状态
String status = (String) returnOrderLine.get("status");
ReturnDetailApi returnDetailApi = new ReturnDetailApi();
returnDetailApi.setReturnNum(returnOrderId);
returnDetailApi.setSku(sku);
returnDetailApi.setStatus(status);
returnDetailApi.setQty(qty);
returnDetailApi.setReturnReason(returnReason);
returnDetailApi.setRowNum(returnOrderLineNumber.toString());
Optional<Map<String, String>> first = tackInfos.stream().filter(he -> he.get("returnOrderLineNumber").equals(returnOrderLineNumber.toString())).findFirst();
if (first.isPresent()) {
Map<String, String> track = first.get();
String carrierName = track.get("carrierName");
String trackingNo = track.get("trackingNo");
returnDetailApi.setCarrier(carrierName);
returnDetailApi.setTrackingNum(trackingNo);
}
returnDetailApi.setCreateTime(now);
returnDetailApi.setCreateUser(userCode);
returnDetailApi.setIsHistory("0");
returnDetailApiList.add(returnDetailApi);
returnApi.setPo(purchaseOrderId);
returnApi.setStatus(status);
returnApi.setReturnReason(returnReason);
}
}
returnApi.setPlatform("Walmart");
returnApi.setCreateTime(now);
returnApi.setCreateUser(userCode);
returnApi.setIsHistory("0");
returnApi.setIsOperation("0");
returnApiList.add(returnApi);
}
}
try {
if (!CollectionUtils.isEmpty(returnApiList)) {
returnApiMapper.insertBatch(returnApiList);
}
if (!CollectionUtils.isEmpty(returnDetailApiList)) {
returnDetailApiMapper.insertBatch(returnDetailApiList);
}
} catch (Exception exception) {
exception.getMessage();
exception.printStackTrace();
System.out.println(exception.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return ResultData.fail("获取异常" + exception.getMessage());
}
return ResultData.succeed("api获取数据成功总共" + returnApiList.size() + "个订单");
}

/**
* 获取同步退货单
*/
@RequestMapping("/getReturnNew")
@Transactional
public ResultData getReturnNew() throws URISyntaxException, ParseException {
//获取授权token
String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl);
//设置请求头
Map<String, String> headers = new HashMap<>();
headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken);
headers.put("WM_SVC.NAME", accountName);
headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString());
headers.put("Accept", "application/json");
ReturnApi returnApi1 = new ReturnApi();
returnApi1.setPlatform("Walmart");
List<ReturnApi> returnApis = returnApiMapper.query(returnApi1);
Date date = returnApiMapper.orderMaxDate(returnApi1);
// 设置参数
HashMap<String, Object> objectObjectHashMap = new HashMap<>();
// 获取数据库中沃尔玛平台的时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date now = new Date();
if (null != date) {
String returnCreationStartDate = simpleDateFormat.format(date);
String returnCreationEndDate = simpleDateFormat.format(now);
objectObjectHashMap.put("returnCreationStartDate", returnCreationStartDate);
objectObjectHashMap.put("returnCreationEndDate", returnCreationEndDate);
}
//status INITIATED, DELIVERED, COMPLETED
// objectObjectHashMap.put("status","INITIATED");
objectObjectHashMap.put("limit", "200");
String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpGet, "https://marketplace.walmartapis.com/v3/returns", objectObjectHashMap, headers);
JSONObject resultObject = JSONObject.parseObject(response);
List<Map<String, Object>> returnOrders = (List<Map<String, Object>>) resultObject.get("returnOrders");
List<ReturnApi> returnApiList = new ArrayList<>();
List<ReturnDetailApi> returnDetailApiList = new ArrayList<>();
if (!CollectionUtils.isEmpty(returnOrders)) {
String userCode = UserUtils.getUserCode();
for (Map<String, Object> order : returnOrders) {
ReturnApi returnApi = new ReturnApi();
//退货单号
String returnOrderId = (String) order.get("returnOrderId");
Optional<ReturnApi> first1 = returnApis.stream().filter(he -> he.getReturnNum().equals(returnOrderId)).findFirst();
if (first1.isPresent()) {
continue;
}
//客户邮箱地址
String customerEmailId = (String) order.get("customerEmailId");
//客户信息
Map customerName = (Map) order.get("customerName");
String firstName = (String) customerName.get("firstName");
String lastName = (String) customerName.get("lastName");
//客户订单号
String customerOrderId = (String) order.get("customerOrderId");
//退货时间
String orderDateStr = (String) order.get("returnOrderDate");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
orderDateStr = orderDateStr.replace("Z", " UTC");
Date orderDate = format.parse(orderDateStr);
String returnByDateStr = (String) order.get("returnByDate");
returnByDateStr = returnByDateStr.replace("Z", " UTC");
Date returnByDate = format.parse(returnByDateStr);
returnApi.setReturnNum(returnOrderId);
returnApi.setIssueDate(orderDate);
returnApi.setReturnConfirmationTime(returnByDate);
List<Map<String, String>> tackInfos = new ArrayList<>();
List<Map<String, Object>> returnLineGroups = (List<Map<String, Object>>) order.get("returnLineGroups");
if (!CollectionUtils.isEmpty(returnLineGroups)) {
Map<String, String> tack = new HashMap<>();
for (Map<String, Object> returnLineGroup : returnLineGroups) {
List<Map<String, Object>> returnLines = (List<Map<String, Object>>) returnLineGroup.get("returnLines");
if (!CollectionUtils.isEmpty(returnLines)) {
Map<String, Object> map = returnLines.get(0);
Integer returnOrderLineNumber = (Integer) map.get("returnOrderLineNumber");
tack.put("returnOrderLineNumber", returnOrderLineNumber.toString());
}
List<Map<String, Object>> labels = (List<Map<String, Object>>) returnLineGroup.get("labels");
if (!CollectionUtils.isEmpty(labels)) {
Map<String, Object> map = labels.get(0);
List<Map<String, Object>> carrierInfoList = (List<Map<String, Object>>) map.get("carrierInfoList");
if (!CollectionUtils.isEmpty(carrierInfoList)) {
Map<String, Object> carrierInfo = carrierInfoList.get(0);
String carrierName = (String) carrierInfo.get("carrierName");
String trackingNo = (String) carrierInfo.get("trackingNo");
tack.put("carrierName", carrierName);
tack.put("trackingNo", trackingNo);
}
}
}
tackInfos.add(tack);
}
List<Map<String, Object>> returnOrderLines = (List<Map<String, Object>>) order.get("returnOrderLines");
if (!CollectionUtils.isEmpty(returnOrderLines)) {
for (Map<String, Object> returnOrderLine : returnOrderLines) {
//退料行号
Integer returnOrderLineNumber = (Integer) returnOrderLine.get("returnOrderLineNumber");
//采购单号行号
Integer rowNum = (Integer) returnOrderLine.get("purchaseOrderLineNumber");
//采购单号
String purchaseOrderId = (String) returnOrderLine.get("purchaseOrderId");
//退货原因
String returnReason = (String) returnOrderLine.get("returnReason");
Map item = (Map) returnOrderLine.get("item");
//sku
String sku = (String) item.get("sku");
Map unitPrice = (Map) returnOrderLine.get("unitPrice");
//价格
BigDecimal currencyAmount = (BigDecimal) unitPrice.get("currencyAmount");
double price = currencyAmount.doubleValue();
Map quantity = (Map) returnOrderLine.get("quantity");
BigDecimal measurementValue = (BigDecimal) quantity.get("measurementValue");
//数量
int qty = measurementValue.intValue();
//状态
String status = (String) returnOrderLine.get("status");
ReturnDetailApi returnDetailApi = new ReturnDetailApi();
returnDetailApi.setReturnNum(returnOrderId);
returnDetailApi.setSku(sku);
returnDetailApi.setStatus(status);
returnDetailApi.setQty(qty);
returnDetailApi.setReturnReason(returnReason);
returnDetailApi.setRowNum(returnOrderLineNumber.toString());
Optional<Map<String, String>> first = tackInfos.stream().filter(he -> he.get("returnOrderLineNumber").equals(returnOrderLineNumber.toString())).findFirst();
if (first.isPresent()) {
Map<String, String> track = first.get();
String carrierName = track.get("carrierName");
String trackingNo = track.get("trackingNo");
returnDetailApi.setCarrier(carrierName);
returnDetailApi.setTrackingNum(trackingNo);
}
returnDetailApi.setCreateTime(now);
returnDetailApi.setCreateUser(userCode);
returnDetailApi.setIsHistory("0");
returnDetailApiList.add(returnDetailApi);
returnApi.setPo(purchaseOrderId);
returnApi.setStatus(status);
returnApi.setReturnReason(returnReason);
}
}
returnApi.setPlatform("Walmart");
returnApi.setCreateTime(now);
returnApi.setCreateUser(userCode);
returnApi.setIsHistory("0");
returnApi.setIsOperation("0");
returnApiList.add(returnApi);
}
}
try {
if (!CollectionUtils.isEmpty(returnApiList)) {
returnApiMapper.insertBatch(returnApiList);
}
if (!CollectionUtils.isEmpty(returnDetailApiList)) {
returnDetailApiMapper.insertBatch(returnDetailApiList);
}
} catch (Exception exception) {
exception.getMessage();
exception.printStackTrace();
System.out.println(exception.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return ResultData.fail("获取异常" + exception.getMessage());
}
return ResultData.succeed("api获取数据成功总共" + returnApiList.size() + "个订单");
}


/**
* 库存同步
*/
@RequestMapping("/feeds")
@Transactional
public ResultData feeds(MultipartFile file) throws URISyntaxException {
//获取授权token
String usaAccessToken = getUSAAccessToken(clientId, clientSecret, accountName, tokenUrl);
//设置请求头
Map<String, String> headers = new HashMap<>();
headers.put("WM_SEC.ACCESS_TOKEN", usaAccessToken);
headers.put("WM_SVC.NAME", accountName);
headers.put("WM_QOS.CORRELATION_ID", UUID.randomUUID().toString());
headers.put("Accept", "application/json");
//设置参数
HashMap<String, Object> objectObjectHashMap = new HashMap<>();
objectObjectHashMap.put("file", file);
String response = HttpUtil.sendHttp(HttpRequestMethedEnum.HttpPost, "https://sandbox.walmartapis.com/v3/feeds?feedType=inventory", objectObjectHashMap, headers);
JSONObject resultObject = JSONObject.parseObject(response);
if (null == resultObject.get("feedId")) {
return ResultData.fail("批量更新库存出现异常" + response);
}
return ResultData.succeed("库存批量更新成功");
}
}