微店商品详情 item_get API 接入与爬虫式测试全流程(2025 最新)

关键词:微店开放平台、micro.item_get、签名鉴权、Python 自动化、数据驱动测试

一、接口能力速览

micro.item_get 是微店官方提供的"商品详情"原子接口,可一次性拿回 20+ 字段:标题、价格、库存、主图、SKU、销量、描述、上下架状态等。

  • 地址https://api.weidian.com/v3/item/get(正式)

  • 协议:HTTP GET/POST,JSON 返回

  • 鉴权:AppKey + AppSecret 签名(HMAC-SHA256)

  • QPS:单应用默认 200,店铺维度 1000,超出即 429

二、接入 4 步走

1. 注册&授权

  1. 登录微店平台 → 创建应用 → 审核通过后拿到

    • client_id(AppKey)

    • client_secret(AppSecret)

  2. 勾选 "商品管理" 权限包,否则调用会返回 401。

2. 获取 Access Token

微店使用 2 h 有效期的 Bearer Token,只需客户端凭证即可。

python 复制代码
import requests, json

def get_token(client_id, client_secret):
    url = 'https://open.weidian.com/api/oauth2/token'
    rsp = requests.post(url, data={
        'grant_type': 'client_credentials',
        'client_id': client_id,
        'client_secret': client_secret
    })
    return rsp.json()['access_token']

3. 生成签名(HMAC-SHA256)

官方要求所有私有参数必须参与签名,按 key 升序后 HMAC-SHA256 计算,输出 64 位大写 hex。

python 复制代码
import hmac, hashlib, urllib.parse, time

def sign(p: dict, secret: str) -> str:
    s = '&'.join([f"{k}={urllib.parse.quote_plus(str(p[k]))}"
                  for k in sorted(p)])
    return hmac.new(secret.encode(), s.encode(),
                    digestmod=hashlib.sha256).hexdigest().upper()

4. 拼装请求

access_tokentimestampsign 一并带在 Query 里即可。

python 复制代码
ITEM_ID = '2749499386'          # 替换成目标商品
TOKEN   = get_token(APP_KEY, APP_SECRET)

params = {
    'item_id': ITEM_ID,
    'access_token': TOKEN,
    'timestamp': int(time.time())
}
params['sign'] = sign(params, APP_SECRET)

url = 'https://api.weidian.com/v3/item/get'
r = requests.get(url, params=params, timeout=5)
print(json.dumps(r.json(), indent=2, ensure_ascii=False))

返回示例

javascript 复制代码
{
  "result": {
    "item_id": "2749499386",
    "title": "2025 春季新款风衣",
    "price": "299.00",
    "original_price": "399.00",
    "stock": 120,
    "sold_num": 45,
    "images": ["https://img.weidian.com/xxx.jpg"],
    "sku_list": [{"sku_id": "123", "spec": "红色;M", "price": "299", "stock": 30}]
  },
  "status": {"status_code": 0, "status_reason": "成功"}
}

三、把脚本升级成"爬虫"式测试

目标:对 500 个爆款商品每 30 min 跑一次,监控价格/库存变动并告警。

1. 数据驱动

Excel 维护商品池,pytest 参数化:

python 复制代码
import pytest, pandas as pd

IDS = pd.read_excel('hot_items.xlsx')['item_id'].tolist()

@pytest.mark.parametrize('iid', IDS)
def test_price_stock(iid):
    data = get_item_details(iid)        # 二次封装
    item = data['result']
    assert 0 < float(item['price']) < 2000
    assert int(item['stock']) > 0

2. 并发但限速

微店对"单 IP + 单应用"维度做秒级限流,推荐漏桶 50 QPS。

python 复制代码
import asyncio, aiohttp, asyncio.Semaphore

sem = asyncio.Semaphore(20)   # 20 并发

async def fetch(iid):
    async with sem:
        async with aiohttp.ClientSession() as session:
            async with session.get(URL, params=build_param(iid)) as r:
                return await r.json()

async def main():
    return await asyncio.gather(*[fetch(i) for i in IDS])

3. 异常&重试

