跨境电商技术架构 亚马逊SP-API API集成 代码示例

亚马逊SP-API调用示例完全指南

作者: API专家 | 发布于: 2025年5月1日

亚马逊SP-API调用示例完全指南

亚马逊Selling Partner API (SP-API)是跨境电商卖家与亚马逊平台集成的核心接口。本文将提供详细的SP-API调用示例和最佳实践,帮助开发者快速实现系统集成。

SP-API概述

SP-API是亚马逊提供的新一代API,用于替代旧版MWS API。它提供了更丰富的功能、更好的性能和更高的安全性。SP-API涵盖了以下主要功能领域:

  • 卖家账户管理
  • 商品管理
  • 订单管理
  • 物流管理
  • 财务管理
  • 报告管理

环境准备

在开始调用SP-API之前,需要完成以下准备工作:

  1. 注册亚马逊开发者账号
  2. 创建SP-API应用程序
  3. 配置IAM权限
  4. 获取卖家授权

基础调用示例

下面是一个基础的SP-API调用示例,用于获取卖家支持的市场:

import { SellingPartnerAPI } from 'amazon-sp-api';

// 配置SP-API凭证
const spApi = new SellingPartnerAPI({
  region: 'NA', // 北美地区
  refresh_token: 'YOUR_REFRESH_TOKEN',
  credentials: {
    SELLING_PARTNER_APP_CLIENT_ID: 'YOUR_APP_CLIENT_ID',
    SELLING_PARTNER_APP_CLIENT_SECRET: 'YOUR_APP_CLIENT_SECRET',
    AWS_ACCESS_KEY_ID: 'YOUR_AWS_ACCESS_KEY',
    AWS_SECRET_ACCESS_KEY: 'YOUR_AWS_SECRET_KEY',
    AWS_SELLING_PARTNER_ROLE: 'YOUR_ROLE_ARN'
  }
});

// 获取卖家账户支持的市场
async function getMarketplaces() {
  try {
    const res = await spApi.callAPI({
      operation: 'getMarketplaceParticipations',
      endpoint: 'sellers'
    });
    return res;
  } catch (error) {
    console.error('API调用失败:', error);
    throw error;
  }
}

// 调用示例
getMarketplaces()
  .then(result => console.log(JSON.stringify(result, null, 2)))
  .catch(error => console.error('获取市场失败:', error));

订单管理API示例

获取订单列表

async function getOrders() {
  try {
    const createdAfter = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
    
    const res = await spApi.callAPI({
      operation: 'getOrders',
      endpoint: 'orders',
      query: {
        MarketplaceIds: ['ATVPDKIKX0DER'], // 美国市场
        CreatedAfter: createdAfter,
        OrderStatuses: ['Unshipped', 'PartiallyShipped']
      }
    });
    
    return res;
  } catch (error) {
    console.error('获取订单失败:', error);
    throw error;
  }
}

获取订单详情

async function getOrderDetails(orderId) {
  try {
    const res = await spApi.callAPI({
      operation: 'getOrder',
      endpoint: 'orders',
      path: {
        orderId: orderId
      }
    });
    
    return res;
  } catch (error) {
    console.error(`获取订单详情失败 (${orderId}):`, error);
    throw error;
  }
}

商品管理API示例

获取商品列表

async function getInventory() {
  try {
    const res = await spApi.callAPI({
      operation: 'getInventorySummaries',
      endpoint: 'fba-inventory',
      query: {
        marketplaceIds: ['ATVPDKIKX0DER'], // 美国市场
        granularityType: 'Marketplace',
        granularityId: 'ATVPDKIKX0DER'
      }
    });
    
    return res;
  } catch (error) {
    console.error('获取库存失败:', error);
    throw error;
  }
}

更新商品价格

