阿里巴巴作为全球最大的 B2B 电商平台,其开放平台的item_get接口是获取商品详情的核心工具,广泛应用于供应商筛选、价格监控、竞品分析、采购系统集成等场景。本文将系统讲解该接口的对接流程、认证机制、代码实现及最佳实践,帮助开发者从入门到精通,构建高效稳定的商品详情获取系统。
一、接口基础认知
二、对接前置准备
三、接口调用流程
四、代码实现示例(Python)
import requests
import time
import hashlib
import json
from urllib.parse import urlencode
class AlibabaItemApi:
def __init__(self, app_key, app_secret):
self.app_key = app_key
self.app_secret = app_secret
self.base_url = "https://gw.api.1688.com/openapi/param2/1/com.alibaba.product/alibaba.product.get/"
self.format = "json"
self.version = "1.0"
def generate_sign(self, params):
"""生成签名(MD5算法)"""
# 1. 按参数名ASCII升序排序
sorted_params = sorted(params.items(), key=lambda x: x[0])
# 2. 拼接为key=value形式
sign_str = urlencode(sorted_params)
# 3. 拼接app_secret
sign_str += f"&app_secret={self.app_secret}"
# 4. MD5加密并转为大写
sign = hashlib.md5(sign_str.encode()).hexdigest().upper()
return sign
def item_get(self, product_id, fields=None):
"""
获取商品详情
:param product_id: 商品ID(num_iid)
:param fields: 需要返回的字段列表,如"productId,title,price"
:return: 商品详情数据
"""
# 1. 组装公共参数
public_params = {
"app_key": self.app_key,
"method": "com.alibaba.product.alibaba.product.get",
"timestamp": int(time.time() * 1000), # 毫秒级时间戳
"format": self.format,
"v": self.version
}
# 2. 组装业务参数
param = {"productId": product_id}
if fields:
param["fields"] = fields
# 3. 合并参数并生成签名
all_params = public_params.copy()
all_params["param"] = json.dumps(param) # 业务参数需JSON序列化
sign = self.generate_sign(all_params)
all_params["sign"] = sign
try:
# 4. 发送POST请求
response = requests.post(
url=self.base_url,
data=all_params,
timeout=15
)
response.raise_for_status()
result = response.json()
# 5. 处理响应
if "error_response" in result:
error = result["error_response"]
return {
"success": False,
"error_code": error["code"],
"error_msg": error["msg"]
}
# 6. 提取商品数据
product_data = result.get("alibaba_product_get_response", {}).get("result", {})
return {
"success": True,
"data": product_data
}
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"
PRODUCT_ID = "622250555555" # 示例商品ID
# 初始化API客户端
api = AlibabaItemApi(APP_KEY, APP_SECRET)
# 调用接口,指定需要返回的字段(可选)
result = api.item_get(
product_id=PRODUCT_ID,
fields="productId,title,price,minOrderQuantity,packingList,"
"sellerInfo,tradeInfo,saleInfo,imageList"
)
if result["success"]:
item = result["data"]
print(f"商品ID: {item.get('productId')}")
print(f"标题: {item.get('title')}")
print(f"单价: {item.get('price', {}).get('price')} {item.get('price', {}).get('currency')}")
print(f"起订量: {item.get('minOrderQuantity', {}).get('value')} {item.get('minOrderQuantity', {}).get('unit')}")
print(f"30天成交量: {item.get('saleInfo', {}).get('tradeCount')}")
print(f"供应商: {item.get('sellerInfo', {}).get('companyName')}")
print(f"诚信通年限: {item.get('sellerInfo', {}).get('memberLevel')}年")
print(f"主图: {item.get('imageList', [{}])[0].get('url')}")
print(f"商品链接: {item.get('detailUrl')}")
else:
print(f"获取失败: {result.get('error_msg')} (错误码: {result.get('error_code')})")