1688 开放平台的item_get接口是获取商品详情的核心工具,广泛应用于批发采购系统、供应链管理、电商数据分析等场景。本文将全面讲解该接口的对接流程、使用技巧和最佳实践,帮助开发者快速掌握从入门到精通的全过程。
一、接口基础认知
二、对接前置准备
三、接口调用流程
四、代码实现示例(Python)
import requests
import hashlib
import time
import json
class AlibabaItemApi:
def __init__(self, app_key, app_secret):
self.app_key = app_key
self.app_secret = app_secret
self.token_url = "https://gw.open.1688.com/openapi/http/1/system.oauth2/getToken"
self.item_url = "https://gw.open.1688.com/openapi/param2/2/portals.open/api.item.get"
self.access_token = None
self.token_expire_time = 0
def generate_sign(self, params):
"""生成签名"""
# 按参数名ASCII排序
sorted_params = sorted(params.items(), key=lambda x: x[0])
# 拼接参数
sign_str = ""
for key, value in sorted_params:
sign_str += f"{key}{value}"
# 拼接app_secret后进行MD5加密
sign_str += self.app_secret
sign = hashlib.md5(sign_str.encode()).hexdigest().upper()
return sign
def get_access_token(self):
"""获取access_token"""
# 检查token是否有效
if self.access_token and time.time() < self.token_expire_time - 60:
return self.access_token
params = {
"grant_type": "client_credentials",
"client_id": self.app_key,
"client_secret": self.app_secret
}
try:
response = requests.post(self.token_url, data=params, timeout=10)
result = json.loads(response.text)
if "error" in result:
raise Exception(f"获取token失败: {result['error_description']}")
self.access_token = result["access_token"]
self.token_expire_time = time.time() + int(result["expires_in"])
return self.access_token
except Exception as e:
raise Exception(f"获取access_token异常: {str(e)}")
def item_get(self, offer_id, fields="offerId,title,price,rprice,minAmount,detailUrl,picUrl,shopName"):
"""
获取商品详情
:param offer_id: 商品ID
:param fields: 需要返回的字段,多个字段用逗号分隔
:return: 商品详情数据
"""
# 获取access_token
token = self.get_access_token()
# 组装参数
params = {
"app_key": self.app_key,
"access_token": token,
"method": "portals.open.api.item.get",
"format": "json",
"v": "1.0",
"timestamp": str(int(time.time() * 1000)),
"offerId": offer_id,
"fields": fields
}
# 生成签名
params["sign"] = self.generate_sign(params)
try:
# 发送POST请求
response = requests.post(
self.item_url,
data=params,
headers={"Content-Type": "application/x-www-form-urlencoded"},
timeout=15
)
result = json.loads(response.text)
# 处理错误响应
if "error_response" in result:
error = result["error_response"]
return {
"success": False,
"error_code": error.get("code"),
"error_msg": error.get("msg")
}
# 提取商品数据
if "item_get_response" in result:
item_data = result["item_get_response"].get("item", {})
return {
"success": True,
"data": item_data
}
return {"success": False, "error_msg": "未知响应格式"}
except Exception as e:
return {"success": False, "error_msg": f"请求异常: {str(e)}"}
# 使用示例
if __name__ == "__main__":
# 替换为自己的app_key和app_secret
APP_KEY = "your_app_key"
APP_SECRET = "your_app_secret"
# 初始化API客户端
api = AlibabaItemApi(APP_KEY, APP_SECRET)
# 调用接口,获取商品ID为6123456789的详情
result = api.item_get(
offer_id="6123456789",
fields="offerId,title,price,rprice,minAmount,maxAmount,amount,onSaleTime,shopName,shopId,picUrl,detailUrl"
)
if result["success"]:
item = result["data"]
print(f"商品ID: {item.get('offerId')}")
print(f"商品标题: {item.get('title')}")
print(f"价格: {item.get('price')} 元")
print(f"建议零售价: {item.get('rprice')} 元")
print(f"起订量: {item.get('minAmount')} 件")
print(f"可售数量: {item.get('amount')} 件")
print(f"上架时间: {item.get('onSaleTime')}")
print(f"店铺名称: {item.get('shopName')}")
print(f"商品主图: {item.get('picUrl')}")
print(f"详情链接: {item.get('detailUrl')}")
else:
print(f"获取失败: {result['error_msg']} (错误码: {result.get('error_code')})")