微店开放平台的item_get接口是获取商品详情的核心工具,适用于个人店铺、电商平台、供应链系统等场景,可获取商品基本信息、价格、库存、规格等关键数据。本文将全面讲解该接口的对接流程、使用技巧和最佳实践,帮助开发者快速掌握从入门到精通的全流程掌握。
一、接口基础认知
二、对接前置准备
三、接口调用流程
import requests
import hashlib
import time
import json
class WeidianItemApi:
def __init__(self, appkey, appsecret):
self.appkey = appkey
self.appsecret = appsecret
self.url = "https://api.weidian.com/item/get" # 正式环境
# 沙箱环境:https://sandbox.api.weidian.com/item/get
def generate_signature(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. 追加appsecret
sign_str += f"&appsecret={self.appsecret}"
# 4. MD5加密(32位小写)
signature = hashlib.md5(sign_str.encode()).hexdigest()
return signature
def item_get(self, item_id, fields=None):
"""
获取商品详情
:param item_id: 商品ID
:param fields: 需要返回的字段,多个用逗号分隔,如"item_id,title,price"
:return: 商品详情数据
"""
# 1. 组装基础参数
params = {
"appkey": self.appkey,
"timestamp": int(time.time()), # 秒级时间戳
"item_id": item_id
}
# 2. 可选字段
if fields:
params["fields"] = fields
# 3. 生成签名
params["signature"] = self.generate_signature(params)
try:
# 4. 发送POST请求
response = requests.post(
url=self.url,
json=params,
headers={"Content-Type": "application/json"},
timeout=10
)
response.raise_for_status() # 触发HTTP错误(如404、500)
result = response.json()
# 5. 处理响应
if result.get("errcode") == 0:
# 成功响应
return {
"success": True,
"data": result.get("item", {})
}
else:
# 错误响应
return {
"success": False,
"error_code": result.get("errcode"),
"error_msg": result.get("errmsg")
}
except Exception as e:
return {
"success": False,
"error_msg": f"请求异常: {str(e)}"
}
# 使用示例
if __name__ == "__main__":
# 替换为自己的appkey和appsecret
APPKEY = "your_appkey"
APPSECRET = "your_appsecret"
# 初始化API客户端
api = WeidianItemApi(APPKEY, APPSECRET)
# 调用接口,获取商品ID为12345678的详情
# 指定返回字段:商品ID、标题、售价、库存、主图
result = api.item_get(
item_id="12345678",
fields="item_id,title,price,stock,main_img"
)
if result["success"]:
item = result["data"]
print(f"商品ID: {item.get('item_id')}")
print(f"商品标题: {item.get('title')}")
print(f"售价: {item.get('price')} 元")
print(f"库存: {item.get('stock')} 件")
print(f"主图地址: {item.get('main_img')}")
else:
print(f"获取失败: {result['error_msg']} (错误码: {result.get('error_code')})")