爱回收(Aihuishou)是国内领先的电子产品回收与以旧换新平台,其 API 接口主要服务于企业客户(如手机厂商、电商平台、线下门店),提供设备回收估价、订单创建、物流跟踪、款项结算等全链路功能,支撑 "以旧换新""批量回收" 等业务场景。由于爱回收未开放公共 API,需通过企业合作通道申请权限(个人开发者无法直接调用),以下从接口体系、认证机制、核心功能展开深度分析,并基于企业合作文档提供 Python 实现方案。 一、爱回收 API 核心特性分析
- 接口体系与业务场景 爱回收 API 围绕 "回收业务全流程" 设计,核心功能域覆盖从 "估价" 到 "结算" 的闭环,具体如下:
功能域 | 核心接口 | 业务场景 | 关键参数 |
---|---|---|---|
设备估价 | /api/valuation/get (设备回收估价) |
输入设备型号、成色、功能状态,获取回收价格 | device_model (型号)、condition (成色)、functional_status (功能) |
订单管理 | /api/order/create (创建回收订单) /api/order/getDetail (订单详情) |
生成回收订单、查询订单状态(待邮寄 / 检测中 / 已完成) | valuation_id (估价 ID)、order_no (订单号)、user_info (用户信息) |
物流跟踪 | /api/logistics/getTrace (物流轨迹查询) |
跟踪用户邮寄设备的物流状态 | logistics_no (物流单号)、logistics_company (快递公司) |
检测与结算 | /api/order/getInspectionResult (检测结果查询) /api/settlement/get (结算查询) |
获取设备检测报告、确认最终回收价及结算金额 | order_no (订单号)、settlement_no (结算单号) |
以旧换新 | /api/tradeIn/create (以旧换新订单) |
关联 "回收订单" 与 "新机购买订单",实现补贴抵扣 | recycle_order_no (回收订单号)、new_machine_order_no (新机订单号) |
-
认证机制 爱回收 API 采用企业级认证,安全性要求高,核心流程如下:
-
合作申请 :企业需提供营业执照、业务合作方案,通过爱回收商务审核后获取
app_id
和app_secret
; -
签名生成 :每次请求需按规则生成签名(
sign
),防止参数篡改,规则如下:- 所有请求参数(含公共参数和业务参数)按参数名 ASCII 升序排序;
- 拼接为
key=value&key=value
格式,末尾拼接app_secret
; - 通过 SHA256 加密生成签名(区分大小写);
-
请求头认证 :签名和
app_id
需放在请求头(如X-AppId: {app_id}
、X-Sign: {sign}
),部分接口需额外携带timestamp
(时间戳,误差≤5 分钟)。 -
数据格式与接口限制
- 数据格式 :请求 / 响应均为 JSON,编码为 UTF-8,日期格式统一为
yyyy-MM-dd HH:mm:ss
; - 调用限制 :企业客户默认 QPS 为 5(每秒 5 次),超过返回
429 Too Many Requests
,需申请提升需提供业务量证明; - 数据权限:仅能访问本企业合作范围内的订单数据(如某手机厂商仅能查询其品牌设备的回收订单);
- 环境区分 :提供测试环境(
test-api.aihuishou.com
)和生产环境(api.aihuishou.com
),测试环境数据为模拟数据,不产生真实业务。
二、核心接口参数与响应示例
以设备估价 和订单创建两个高频接口为例,详细说明参数与响应格式:
- 设备估价接口(
/api/valuation/get
)
请求参数(JSON)
json
{
"device_model": "iPhone 15 Pro", // 设备型号(需与爱回收型号库一致,如"小米14")
"brand": "Apple", // 品牌
"condition": "good", // 成色:good(良好)、normal(一般)、poor(较差)
"functional_status": "normal", // 功能状态:normal(正常)、abnormal(异常,如屏幕损坏)
"storage": "256GB", // 存储容量
"color": "black", // 颜色
"is_original": true, // 是否原装(无拆修)
"timestamp": "2024-08-28 15:30:00" // 时间戳
}
响应示例(JSON)
json
json
{
"code": 0, // 0=成功,非0=错误
"msg": "success",
"data": {
"valuation_id": "VAL20240828001", // 估价ID(创建订单需携带)
"recycle_price": 6800.00, // 回收价格(元)
"deposit_price": 50.00, // 预付款(用户邮寄设备后到账)
"valid_time": "2024-08-30 15:30:00", // 估价有效期(2天内有效)
"remark": "屏幕无划痕、无拆修可维持此价格",
"device_info": { // 设备基础信息
"model": "iPhone 15 Pro",
"brand": "Apple",
"storage": "256GB"
}
}
}
2. 订单创建接口(/api/order/create
)
请求参数(JSON)
json
json
{
"valuation_id": "VAL20240828001", // 估价ID(来自估价接口)
"user_name": "张三", // 用户姓名
"user_phone": "138****6789", // 用户手机号(需脱敏传输,部分场景可加密)
"user_address": "北京市朝阳区XX街道",// 用户邮寄地址
"logistics_type": "express", // 物流类型:express(快递)、store(门店自送)
"timestamp": "2024-08-28 15:35:00"
}
响应示例(JSON)
json
json
{
"code": 0,
"msg": "success",
"data": {
"order_no": "ORD20240828001", // 回收订单号(唯一标识)
"express_no": "YT1234567890123", // 爱回收收货快递单号(用户邮寄时使用)
"express_company": "圆通快递", // 合作快递公司
"store_info": null, // 门店信息(物流类型为store时非空)
"create_time": "2024-08-28 15:35:00",
"status": "pending_send" // 订单状态:pending_send(待邮寄)
}
}
三、Python 脚本实现
以下基于爱回收企业 API 规范,实现设备估价、订单创建、订单详情查询 三个核心功能,需替换企业合作获取的 app_id
和 app_secret
。
- 完整代码实现
python
运行
python
import requests
import hashlib
import time
import json
import logging
from typing import Dict, Optional
from requests.exceptions import RequestException
# 配置日志(记录请求状态、错误信息)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
class AihuishouAPI:
def __init__(self, app_id: str, app_secret: str, env: str = "test"):
"""
初始化爱回收API客户端
:param app_id: 企业合作获取的app_id
:param app_secret: 企业合作获取的app_secret
:param env: 环境:test(测试环境)、prod(生产环境)
"""
self.app_id = app_id
self.app_secret = app_secret
# 环境域名(测试/生产)
self.base_url = "https://test-api.aihuishou.com" if env == "test" else "https://api.aihuishou.com"
self.session = requests.Session()
# 公共请求头
self.session.headers.update({
"X-AppId": self.app_id,
"Content-Type": "application/json;charset=UTF-8"
})
def _generate_sign(self, params: Dict) -> str:
"""
生成签名(爱回收API规则)
:param params: 请求参数(含业务参数和timestamp)
:return: SHA256签名(大写)
"""
# 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. 末尾拼接app_secret,SHA256加密后转大写
sign_str += self.app_secret
return hashlib.sha256(sign_str.encode("utf-8")).hexdigest().upper()
def _get_timestamp(self) -> str:
"""生成时间戳(格式:yyyy-MM-dd HH:mm:ss)"""
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def _send_request(self, path: str, params: Dict) -> Optional[Dict]:
"""
发送API请求(POST)
:param path: 接口路径(如/api/valuation/get)
:param params: 业务参数
:return: 接口响应数据(data字段)或None
"""
# 1. 拼接完整URL
url = f"{self.base_url}{path}"
# 2. 添加时间戳(公共参数)
request_params = {**params, "timestamp": self._get_timestamp()}
# 3. 生成签名并添加到请求头
sign = self._generate_sign(request_params)
self.session.headers["X-Sign"] = sign
try:
# 4. 发送POST请求(爱回收API均为POST)
response = self.session.post(
url,
data=json.dumps(request_params, ensure_ascii=False),
timeout=15
)
response.raise_for_status() # 抛出HTTP错误(如401、429)
result = response.json()
# 5. 处理错误响应(code≠0为错误)
if result.get("code") != 0:
error_msg = result.get("msg", "未知错误")
logging.error(f"API错误:{error_msg}(错误码:{result.get('code')},接口:{path})")
return None
logging.info(f"接口请求成功:{path}")
return result.get("data", {})
except RequestException as e:
logging.error(f"请求异常:{str(e)},接口:{path}")
return None
except json.JSONDecodeError:
logging.error(f"响应解析失败:{response.text[:200]}...,接口:{path}")
return None
def get_device_valuation(self, device_params: Dict) -> Optional[Dict]:
"""
设备回收估价
:param device_params: 设备参数(model、brand、condition等)
:return: 估价结果(含valuation_id、回收价格)
"""
path = "/api/valuation/get"
# 校验必填参数
required_fields = ["device_model", "brand", "condition", "functional_status", "storage"]
for field in required_fields:
if field not in device_params or not device_params[field]:
logging.error(f"设备估价缺少必填参数:{field}")
return None
return self._send_request(path, device_params)
def create_recycle_order(self, order_params: Dict) -> Optional[Dict]:
"""
创建回收订单
:param order_params: 订单参数(valuation_id、user_info等)
:return: 订单信息(含order_no、快递单号)
"""
path = "/api/order/create"
# 校验必填参数
required_fields = ["valuation_id", "user_name", "user_phone", "user_address", "logistics_type"]
for field in required_fields:
if field not in order_params or not order_params[field]:
logging.error(f"创建订单缺少必填参数:{field}")
return None
return self._send_request(path, order_params)
def get_order_detail(self, order_no: str) -> Optional[Dict]:
"""
查询订单详情
:param order_no: 回收订单号
:return: 订单详情(状态、检测结果、物流信息)
"""
path = "/api/order/getDetail"
return self._send_request(path, {"order_no": order_no})
# 示例调用(需替换为企业真实参数)
if __name__ == "__main__":
# 1. 企业合作参数(从爱回收商务对接获取)
AIHUISHOU_APP_ID = "your_enterprise_app_id"
AIHUISHOU_APP_SECRET = "your_enterprise_app_secret"
# 2. 初始化API客户端(测试环境)
aihuishou_api = AihuishouAPI(
app_id=AIHUISHOU_APP_ID,
app_secret=AIHUISHOU_APP_SECRET,
env="test" # 生产环境改为"prod"
)
# ------------------------------
# 步骤1:设备估价(以iPhone 15 Pro为例)
# ------------------------------
device_params = {
"device_model": "iPhone 15 Pro",
"brand": "Apple",
"condition": "good", # 成色:good/normal/poor
"functional_status": "normal", # 功能:normal/abnormal
"storage": "256GB",
"color": "black",
"is_original": True # 是否原装
}
valuation_result = aihuishou_api.get_device_valuation(device_params)
if not valuation_result:
logging.error("设备估价失败,终止流程")
exit(1)
# 提取估价ID(创建订单需用)
valuation_id = valuation_result["valuation_id"]
print(f"=== 设备估价结果 ===")
print(f"估价ID:{valuation_id}")
print(f"回收价格:{valuation_result['recycle_price']} 元")
print(f"预付款:{valuation_result['deposit_price']} 元")
print(f"估价有效期:{valuation_result['valid_time']}\n")
# ------------------------------
# 步骤2:创建回收订单
# ------------------------------
order_params = {
"valuation_id": valuation_id,
"user_name": "张三",
"user_phone": "138****6789", # 实际场景需脱敏或加密
"user_address": "北京市朝阳区XX街道XX小区",
"logistics_type": "express" # 快递邮寄(门店自送为"store")
}
order_result = aihuishou_api.create_recycle_order(order_params)
if not order_result:
logging.error("创建订单失败,终止流程")
exit(1)
# 提取订单号(查询详情需用)
order_no = order_result["order_no"]
print(f"=== 回收订单创建结果 ===")
print(f"订单号:{order_no}")
print(f"收货快递单号:{order_result['express_no']}")
print(f"快递公司:{order_result['express_company']}")
print(f"订单状态:{order_result['status']}\n")
# ------------------------------
# 步骤3:查询订单详情
# ------------------------------
order_detail = aihuishou_api.get_order_detail(order_no)
if order_detail:
print(f"=== 订单详情({order_no})===")
print(f"订单状态:{order_detail['status']}")
print(f"创建时间:{order_detail['create_time']}")
print(f"用户信息:{order_detail['user_name']}({order_detail['user_phone']})")
print(f"物流状态:{order_detail['logistics_status'] if 'logistics_status' in order_detail else '待邮寄'}")
# 若订单已检测,打印检测结果
if "inspection_result" in order_detail:
print(f"检测结果:{order_detail['inspection_result']['conclusion']}")
print(f"最终回收价:{order_detail['inspection_result']['final