Lazada 开放平台的item_search接口是按关键字关键字搜索商品列表的核心工具,适用于东南亚跨境电商选品、市场分析、价格监控等场景。本文将全面讲解该接口的对接流程、参数配置、代码实现及最佳实践,帮助开发者系统掌握从入门到精通的全流程。
一、接口基础认知
二、对接前置准备
三、接口调用流程
四、代码实现示例(Python)
import requests
import hashlib
import time
import json
class LazadaSearchApi:
def __init__(self, app_key, app_secret, access_token=None, region="sg"):
self.app_key = app_key
self.app_secret = app_secret
self.access_token = access_token # 公开搜索可无需
self.region = region # 站点区域:sg/my/co.th/co.id/com.ph/com.vn
self.base_url = f"https://api.lazada.{region}/rest/product/search"
self.token_expire_time = 0 # 令牌过期时间(时间戳,秒)
def generate_sign(self, params):
"""生成签名"""
# 1. 按参数名ASCII升序排序
sorted_params = sorted(params.items(), key=lambda x: x[0])
# 2. 拼接为key=value格式
sign_str = "".join([f"{k}{v}" for k, v in sorted_params])
# 3. 前后添加app_secret
sign_str = self.app_secret + sign_str + self.app_secret
# 4. SHA256加密(大写)
sign = hashlib.sha256(sign_str.encode()).hexdigest().upper()
return sign
def refresh_access_token(self):
"""刷新access_token"""
token_url = f"https://api.lazada.{self.region}/rest/auth/token/refresh"
params = {
"app_key": self.app_key,
"refresh_token": "your_refresh_token", # 替换为实际的refresh_token
"timestamp": int(time.time())
}
# 生成签名
params["sign"] = self.generate_sign(params)
response = requests.get(token_url, params=params)
result = response.json()
if result.get("code") != "0":
raise Exception(f"令牌刷新失败: {result.get('message')}")
self.access_token = result["access_token"]
self.token_expire_time = time.time() + int(result["expires_in"])
return self.access_token
def item_search(self, keyword, page=1, limit=20, **kwargs):
"""
搜索商品列表
:param keyword: 搜索关键字(必填)
:param page: 页码,默认1
:param limit: 每页条数,默认20,最大50
:param kwargs: 可选参数(price_min, price_max, sort等)
:return: 搜索结果
"""
# 检查并刷新令牌(如需要)
if self.access_token and (not self.access_token or time.time() > self.token_expire_time - 3600):
self.refresh_access_token()
# 1. 组装基础参数
params = {
"app_key": self.app_key,
"timestamp": int(time.time()), # 秒级时间戳
"q": keyword,
"page": page,
"limit": limit
}
# 2. 添加可选参数
if self.access_token:
params["access_token"] = self.access_token
params.update(kwargs)
# 3. 生成签名
params["sign"] = self.generate_sign(params)
try:
# 4. 发送GET请求
response = requests.get(
url=self.base_url,
params=params,
timeout=15
)
response.raise_for_status()
result = response.json()
# 5. 处理响应
if result.get("code") != "0":
return {
"success": False,
"error_code": result.get("code"),
"error_msg": result.get("message")
}
data = result.get("data", {})
return {
"success": True,
"total_count": data.get("total_count", 0),
"page": page,
"limit": limit,
"total_pages": (data.get("total_count", 0) + limit - 1) // limit,
"items": data.get("products", [])
}
except Exception as e:
return {
"success": False,
"error_msg": f"请求异常: {str(e)}"
}
# 使用示例
if __name__ == "__main__":
# 替换为实际参数
APP_KEY = "your_app_key"
APP_SECRET = "your_app_secret"
ACCESS_TOKEN = None # 公开搜索可无需
REGION = "sg" # 新加坡站点
# 初始化API客户端
api = LazadaSearchApi(APP_KEY, APP_SECRET, ACCESS_TOKEN, REGION)
# 搜索"wireless earbuds",第1页,20条/页,价格10-100新元,按销量排序
result = api.item_search(
keyword="wireless earbuds",
page=1,
limit=20,
price_min=10,
price_max=100,
sort="sales" # 排序方式:sales-销量,price-价格,newest-最新
)
if result["success"]:
print(f"共搜索到 {result['total_count']} 个商品")
print(f"第 {result['page']} 页,共 {result['total_pages']} 页")
# 打印前5个商品信息
for i, item in enumerate(result["items"][:5]):
print(f"\n商品 {i+1}:")
print(f"ID: {item.get('item_id')}")
print(f"标题: {item.get('title')}")
print(f"售价: {item.get('price')} {item.get('currency')}")
print(f"销量: {item.get('sales_count')}")
print(f"卖家: {item.get('seller_name')}")
print(f"主图: {item.get('main_image')}")
else:
print(f"搜索失败: {result['error_msg']} (错误码: {result.get('error_code')})")