Home / Blog / Amazon Buy Box Lost Alert in WeCom: Read errcode, Not HTTP Status

Amazon Buy Box Lost Alert in WeCom: Read errcode, Not HTTP Status

Get an Amazon Buy Box lost alert pushed to WeCom (Enterprise WeChat): poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check and POST one markdown message per run to a group robot webhook. WeCom always answers HTTP 200; the script reads the errcode field inside the JSON body instead, and caps the message on UTF-8 bytes, not characters. Costs one credit per ASIN per check.

November 29, 2026
8 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing the Amazon Buy Box lost alert a Python script sent via WeCom

To get an Amazon Buy Box lost alert pushed to WeCom (Enterprise WeChat) today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and POST one markdown message per run to your WeCom group robot's webhook. The one thing every other channel in this series gets you ready for and WeCom breaks the same way DingTalk and Lark do: the HTTP response is always 200, success or failure, so the script never looks at resp.status_code alone for the outgoing call - it reads the errcode field inside the JSON body. WeCom adds its own trap on top: the markdown body is capped at 4096 bytes of UTF-8, not characters, so the script trims on the encoded length. The script below tells a lost Buy Box apart from a suppressed one, retries the one errcode WeCom actually wants retried, and costs one SellerMagnet credit per ASIN per check.

Key Takeaways

  • A WeCom group-robot send answers HTTP 200 on every outcome - the real result is the JSON body's errcode (0 = sent), never the HTTP status alone, the same shape as DingTalk's errcode and Lark's code earlier in this series.
  • errcode 45009 is the one result in this series that means 'retry' for WeCom: the documented per-robot rate limit of 20 messages a minute. The script waits 5s and resends once.
  • errcode 93000 means the webhook key is invalid or the robot was removed from the group - a setup problem, never retried.
  • The markdown content cap is 4096 BYTES of UTF-8, not characters; a character-count cap would let CJK text (3 bytes per character) through that WeCom still rejects. The script encodes first, then trims.
  • buyBox is the featured offer: its sellerId is the seller who holds the Buy Box, the literal "Amazon" when Amazon does.
  • Alert only when two checks in a row agree: an offer page can come back without parsable offers, and one reading should not page you.
  • Each check costs 1 SellerMagnet credit per ASIN; 502/503 retries are billed per attempt, a 500 is refunded, and a free 401/403 stops the run with one STOP message.

Why is WeCom's result inside the body, not the HTTP status?

Every group-robot send is POST https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<uuid> (developer.work.weixin.qq.com/document/path/91770, checked 2026-11-29), and the server answers HTTP 200 whether the message actually landed or not. The documented success body is {"errcode": 0, "errmsg": "ok"}. A non-zero errcode with a readable errmsg marks a failure. Checking resp.status_code the way every non-DingTalk, non-Lark sibling channel in this series does would pass every one of these failure cases, because the status code itself never changes.

The four readings and the WeCom message each one can trigger.
ResponseReadingWeCom message
buyBox.sellerId is your sellerIdmineBACK, after a confirmed loss
buyBox.sellerId is any other seller or "Amazon"lostLOST, with holder, price and your offer
buyBox is {} and buyBoxSuppressed is truesuppressedNONE
buyBox is {} and offers is []no-offersEMPTY

How do I build the Amazon Buy Box lost alert for WeCom?

read_buy_box() turns one offers response into a reading, check() keeps a streak per ASIN in buybox_state.json and queues a line once a new reading has been seen CONFIRM times in a row, and post_to_wecom() sends every queued line as one markdown message. get_with_retry comes from retry.py and ApiError/new_session from sellermagnet.py, both from the Python quickstart. Malformed ASINs are skipped before any call, because the offers endpoint bills a typo like any other request. MY_SELLER_ID has no default on purpose: without it every ASIN would read as lost, so the script refuses to start. _markdown_body() builds the text and, only if the UTF-8 encoding of it is over 4096 bytes, decodes a truncated slice back with errors="ignore" so a multi-byte character is never cut in half, then re-encodes to confirm the result fits.

buybox_wecom_alert.py - offers check, 2-check confirmation, one group-robot send per run

import json
import os
import re
import time

import requests

from retry import get_with_retry
from sellermagnet import ApiError, new_session

MARKETPLACE_ID = "ATVPDKIKX0DER"                 # amazon.com
MY_SELLER_ID = os.environ["MY_SELLER_ID"]        # your sellerId as it appears in offers[]; no default on purpose
ASINS = ["B0CL61F39H", "B0EXAMPLE2", "B0EXAMPLE3"]
CONFIRM = 2                                      # same reading on 2 checks in a row before WeCom hears about it
STATE_FILE = "buybox_state.json"
ASIN_RE = re.compile(r"^[A-Z0-9]{10}$")           # offers calls are billed even for a typo, so filter first

