速卖通(AliExpress)开放平台的item_get接口是获取商品详情的核心工具,适用于跨境电商分析、多平台比价、选品系统等场景。本文将全面讲解该接口的对接流程、认证机制、代码实现及最佳实践,帮助开发者系统掌握从入门到精通的全流程。
一、接口基础认知
二、对接前置准备
三、接口调用流程
四、代码实现示例(Python)
import requests
import hashlib
import time
import json
class AliexpressItemApi:
def __init__(self, app_key, app_secret, access_token=None):
self.app_key = app_key
self.app_secret = app_secret
self.access_token = access_token
self.url = "https://gw.api.alibaba.com/openapi/param2/2/portals.open/api.item.get"
self.token_expire_time = 0 # 令牌过期时间(时间戳,秒)
def generate_sign(self, params):
"""生成签名"""
# 1. 按参数名ASCII升序排序
sorted_params = sorted(params.items(), key=lambda x: x[0])
# 2. 拼接为key=value&key=value格式
sign_str = "&".join([f"{k}={v}" for k, v in sorted_params])
# 3. 追加app_secret
sign_str += f"&app_secret={self.app_secret}"
# 4. MD5加密(32位大写)
sign = hashlib.md5(sign_str.encode()).hexdigest().upper()
return sign
def refresh_access_token(self):
"""刷新access_token(需根据实际授权方式实现)"""
# 实际应用中需根据速卖通授权流程实现令牌刷新
# 此处为示例,实际需替换为真实刷新逻辑
token_url = "https://gw.api.alibaba.com/openapi/http/1/system.oauth2/getToken"
params = {
"grant_type": "refresh_token",
"client_id": self.app_key,
"client_secret": self.app_secret,
"refresh_token": "your_refresh_token"
}
response = requests.post(token_url, data=params)
result = response.json()
if "error" in result:
raise Exception(f"令牌刷新失败: {result['error_description']}")
self.access_token = result["access_token"]
self.token_expire_time = time.time() + int(result["expires_in"])
return self.access_token
def item_get(self, product_id, fields="productId,title,price,stock,imageUrl"):
"""
获取商品详情
:param product_id: 商品ID
:param fields: 需要返回的字段,多个用逗号分隔
:return: 商品详情数据
"""
# 检查并刷新令牌
if not self.access_token or time.time() > self.token_expire_time - 60:
self.refresh_access_token()
# 1. 组装参数
params = {
"app_key": self.app_key,
"access_token": self.access_token,
"timestamp": int(time.time() * 1000), # 毫秒级时间戳
"format": "json",
"v": "1.0",
"productId": product_id,
"fields": fields
}
# 2. 生成签名
params["sign"] = self.generate_sign(params)
try:
# 3. 发送POST请求
response = requests.post(
url=self.url,
json=params,
headers={"Content-Type": "application/json"},
timeout=15
)
response.raise_for_status()
result = response.json()
# 4. 处理响应
if "error_response" in result:
error = result["error_response"]
return {
"success": False,
"error_code": error.get("code"),
"error_msg": error.get("msg")
}
return {
"success": True,
"data": result.get("item_get_response", {}).get("item", {})
}
except Exception as e:
return {
"success": False,
"error_msg": f"请求异常: {str(e)}"
}
# 使用示例
if __name__ == "__main__":
# 替换为实际参数
APP_KEY = "your_app_key"
APP_SECRET = "your_app_secret"
ACCESS_TOKEN = "your_access_token"
# 初始化API客户端
api = AliexpressItemApi(APP_KEY, APP_SECRET, ACCESS_TOKEN)
# 调用接口,获取商品详情
result = api.item_get(
product_id="1234567890",
fields="productId,title,price,originalPrice,stock,imageUrl,saleCount,storeName"
)
if result["success"]:
item = result["data"]
print(f"商品ID: {item.get('productId')}")
print(f"商品标题: {item.get('title')}")
print(f"售价: {item.get('price')} {item.get('currency')}")
print(f"原价: {item.get('originalPrice')} {item.get('currency')}")
print(f"库存: {item.get('stock')}")
print(f"30天销量: {item.get('saleCount')}")
print(f"店铺名称: {item.get('storeName')}")
print(f"主图地址: {item.get('imageUrl')}")
else:
print(f"获取失败: {result['error_msg']} (错误码: {result.get('error_code')})")