async function updatePrice(sku, price) {
  try {
    const res = await spApi.callAPI({
      operation: 'putListingPrice',
      endpoint: 'listings-items',
      path: {
        sellerId: 'YOUR_SELLER_ID',
        sku: sku
      },
      body: {
        patchOperation: 'replace',
        issue: 'PRICING',
        patches: [
          {
            op: 'replace',
            path: '/price',
            value: {
              value: price,
              currency: 'USD'
            }
          }
        ]
      }
    });
    
    return res;
  } catch (error) {
    console.error(`更新价格失败 (${sku}):`, error);
    throw error;
  }
}

报告API示例

请求报告

async function requestReport(reportType) {
  try {
    const res = await spApi.callAPI({
      operation: 'createReport',
      endpoint: 'reports',
      body: {
        reportType: reportType,
        marketplaceIds: ['ATVPDKIKX0DER'] // 美国市场
      }
    });
    
    return res;
  } catch (error) {
    console.error(`请求报告失败 (${reportType}):`, error);
    throw error;
  }
}

获取报告状态

async function getReportStatus(reportId) {
  try {
    const res = await spApi.callAPI({
      operation: 'getReport',
      endpoint: 'reports',
      path: {
        reportId: reportId
      }
    });
    
    return res;
  } catch (error) {
    console.error(`获取报告状态失败 (${reportId}):`, error);
    throw error;
  }
}

下载报告

async function downloadReport(reportDocumentId) {
  try {
    // 获取报告文档信息
    const documentInfo = await spApi.callAPI({
      operation: 'getReportDocument',
      endpoint: 'reports',
      path: {
        reportDocumentId: reportDocumentId
      }
    });
    
    // 下载报告内容
    const reportContent = await spApi.download(documentInfo);
    
    return reportContent;
  } catch (error) {
    console.error(`下载报告失败 (${reportDocumentId}):`, error);
    throw error;
  }
}

错误处理最佳实践

SP-API调用中的错误处理是关键环节,以下是最佳实践:

async function callApiWithErrorHandling(operation) {
  try {
    return await operation();
  } catch (error) {
    // 处理限流错误
    if (error.code === 'QuotaExceeded' || error.code === 'ThrottlingException') {
      console.warn('API调用被限流,将在短暂延迟后重试');
      await sleep(2000); // 等待2秒
      return callApiWithErrorHandling(operation); // 重试
    }
    
    // 处理授权错误
    if (error.code === 'Unauthorized' || error.code === 'AccessDenied') {
      console.error('授权错误,请检查凭证');
      // 可能需要刷新令牌
      await refreshTokens();
      return callApiWithErrorHandling(operation); // 重试
    }
    
    // 处理其他错误
    console.error('API调用失败:', error);
    throw error;
  }
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

性能优化技巧

1. 批量处理

尽可能使用批量API,减少API调用次数:

// 批量更新价格示例
async function updatePricesBatch(priceUpdates) {
  const batches = [];
  
  // 将更新分成最多20个项目的批次
  for (let i = 0; i < priceUpdates.length; i += 20) {
    batches.push(priceUpdates.slice(i, i + 20));
  }
  
  const results = [];
  
  for (const batch of batches) {
    try {
      const res = await spApi.callAPI({
        operation: 'putListingPricesBatch',
        endpoint: 'listings-items',
        body: {
          requests: batch.map(item => ({
            sellerId: 'YOUR_SELLER_ID',
            sku: item.sku,
            patchOperation: 'replace',
            issue: 'PRICING',
            patches: [
              {
                op: 'replace',
                path: '/price',
                value: {
                  value: item.price,
                  currency: 'USD'
                }
              }
            ]
          }))
        }
      });
      
      results.push(res);
    } catch (error) {
      console.error('批量更新价格失败:', error);
      throw error;
    }
  }
  
  return results;
}

2. 缓存策略

实现有效的缓存策略,减少重复API调用:

class ApiCache {
  private cache = new Map();
  
  async getWithCache(cacheKey, ttlMs, fetchFunction) {
    const cachedItem = this.cache.get(cacheKey);
    
    if (cachedItem && cachedItem.expiry > Date.now()) {
      return cachedItem.data;
    }
    
    // 缓存未命中或已过期,调用API
    const data = await fetchFunction();
    
    // 更新缓存
    this.cache.set(cacheKey, {
      data,
      expiry: Date.now() + ttlMs
    });
    
    return data;
  }
  
  invalidate(cacheKey) {
    this.cache.delete(cacheKey);
  }
}

// 使用示例
const apiCache = new ApiCache();

async function getMarketplacesWithCache() {
  return apiCache.getWithCache(
    'marketplaces',
    24 * 60 * 60 * 1000, // 24小时缓存
    () => getMarketplaces()
  );
}

实际应用案例

订单同步系统

以下是一个完整的订单同步系统示例:

class OrderSyncService {
  private spApi;
  private lastSyncTime;
  
  constructor(spApiConfig) {
    this.spApi = new SellingPartnerAPI(spApiConfig);
    this.lastSyncTime = this.getLastSyncTimeFromStorage();
  }
  
  async syncOrders() {
    try {
      // 获取上次同步后的新订单
      const newOrders = await this.fetchNewOrders();
      
      // 处理新订单
      for (const order of newOrders) {
        await this.processOrder(order);
      }
      
      // 更新同步时间
      this.updateLastSyncTime();
      
      return {
        success: true,
        ordersProcessed: newOrders.length
      };
    } catch (error) {
      console.error('订单同步失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }
  
  private async fetchNewOrders() {
    const createdAfter = this.lastSyncTime.toISOString();
    
    const response = await this.spApi.callAPI({
      operation: 'getOrders',
      endpoint: 'orders',
      query: {
        MarketplaceIds: ['ATVPDKIKX0DER'], // 美国市场
        CreatedAfter: createdAfter
      }
    });
    
    return response.Orders || [];
  }
  
  private async processOrder(order) {
    // 获取订单详情
    const orderDetails = await this.fetchOrderDetails(order.AmazonOrderId);
    
    // 获取订单商品
    const orderItems = await this.fetchOrderItems(order.AmazonOrderId);
    
    // 将订单保存到系统
    await this.saveOrderToDatabase({
      ...orderDetails,
      items: orderItems
    });
    
    // 触发后续处理流程
    await this.triggerOrderProcessing(order.AmazonOrderId);
  }
  
  private async fetchOrderDetails(orderId) {
    const response = await this.spApi.callAPI({
      operation: 'getOrder',
      endpoint: 'orders',
      path: {
        orderId: orderId
      }
    });
    
    return response.Order;
  }
  
  private async fetchOrderItems(orderId) {
    const response = await this.spApi.callAPI({
      operation: 'getOrderItems',
      endpoint: 'orders',
      path: {
        orderId: orderId
      }
    });
    
    return response.OrderItems || [];
  }
  
  private getLastSyncTimeFromStorage() {
    // 从持久化存储中获取上次同步时间
    // 如果没有,返回7天前的时间
    return new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  }
  
  private updateLastSyncTime() {
    // 更新同步时间为当前时间
    this.lastSyncTime = new Date();
    // 保存到持久化存储
  }
  
  private async saveOrderToDatabase(order) {
    // 将订单保存到数据库
    // ...
  }
  
  private async triggerOrderProcessing(orderId) {
    // 触发订单处理流程
    // ...
  }
}

结论

SP-API为跨境电商卖家提供了强大的系统集成能力。通过本文提供的调用示例和最佳实践,开发者可以快速实现与亚马逊平台的无缝集成,提升业务运营效率。

在实际应用中,建议结合错误处理、性能优化和缓存策略,构建稳定、高效的集成系统。同时,随着业务规模的扩大,可以考虑引入更复杂的架构,如消息队列、事件驱动等模式,进一步提升系统的可扩展性和可靠性。

在未来的文章中,我们将深入探讨SP-API的高级应用场景,如多账户管理、跨区域部署等话题。

目录

加载中...