手把手教你接入速卖通 API:开发商品详情实时数据采集接口

113 阅读4分钟

一、速卖通 API 接入准备

在开始开发商品详情数据采集接口之前,你需要完成以下准备工作:

  1. 注册账号
    访问注册获取**ApiKey**和ApiSecret

  2. 获取访问令牌 (Access Token)

    • 通过授权流程获取用户授权
    • 保存并管理获取到的 Access Token
  3. 了解 API 文档

    • 熟悉API文档
    • 重点关注商品信息相关 API

二、API 请求签名机制

速卖通 API 使用 MD5 签名算法保证请求的安全性,签名生成步骤如下:

  1. 将所有请求参数(除 sign 外)按照参数名的字典序排序
  2. 将排序后的参数名和参数值拼接成一个字符串
  3. 在拼接字符串前加上 AppSecret
  4. 对拼接后的字符串进行 MD5 加密并转换为大写

以下是 Python 实现的签名生成函数:

def generate_signature(self, params):
    """生成API请求签名"""
    # 按参数名排序
    sorted_params = sorted(params.items(), key=lambda x: x[0])
    # 拼接参数名和参数值
    string_to_sign = self.app_secret + ''.join([k + str(v) for k, v in sorted_params])
    # 计算MD5哈希
    signature = hashlib.md5(string_to_sign.encode('utf-8')).hexdigest().upper()
    return signature

 

三、商品详情 API 接入实现

1. API 客户端初始化

首先需要创建一个 API 客户端类,初始化必要的认证信息:

class AliexpressAPI:
    def __init__(self, app_key, app_secret, access_token=None):
        """初始化速卖通API客户端"""
        self.app_key = app_key
        self.app_secret = app_secret
        self.access_token = access_token
        self.server_url = "https://gw.api.alibaba.com/openapi/param2/2/aliexpress.open/api.listProducts"

 

2. 单个商品详情获取

实现获取单个商品详情的方法:

def get_product_details(self, product_id, fields=None):
    """获取单个商品详情"""
    if fields is None:
        fields = ["productId", "productTitle", "salePrice", "originalPrice", 
                  "productUrl", "imageUrl", "quantity", "categoryId"]
    
    # 构建请求参数
    params = {
        "appKey": self.app_key,
        "timestamp": int(time.time() * 1000),
        "format": "json",
        "method": "aliexpress.open.api.getProductDetail",
        "sign_method": "md5",
        "session": self.access_token,
        "product_id": product_id,
        "fields": ",".join(fields)
    }
    
    # 生成签名
    params["sign"] = self.generate_signature(params)
    
    try:
        # 发送请求
        response = requests.post(self.server_url, data=params)
        response.raise_for_status()  # 检查请求是否成功
        result = response.json()
        
        # 处理API返回结果
        if "error_response" in result:
            error = result["error_response"]
            logger.error(f"API请求失败: {error['code']} - {error['msg']}")
            return None
        else:
            return result.get("aliexpress_open_api_getproductdetail_response", {})
    except requests.exceptions.RequestException as e:
        logger.error(f"请求异常: {e}")
        return None
    except json.JSONDecodeError as e:
        logger.error(f"JSON解析错误: {e}")
        return None

 

3. 批量获取商品详情

为了提高效率,实现批量获取多个商品详情的方法:

def batch_get_products(self, product_ids, fields=None):
    """批量获取商品详情"""
    results = {}
    for product_id in product_ids:
        product_data = self.get_product_details(product_id, fields)
        if product_data:
            results[product_id] = product_data
        # 控制请求频率,避免触发限流
        time.sleep(1)
    return results

 

四、数据处理与存储

获取到商品详情数据后,你可以根据业务需求进行处理和存储:

# 处理商品数据示例
def process_product_data(product_data):
    """处理商品数据"""
    if not product_data:
        return None
    
    # 提取关键信息
    product_info = {
        "id": product_data.get("productId"),
        "title": product_data.get("productTitle"),
        "price": product_data.get("salePrice"),
        "original_price": product_data.get("originalPrice"),
        "url": product_data.get("productUrl"),
        "image": product_data.get("imageUrl"),
        "stock": product_data.get("quantity"),
        "category": product_data.get("categoryId"),
        "crawl_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    
    return product_info

# 存储商品数据到CSV
def save_to_csv(products, filename="aliexpress_products.csv"):
    """将商品数据保存到CSV文件"""
    if not products:
        print("没有数据可保存")
        return
    
    headers = products[0].keys()
    
    with open(filename, 'w', newline='', encoding='utf-8-sig') as f:
        writer = csv.DictWriter(f, fieldnames=headers)
        writer.writeheader()
        writer.writerows(products)
    
    print(f"已保存 {len(products)} 条商品数据到 {filename}")

 

五、API 调用示例

下面是如何使用上述代码获取商品详情的完整示例:

# 使用示例
if __name__ == "__main__":
    # 替换为你的实际应用信息
    APP_KEY = "your_app_key"
    APP_SECRET = "your_app_secret"
    ACCESS_TOKEN = "your_access_token"
    
    api_client = AliexpressAPI(APP_KEY, APP_SECRET, ACCESS_TOKEN)
    
    # 获取单个商品详情
    product_id = "1005001234567890"  # 替换为实际商品ID
    product_detail = api_client.get_product_details(product_id)
    
    if product_detail:
        print(f"商品 {product_id} 详情:")
        print(json.dumps(product_detail, indent=2, ensure_ascii=False))
    
    # 批量获取商品详情
    product_ids = ["1005001234567890", "1005000987654321"]  # 替换为实际商品ID列表
    batch_results = api_client.batch_get_products(product_ids)
    
    print(f"批量获取 {len(batch_results)} 个商品详情")

 

六、注意事项与优化建议

  1. API 限流处理

    • 速卖通 API 有请求频率限制,建议在代码中添加请求间隔控制
    • 实现重试机制处理临时失败的请求
  2. 数据缓存策略

    • 对于频繁请求的商品数据,可以实现本地缓存
    • 设置合理的缓存过期时间,平衡数据实时性和性能
  3. 异常处理与监控

    • 完善异常处理机制,记录详细的错误日志
    • 实现监控系统,及时发现并处理 API 调用异常

通过以上步骤,你可以成功接入速卖通 API 并开发出商品详情实时数据采集接口。根据实际业务需求,你还可以进一步扩展功能,如定时采集、数据清洗和分析等。