错误码 含义 策略
429 QPS 超限 指数退避 1-2-4 s
401 Token 失效 自动刷新再重跑
5xx 服务端抖动 最多 3 次重试

4. 数据落库

  • 热数据(价格/库存)写 Redis,2 h TTL;

  • 冷数据 (全字段)写 MySQL,按 item_id 分片;

  • 差异对比 用 Python deepdiff,价格变动 ≥5 % 即钉钉推送。

四、完整可运行 Demo(单商品版)

python 复制代码
#!/usr/bin/env python3
# weidian_item_get.py
import requests, json, time, hmac, hashlib, urllib.parse

APP_KEY     = '你的AppKey'
APP_SECRET  = '你的AppSecret'
ITEM_ID     = '2749499386'

def token() -> str:
    url = 'https://open.weidian.com/api/oauth2/token'
    r = requests.post(url, data={
        'grant_type': 'client_credentials',
        'client_id': APP_KEY,
        'client_secret': APP_SECRET})
    return r.json()['access_token']

def sign(p: dict) -> str:
    s = '&'.join([f"{k}={urllib.parse.quote_plus(str(p[k]))}"
                  for k in sorted(p)])
    return hmac.new(APP_SECRET.encode(), s.encode(),
                    hashlib.sha256).hexdigest().upper()

def item_get(iid: str):
    tk = token()
    p = {'item_id': iid, 'access_token': tk, 'timestamp': int(time.time())}
    p['sign'] = sign(p)
    url = 'https://api.weidian.com/v3/item/get'
    r = requests.get(url, params=p, timeout=5)
    return r.json()

if __name__ == '__main__':
    print(json.dumps(item_get(ITEM_ID), ensure_ascii=False, indent=2))

运行结果:

复制

复制代码
{
  "result": {
    "item_id": "2749499386",
    "title": "2025 春季新款风衣",
    ...
  },
  "status": {"status_code": 0, "status_reason": "成功"}
}

五、常见坑汇总

  1. 签名大小写:必须 64 位大写 hex,否则 15-签名错误。

  2. 时间戳单位:秒级,10 位整数,毫秒会 400。

  3. Token 缓存:2 h 有效期,每 1.5 h 刷新一次,避免并发竞争刷新。

  4. 商品下架 :接口仍 200,但 is_on_sale=0,业务层需自行过滤。

六、合规 & 版权红线

  • 微店官方允许"自用型"数据抓取,但禁止将商品图片、描述等版权内容二次分发或用于竞品 SaaS 对外服务。

  • 建议把调用频率压在官方白皮书范围内,若需要更高配额,走"企业认证"通道。

七、结语

借助 micro.item_get,你可在 1 小时内完成"商品详情爬虫"到"监控告警"的闭环:

  • 开发阶段用本文脚本快速调试;

  • 上线阶段用 pytest + CI 跑每日巡检;

  • 运营阶段把价格/库存差异推送到飞书,真正做到数据驱动增长。

相关推荐
Kratzdisteln10 小时前
【Web-Crawler-Steamdt】以项目文件steamdt_crawler.py学习python爬虫
爬虫·python·学习
嫂子的姐夫10 小时前
03-自动化小案例
爬虫·自动化·drissionpage
嫂子的姐夫11 小时前
02-DrissionPage
爬虫·drissionpage·自动化爬虫
Pyeako11 小时前
操作HTML网页(PyCharm版)
爬虫·python·html
傻啦嘿哟12 小时前
学术爬虫实战:构建知网论文关键词共现网络的技术指南
网络·爬虫
几分醉意.14 小时前
Bright Data AI Scraper Studio:用一句Prompt,自动生成企业级爬虫架构
人工智能·爬虫·prompt
sugar椰子皮1 天前
【爬虫框架-3】闭包的用法
爬虫
齐齐大魔王1 天前
python爬虫学习进程(四)
爬虫·python·学习
毕设源码-钟学长1 天前
【开题答辩全过程】以 基于Python爬虫的二手房信息爬取及分析为例,包含答辩的问题和答案
开发语言·爬虫·python