京东工业(JD Industrial)是京东旗下专注于工业供应链的服务平台,其开放 API 接口主要面向企业客户,提供工业商品采购、库存查询、订单管理、供应商合作等全链路服务。以下从接口体系、认证机制、核心功能展开分析,并提供 Python 调用实现(以商品查询和库存接口为例)。
一、京东工业 API 核心特性分析
1. 接口体系与功能域
2. 认证与签名机制
3. 核心接口参数与响应示例
二、Python 脚本实现
import requests
import hashlib
import time
import json
import logging
from typing import Dict, Optional, List
from requests.exceptions import RequestException
# 配置日志
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
class JDIndustryAPI:
def __init__(self, appkey: str, appsecret: str, access_token: str = ""):
"""
初始化京东工业API客户端
:param appkey: 应用appkey(京东开放平台获取)
:param appsecret: 应用appsecret
:param access_token: 用户授权令牌(部分接口需要)
"""
self.appkey = appkey
self.appsecret = appsecret
self.access_token = access_token
self.base_url = "https://api.jd.com/routerjson"
self.session = requests.Session()
def _generate_sign(self, params: Dict) -> str:
"""生成签名(京东API规则)"""
# 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并MD5加密(小写)
sign_str += self.appsecret
return hashlib.md5(sign_str.encode("utf-8")).hexdigest().lower()
def _get_timestamp(self) -> str:
"""生成时间戳(格式:yyyy-MM-dd HH:mm:ss)"""
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def call_api(self, method: str, biz_params: Dict) -> Optional[Dict]:
"""
通用API调用方法
:param method: 接口方法名(如jd.industry.product.get)
:param biz_params: 业务参数
:return: 接口响应数据(业务部分)
"""
# 1. 公共参数
public_params = {
"app_key": self.appkey,
"method": method,
"timestamp": self._get_timestamp(),
"format": "json",
"v": "1.0",
"sign_method": "md5"
}
# 2. 加入access_token(如需要)
if self.access_token:
public_params["access_token"] = self.access_token
# 3. 合并参数(业务参数需序列化为JSON字符串)
all_params = {**public_params, "param_json": json.dumps(biz_params)}
# 4. 生成签名
sign = self._generate_sign(all_params)
all_params["sign"] = sign
try:
# 5. 发送POST请求(京东工业API推荐POST)
response = self.session.post(
self.base_url,
data=all_params,
timeout=15
)
response.raise_for_status()
result = response.json()
# 6. 处理错误响应(京东API错误码在根节点)
if "error_response" in result:
error = result["error_response"]
logging.error(f"API错误:{error['msg']}(错误码:{error['code']})")
return None
# 7. 提取业务响应(格式:{method}_response)
response_key = method.replace(".", "_") + "_response"
if response_key not in result:
logging.error(f"响应格式错误,缺少{response_key}字段")
return None
return result[response_key]
except RequestException as e:
logging.error(f"请求异常:{str(e)},接口:{method}")
return None
except json.JSONDecodeError:
logging.error(f"响应解析失败:{response.text[:200]}...")
return None
def get_product_detail(self, product_id: str) -> Optional[Dict]:
"""
获取工业商品详情
:param product_id: 商品ID(工业商品唯一标识)
:return: 商品详情字典
"""
method = "jd.industry.product.get"
params = {"product_id": product_id}
result = self.call_api(method, params)
if not result:
return None
# 解析商品详情
return {
"product_id": product_id,
"name": result.get("product_name"),
"brand": result.get("brand_name"),
"specs": result.get("spec_info"), # 规格参数(如"型号:M10;材质:不锈钢")
"price": float(result.get("price", 0)), # 单价(元)
"market_price": float(result.get("market_price", 0)), # 市场价
"description": result.get("product_desc"), # 商品描述
"images": result.get("image_urls", "").split(","), # 图片URL列表
"category": result.get("category_name") # 所属分类
}
def get_product_stock(self, product_id: str, area_id: str = "1_72_28199") -> Optional[Dict]:
"""
查询商品库存(默认区域:北京朝阳区)
:param product_id: 商品ID
:param area_id: 区域ID(格式:省_市_区,如"1_72_28199"代表北京朝阳区)
:return: 库存信息字典
"""
method = "jd.industry.stock.get"
params = {
"product_id": product_id,
"area_id": area_id
}
result = self.call_api(method, params)
if not result:
return None
# 解析库存信息
return {
"product_id": product_id,
"area_id": area_id,
"stock_num": int(result.get("stock_num", 0)), # 库存数量
"available": result.get("is_available", False), # 是否可售
"warehouse": result.get("warehouse_name"), # 发货仓库
"arrival_time": result.get("arrival_time") # 预计到货时间(无货时)
}
# 示例调用
if __name__ == "__main__":
# 替换为实际参数(从京东开放平台获取)
APPKEY = "your_appkey"
APPSECRET = "your_appsecret"
ACCESS_TOKEN = "your_access_token" # 可选,部分接口需要
PRODUCT_ID = "100012345678" # 工业商品ID(从京东工业平台商品详情页获取)
AREA_ID = "1_72_28199" # 北京朝阳区(可根据需求修改)
# 初始化客户端
jd_industry = JDIndustryAPI(
appkey=APPKEY,
appsecret=APPSECRET,
access_token=ACCESS_TOKEN
)
# 1. 获取商品详情
product_detail = jd_industry.get_product_detail(PRODUCT_ID)
if product_detail:
print(f"商品名称:{product_detail['name']}")
print(f"品牌:{product_detail['brand']} | 分类:{product_detail['category']}")
print(f"规格:{product_detail['specs']}")
print(f"价格:{product_detail['price']}元(市场价:{product_detail['market_price']}元)")
print(f"主图:{product_detail['images'][0] if product_detail['images'] else '无'}")
# 2. 查询库存
stock_info = jd_industry.get_product_stock(PRODUCT_ID, AREA_ID)
if stock_info:
print(f"\n库存信息(区域:{AREA_ID}):")
print(f"库存数量:{stock_info['stock_num']}件 | 可售状态:{'是' if stock_info['available'] else '否'}")
print(f"发货仓库:{stock_info['warehouse']}")
if stock_info["arrival_time"]:
print(f"预计到货:{stock_info['arrival_time']}")