WECOM_WEBHOOK = os.environ["WECOM_WEBHOOK"]   # https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<uuid>
MAX_MARKDOWN_BYTES = 4096                     # developer.work.weixin.qq.com/document/path/91770: markdown content,
                                               # max 4096 BYTES (utf-8), not characters - CJK text can hit this fast
MAX_LINES = 200
RATE_LIMIT_CODE = 45009                       # documented cap: 20 messages/minute per webhook key
INVALID_BOT_CODE = 93000                      # bad/rotated key, or the bot was removed from the group


def read_buy_box(session, asin: str) -> tuple[str, str]:
    """('mine' | 'lost' | 'suppressed' | 'no-offers', detail for the message)."""
    data = get_with_retry(session, "amazon-product-offers", asin=asin, marketplaceId=MARKETPLACE_ID)
    box = data.get("buyBox") or {}
    if not box:
        return ("suppressed", "") if data.get("buyBoxSuppressed") else ("no-offers", "")
    holder = box.get("sellerId") or "unknown"
    if holder == MY_SELLER_ID:
        return "mine", ""
    currency = (data.get("currency") or {}).get("code", "")
    detail = f"held by {box.get('sellerName', 'unknown')} ({holder}, {box.get('fulfillment', '?')}) at {box.get('price')} {currency}"
    return "lost", detail


def _load_state() -> dict:
    try:
        with open(STATE_FILE) as f:
            return json.load(f)
    except FileNotFoundError:
        return {}


def _save_state(state: dict) -> None:
    with open(STATE_FILE, "w") as f:
        json.dump(state, f)


def check(session, state: dict) -> list[str]:
    """Advance the streak for every ASIN, return the lines to push this run (confirmed changes only)."""
    lines = []
    for asin in ASINS:
        if not ASIN_RE.match(asin):
            continue
        reading, detail = read_buy_box(session, asin)
        entry = state.get(asin)
        if entry is None:
            state[asin] = {"reading": reading, "streak": CONFIRM, "reported": reading}  # seed, no false alert
            continue
        if entry["reading"] == reading:
            entry["streak"] = min(entry["streak"] + 1, CONFIRM)
        else:
            entry["reading"], entry["streak"] = reading, 1
        if entry["streak"] >= CONFIRM and entry["reported"] != reading:
            entry["reported"] = reading
            if reading == "lost":
                lines.append(f"{asin}: LOST, {detail}")
            elif reading == "mine":
                lines.append(f"{asin}: BACK, you hold the Buy Box again")
    return lines


def _markdown_body(lines: list[str]) -> str:
    """Build the markdown content and cap it to 4096 UTF-8 BYTES (WeCom counts bytes, not characters,
    so this encodes first and trims on the encoded length, never on len(text))."""
    text = "**Amazon Buy Box change, confirmed on 2 checks:**\n" + "\n".join(f"> {l}" for l in lines)
    encoded = text.encode("utf-8")
    if len(encoded) > MAX_MARKDOWN_BYTES:
        encoded = encoded[:MAX_MARKDOWN_BYTES - 40].decode("utf-8", "ignore").encode("utf-8")
        encoded += b"\n> ...(truncated)"
    return encoded.decode("utf-8")


def post_to_wecom(lines: list[str]) -> bool:
    """One POST per run to the group robot webhook. WeCom answers HTTP 200 even on a failure; the
    real result is the JSON body's `errcode` field (0 = sent), never the HTTP status alone. Returns
    True only on HTTP 200 AND errcode 0."""
    if not lines:
        return False
    if len(lines) > MAX_LINES:
        lines = lines[:MAX_LINES] + [f"...and {len(lines) - MAX_LINES} more"]
    text = _markdown_body(lines)
    payload = {"msgtype": "markdown", "markdown": {"content": text}}
    resp = requests.post(WECOM_WEBHOOK, headers={"Content-Type": "application/json"},
                          json=payload, timeout=30)
    try:
        body = resp.json()
    except ValueError:
        print(f"[wecom] non-JSON response, HTTP {resp.status_code}, left unreported")
        return False
    errcode, errmsg = body.get("errcode"), body.get("errmsg", "")
    if resp.status_code != 200:
        print(f"[wecom] HTTP {resp.status_code}, left unreported")
        return False
    if errcode == 0:
        print(f"[wecom] {text}")
        return True
    if errcode == RATE_LIMIT_CODE:
        # 20 messages/minute per webhook key (developer.work.weixin.qq.com/document/path/91770).
        # One fixed backoff-and-retry, same shape as Lark's 19021 and DingTalk's 130101 in this series.
        time.sleep(5)
        resp = requests.post(WECOM_WEBHOOK, headers={"Content-Type": "application/json"},
                              json=payload, timeout=30)
        try:
            body = resp.json()
        except ValueError:
            body = {}
        if resp.status_code == 200 and body.get("errcode") == 0:
            print(f"[wecom] {text}")
            return True
        print("[wecom] still rate-limited after 1 retry, left unreported")
        return False
    if errcode == INVALID_BOT_CODE:
        # bad/rotated key, or the robot was removed from the group - retrying this run cannot fix it.
        print(f"[wecom] STOP errcode={errcode} {errmsg} (webhook key invalid or bot removed)")
        return False
    print(f"[wecom] errcode={errcode} {errmsg}, left unreported")
    return False


