中国供应网作为国内头部 B2B 工业电商平台,其 item_get 接口是获取商品全维度详情的核心入口,专注服务工业用品、电子元件、机械设备、化工原料等 B2B 采购场景。该接口支持通过商品 ID 或详情页 URL,精准提取商品规格参数、阶梯价格、库存状态、供应商资质、交货条款等关键数据,广泛应用于采购比价、供应链管理、产品选型、供应商评估等核心业务,是工业场景下对接平台数据的必备工具。
一、接口核心认知:先明确 “能做什么”“适配什么场景”
1. 接口定位与核心价值
2. 核心参数与返回字段(工业场景适配版)
(1)请求参数(必填 + 可选,按优先级排序)
(2)返回核心字段(按业务场景分类,工业场景重点标注)
3. 接口限制与注意事项
二、对接前准备:3 步搞定前置条件
1. 注册与获取密钥(核心步骤)
2. 技术环境准备
(1)支持语言与协议
(2)必备工具与依赖
3. 业务需求梳理
三、实操步骤:从调试到落地(Python 示例)
步骤 1:理解请求流程
步骤 2:签名生成规则(关键!避免调用失败)
签名示例(参数排序与拼接)
步骤 3:完整代码实现(Python)
(1)依赖安装
(2)完整代码(含签名生成、接口调用、数据标准化)
import requests
import hashlib
import time
import json
from urllib.parse import urlencode
from typing import Dict, Optional, List
# 接口核心配置(替换为自己的密钥和接口地址)
APP_KEY = "你的appkey"
SECRET = "你的secret"
API_URL = "https://api.chinasilkroad.com/item_get" # 正式接口地址
TEST_PRODUCT_ID = "prod_1008611" # 测试用商品ID(可从平台详情页提取)
def generate_sign(params: Dict) -> str:
"""生成接口签名(严格按平台规则实现,核心函数)"""
# 1. 按参数名ASCII升序排序(排除sign字段)
sorted_params = sorted(params.items(), key=lambda x: x[0])
# 2. 拼接参数字符串(urlencode自动处理中文、空格等特殊字符)
param_str = urlencode(sorted_params, encoding="utf-8") + f"&secret={SECRET}"
# 3. MD5加密(32位大写)
md5 = hashlib.md5()
md5.update(param_str.encode("utf-8"))
return md5.hexdigest().upper()
def parse_industrial_specs(specs: List[Dict]) -> Dict:
"""解析工业商品规格参数(标准化字段命名,适配工业场景)"""
# 工业场景核心参数映射表(可根据业务扩展)
standard_specs = {
"model": "", # 型号
"brand": "", # 品牌
"material": "", # 材质
"dimension": "", # 尺寸
"rating": "", # 额定值(电压/功率/压力等)
"tolerance": "", # 精度
"protection_level": "", # 防护等级(IP67等)
"executive_standard": "", # 执行标准(GB/T等)
"operating_temperature": "", # 工作温度
"certification": "" # 认证资质(RoHS/ISO等)
}
for spec in specs:
key = spec.get("key", "").lower() # 参数名转小写,统一匹配
value = spec.get("value", "").strip()
# 按关键词匹配,标准化字段(覆盖不同供应商的参数命名差异)
if any(k in key for k in ["型号", "model"]):
standard_specs["model"] = value
elif any(k in key for k in ["品牌", "brand"]):
standard_specs["brand"] = value
elif any(k in key for k in ["材质", "material"]):
standard_specs["material"] = value
elif any(k in key for k in ["尺寸", "size", "dimension"]):
standard_specs["dimension"] = value
elif any(k in key for k in ["额定", "rating"]):
standard_specs["rating"] = value
elif any(k in key for k in ["精度", "tolerance", "accuracy"]):
standard_specs["tolerance"] = value
elif any(k in key for k in ["防护", "ip"]):
standard_specs["protection_level"] = value
elif any(k in key for k in ["标准", "standard", "gb", "iso"]):
standard_specs["executive_standard"] += value + "|" if value else ""
elif any(k in key for k in ["温度", "temperature", "工作环境"]):
standard_specs["operating_temperature"] = value
elif any(k in key for k in ["认证", "certificate", "rohs", "iatf"]):
standard_specs["certification"] += value + "|" if value else ""
# 清理多余分隔符
standard_specs["executive_standard"] = standard_specs["executive_standard"].rstrip("|")
standard_specs["certification"] = standard_specs["certification"].rstrip("|")
return standard_specs
def get_product_detail(
product_id: Optional[str] = None,
product_url: Optional[str] = None,
is_custom: int = 0,
refresh: int = 0
) -> Dict:
"""
调用item_get接口获取商品详情(核心接口调用函数)
:param product_id: 商品ID(优先级高于URL)
:param product_url: 商品详情页URL
:param is_custom: 是否查询定制化参数(1=是,0=否)
:param refresh: 是否强制刷新缓存(1=是,0=否,企业版可用)
:return: 标准化后的商品详情字典(含成功状态标识)
"""
# 1. 校验必填参数
if not (product_id or product_url):
return {"success": False, "error_msg": "必须传入product_id或product_url", "error_code": -1}
# 2. 构建基础参数(必填项)
params = {
"appkey": APP_KEY,
"timestamp": int(time.time() * 1000), # 毫秒级时间戳
"is_custom": is_custom,
"refresh": refresh,
# 按需筛选字段,减少数据传输量(工业场景核心字段)
"fields": "base_info,specs,price,stock,seller,trade_terms,technical_doc"
}
# 3. 添加查询标识(二选一)
if product_id:
params["product_id"] = product_id
else:
params["product_url"] = product_url
# 4. 生成签名(必须在所有参数拼接完成后)
params["sign"] = generate_sign(params)
try:
# 5. 发送POST请求(HTTPS协议,设置JSON请求头,超时10秒)
response = requests.post(
url=API_URL,
data=json.dumps(params),
headers={"Content-Type": "application/json"},
timeout=10,
verify=True # 生产环境开启SSL验证,防止数据泄露
)
# 6. 解析响应(JSON格式)
result = response.json()
# 7. 处理响应状态
if result.get("code") == 200:
raw_data = result.get("data", {})
# 标准化返回数据结构(统一字段命名,便于后续处理)
standard_data = {
"success": True,
"product_id": raw_data.get("base_info", {}).get("product_id", product_id),
"base_info": {
"name": raw_data.get("base_info", {}).get("name", ""),
"subtitle": raw_data.get("base_info", {}).get("subtitle", ""),
"main_image": raw_data.get("base_info", {}).get("main_image", ""),
"category": raw_data.get("base_info", {}).get("category", ""),
"tags": raw_data.get("base_info", {}).get("tags", []), # 现货/定制/原厂直供
"url": raw_data.get("base_info", {}).get("url", product_url)
},
"specs": parse_industrial_specs(raw_data.get("specs", [])), # 标准化规格参数
"price_info": {
"base_price": raw_data.get("price", {}).get("base_price", 0.0),
"tax_inclusive": raw_data.get("price", {}).get("tax_inclusive", True), # 是否含税
"ladder_prices": raw_data.get("price", {}).get("ladder_prices", []), # 批量阶梯价
"currency": raw_data.get("price", {}).get("currency", "CNY")
},
"stock_info": {
"stock_quantity": raw_data.get("stock", {}).get("quantity", 0),
"stock_status": raw_data.get("stock", {}).get("status", "现货"),
"min_order": raw_data.get("stock", {}).get("min_order", 1), # 最小起订量
"max_supply": raw_data.get("stock", {}).get("max_supply", 99999),
"lead_time": raw_data.get("stock", {}).get("lead_time", "") # 备货周期
},
"seller_info": {
"seller_id": raw_data.get("seller", {}).get("seller_id", ""),
"company_name": raw_data.get("seller", {}).get("company_name", ""),
"qualification": raw_data.get("seller", {}).get("qualification", []), # 资质认证
"location": raw_data.get("seller", {}).get("location", ""),
"contact_phone": raw_data.get("seller", {}).get("contact_phone", ""),
"contact_email": raw_data.get("seller", {}).get("contact_email", ""),
"cooperation_years": raw_data.get("seller", {}).get("cooperation_years", 0) # 合作年限
},
"trade_terms": {
"delivery_cycle": raw_data.get("trade_terms", {}).get("delivery_cycle", ""), # 交货周期
"warranty_period": raw_data.get("trade_terms", {}).get("warranty_period", ""), # 质保期
"payment_method": raw_data.get("trade_terms", {}).get("payment_method", []) # 付款方式
},
"technical_doc": {
"has_spec": raw_data.get("technical_doc", {}).get("has_spec", False),
"spec_url": raw_data.get("technical_doc", {}).get("spec_url", ""), # 规格书下载URL
"detection_report": raw_data.get("technical_doc", {}).get("detection_report", "")
},
"update_time": time.strftime("%Y-%m-%d %H:%M:%S") # 数据更新时间
}
return standard_data
else:
# 接口返回错误(如签名错误、权限不足)
return {
"success": False,
"error_code": result.get("code"),
"error_msg": result.get("msg", "接口调用失败")
}
except requests.exceptions.RequestException as e:
# 网络异常(超时、连接失败、SSL错误等)
return {
"success": False,
"error_code": -2,
"error_msg": f"网络异常:{str(e)}"
}
except Exception as e:
# 其他异常(JSON解析失败、参数处理异常等)
return {
"success": False,
"error_code": -3,
"error_msg": f"处理异常:{str(e)}"
}
# 调用示例(工业商品详情查询,适配采购场景)
if __name__ == "__main__":
# 按商品ID查询(推荐,精准高效)
product_detail = get_product_detail(
product_id=TEST_PRODUCT_ID,
is_custom=1, # 查询定制参数(若为定制商品)
refresh=0 # 非实时需求无需强制刷新
)
# 打印结果(实际场景可存储到数据库/Excel,或对接前端系统)
if product_detail["success"]:
print("=" * 80)
print(f"【商品基础信息】")
print(f"商品名称:{product_detail['base_info']['name']}")
print(f"商品标签:{','.join(product_detail['base_info']['tags'])}")
print(f"所属类目:{product_detail['base_info']['category']}")
print(f"详情页URL:{product_detail['base_info']['url']}")
print("-" * 80)
print(f"【核心规格参数】")
for key, value in product_detail["specs"].items():
if value:
print(f" {key}:{value}")
print("-" * 80)
print(f"【价格信息】")
print(f"基础单价:¥{product_detail['price_info']['base_price']}({'含税' if product_detail['price_info']['tax_inclusive'] else '不含税'})")
print(f"批量阶梯价:")
for ladder in product_detail["price_info"]["ladder_prices"]:
print(f" {ladder['min_qty']}-{ladder['max_qty']}个:¥{ladder['price']}/个")
print("-" * 80)
print(f"【库存与交易条款】")
print(f"库存状态:{product_detail['stock_info']['stock_status']} | 库存数量:{product_detail['stock_info']['stock_quantity']}个")
print(f"最小起订量:{product_detail['stock_info']['min_order']}个 | 最大供应量:{product_detail['stock_info']['max_supply']}个")
print(f"交货周期:{product_detail['trade_terms']['delivery_cycle']} | 质保期:{product_detail['trade_terms']['warranty_period']}")
print(f"付款方式:{','.join(product_detail['trade_terms']['payment_method'])}")
print("-" * 80)
print(f"【供应商信息】")
print(f"企业名称:{product_detail['seller_info']['company_name']}")
print(f"资质认证:{','.join(product_detail['seller_info']['qualification'])}")
print(f"所在地:{product_detail['seller_info']['location']} | 合作年限:{product_detail['seller_info']['cooperation_years']}年")
print(f"联系电话:{product_detail['seller_info']['contact_phone']} | 联系邮箱:{product_detail['seller_info']['contact_email']}")
print("-" * 80)
print(f"【技术文档】")
if product_detail["technical_doc"]["has_spec"]:
print(f"规格书下载:{product_detail['technical_doc']['spec_url']}")
if product_detail["technical_doc"]["detection_report"]:
print(f"检测报告:{product_detail['technical_doc']['detection_report']}")
else:
print("未提供公开技术文档,可联系供应商获取")
print("=" * 80)
else:
print(f"查询失败:{product_detail['error_msg']}(错误码:{product_detail['error_code']})")