def main() -> None:
    session = new_session()
    state = _load_state()
    lines = check(session, state)
    sent = post_to_wecom(lines)
    _save_state(state)
    print(f"{len(ASINS)} checked, {1 if sent else 0} alert(s) sent")


if __name__ == "__main__":
    main()

Five runs of the script (illustrative ASIN and seller; bracketed line = the message sent)

--- run 1 (illustrative ASIN and seller)
3 checked, 0 alert(s) sent
--- run 2, B0EXAMPLE2 lost (1st sighting, not yet confirmed)
3 checked, 0 alert(s) sent
--- run 3, same reading confirmed
[wecom] **Amazon Buy Box change, confirmed on 2 checks:**
> B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD
3 checked, 1 alert(s) sent
--- run 4, back to mine (1st sighting, not yet confirmed)
3 checked, 0 alert(s) sent
--- run 5, back to mine, confirmed
[wecom] **Amazon Buy Box change, confirmed on 2 checks:**
> B0EXAMPLE2: BACK, you hold the Buy Box again
3 checked, 1 alert(s) sent

What the script actually POSTs (curl equivalent, illustrative values)

curl -s -X POST "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=693a91f6-7xxx-4bc4-97a0-0ec2sifa5aaa" \
  -H "Content-Type: application/json" \
  -d '{"msgtype": "markdown", "markdown": {"content": "**Amazon Buy Box change, confirmed on 2 checks:**\n> B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD"}}'
# HTTP 200 {"errcode": 0, "errmsg": "ok"}  <- success is still just a 200, read errcode
Blueprint flow: offers check per ASIN, two-check confirmation, then one WeCom send
A reading has to repeat before it reaches WeCom; the result comes from errcode.

How do I create the robot and read its errcode?

  1. Add the robotOpen the target WeCom group, Group Settings, Group Robots, Add a Robot, give it a name and finish setup.
  2. Copy the webhook URLhttps://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<uuid>. The key in the URL is the only thing protecting this robot; treat it like a password and never commit it.
  3. Send a test message and read errcodecurl -d '{\"msgtype\": \"text\", \"text\": {\"content\": \"test\"}}' <webhook>; the HTTP status is 200 either way, so check the body's errcode - 0 is the only value that means it actually arrived.
  4. Watch the rate limit20 messages a minute per robot. Route high-volume alerts through confirmation and batching rather than one message per reading.

Environment file and a cron entry for a 15-minute check (flock -n prevents overlapping runs)

# .env (keep it out of git: the webhook key lets anyone post to your group)
export SELLERMAGNET_API_KEY="your-key-here"
export WECOM_WEBHOOK="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
export MY_SELLER_ID="A1MYSELLER0001"              # your sellerId as it appears in offers[]

# crontab -e: every 15 minutes, 3 ASINs = 288 credits a day; flock -n skips a run while the last one still runs
*/15 * * * * cd /opt/buybox && . ./.env && flock -n .lock .venv/bin/python buybox_wecom_alert.py >> alert.log 2>&1

WeCom's own message-push documentation (developer.work.weixin.qq.com/document/path/91770, checked 2026-11-29) describes the contract the script relies on: every response is HTTP 200 and carries errcode/errmsg, the markdown content type is capped at 4096 bytes of UTF-8, and the whole webhook is capped at 20 messages per minute. Third-party integration guides (not WeCom's own docs) additionally report the specific numeric codes this script handles - 45009 for the rate limit and 93000 for an invalid or removed robot - which is why those two are cited as community-reported rather than from the primary source.

What should you check when a LOST alert fires?

The alert tells you who holds the Buy Box and at what total price, not why Amazon featured that offer. Amazon's US help page Becoming the Featured Offer (Seller Central, checked 2026-10-23) lists what it weighs: the total price including shipping, a fast and specific delivery promise, free shipping, free returns and seller performance, and an out-of-stock offer cannot be featured. Its Featured Offer guide on sell.amazon.com adds that fulfilling orders yourself can be just as effective as FBA. Start with the gap between the holder's price and your offer in the message, then your delivery date and stock. The Buy Box price gap guide shows why the lowest price alone does not decide it.

How many credits does a Buy Box alert cost?

One offers call per ASIN per check, so the SellerMagnet cost is the number of ASINs times the number of checks; WeCom's own group-robot API is free for this volume, far under its 20-message-a-minute rate limit for a batch sent once per confirmed change. With a 2-check confirmation the worst-case delay before WeCom hears about a loss is about two intervals. Errors add to the SellerMagnet bill in different ways: a 404 is billed once and not retried, a 502 or 503 is billed on every attempt, a 500 is refunded, and the free gate errors (400 for a missing parameter, 401, 403) cost nothing. The Buy Box monitoring interval guide compares intervals in more detail, and Pricing lists the plans.

Credits per tracked ASIN by check interval (1 credit per offers call).
Check intervalCredits per dayCredits per 30 daysWorst-case alert delay
Every 15 minutes962,880about 30 minutes
Every hour24720about 2 hours
Every 4 hours6180about 8 hours
Once a day130about 2 days
Blueprint table of credits per tracked ASIN for four check intervals and the alert delay
Shorter intervals cost more credits and cut the delay; the confirmation doubles it.

Frequently Asked Questions

Do I need a WeCom admin role before I can send?

No. Open the target group in WeCom, Group Settings, Group Robots, Add a Robot, give it a name, and copy the Webhook URL it hands you. That is the whole setup; there is no app review, OAuth or corp secret involved, unlike WeCom's self-built-app path.

Why does WeCom's response look nothing like Telegram's or Rocket.Chat's?

A group-robot send always answers HTTP 200 (developer.work.weixin.qq.com/document/path/91770, checked 2026-11-29), even on a failure. The real result lives inside the JSON body's errcode field: 0 means sent, anything else is an error, with a human-readable errmsg next to it. That is the same shape as DingTalk and Lark earlier in this series and the opposite of Telegram's ok boolean on a real HTTP status or Rocket.Chat's bare success true - this script never once branches on resp.status_code alone for the outgoing call, only on body['errcode'] after confirming the status is 200.

Why cap the markdown body on bytes, not characters?

The official limit is 4096 bytes of UTF-8, not 4096 characters (developer.work.weixin.qq.com/document/path/91770). A seller name or city in CJK script runs 3 bytes per character, so a character-count cap would let a body through that WeCom still rejects. The script encodes to UTF-8 first and trims on the encoded length, then decodes back with errors="ignore" so it never splits a multi-byte character in half.

Why does errcode 45009 get retried when every other errcode here means stop?

45009 is the documented per-webhook throttle: a single group robot is capped at 20 messages a minute. The script waits 5 seconds and resends the identical payload once; a second 45009 in a row is logged and dropped rather than looped.

What does errcode 93000 mean, and why isn't it retried?

93000 means the webhook key is invalid, or the robot that owned it has been removed from the group. Resending the exact same payload changes nothing, so the script reports it and stops instead of retrying.

What happens when my SellerMagnet credits run out?

The API answers 401 (or 403 during a burst), which is not billed. The script stops instead of calling the remaining ASINs, sends one STOP message and does not repeat it until a run gets through without a 401 or 403.

Bottom line: compare buyBox.sellerId with your own seller ID, keep a streak per ASIN, and post one WeCom group-robot message per run - read errcode inside the body, never the HTTP status, cap the markdown on UTF-8 bytes, and retry only the documented 45009 rate limit. To see who held the Buy Box and for how long after the fact, use the Buy Box history API; a free account includes 150 credits to try the alert.

Related Articles

Continue exploring topics related to this article.

Terminal window showing the Amazon Buy Box lost alert a Python script sent through Threema Gateway
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in Threema: a Bare Message ID, Not JSON

Get an Amazon Buy Box lost alert sent through Threema Gateway: poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm on a second check and POST one form-encoded message per run to send_simple. A successful send answers HTTP 200 with the new message's id as bare plain text, no JSON, while every failure gets its own HTTP status. Tested Python, one credit per ASIN per check.

Nov 29, 2026 Read
Terminal window showing the Amazon Buy Box lost alert a Python script posted to Chatwork
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in Chatwork: Form Body, Not JSON

Get an Amazon Buy Box lost alert posted straight into Chatwork: poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check and POST one message per run through Chatwork's Add Message endpoint. Covers the X-ChatWorkToken header auth, the form-urlencoded body other channels get wrong by sending JSON, and the two separate 429 rate limiters. Tested Python, one credit per ASIN per check.

Nov 29, 2026 Read
Terminal window showing the Amazon Buy Box lost alert a Python script sent via Pushsafer
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in Pushsafer: the Error Code Is the HTTP Status

Get an Amazon Buy Box lost alert sent to Pushsafer: poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check and call POST /api once per run with just a private key and a message. A failed send answers with its error CODE written into the HTTP status line itself (250, 255, 260, 270, 280), not a normal 4xx/5xx, so the script checks the status code directly instead of trusting raise_for_status(). 1 credit per ASIN per check.

Nov 29, 2026 Read
Back to Blog

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime