📖 Shopee Aff API — Tài liệu

🤖 llms.txt (cho AI) 🧾 Đối soát 🍪 Cookie 🧪 Test

Giới thiệu

REST API cho hệ thống cashback Shopee affiliate: tạo affiliate link gắn theo từng user (để quy hoa hồng) và lấy báo cáo chuyển đổi. Mọi response là JSON với trường ok: true/false.

✅ Stateless — tạo link chỉ là ghép chuỗi qua endpoint chuyển hướng chính thức của Shopee (s.shopee.vn/an_redir). Không cần Chrome, không captcha, không proxy, không đăng nhập.

Kiến trúc

Tạo link:  client → POST /api/link → linkBuilder → chuỗi s.shopee.vn/an_redir
           (khi user click → Shopee tự gắn tracking + redirect tới sản phẩm)

Báo cáo:   client → GET /api/report → affiliate.shopee.vn/report/list (bằng cookie)

Link affiliate có dạng:

https://s.shopee.vn/an_redir?origin_link=<url SP>&affiliate_id=<id>&sub_id=<s1-s2-s3-s4-s5>

Khi user click, Shopee 301 tới trang sản phẩm và tự gắn utm_source=an_<affiliate_id>, utm_content=<sub_id>, utm_medium=affiliates → hoa hồng quy về đúng affiliate + user. Đây là cơ chế các network (AccessTrade/Involve Asia) vẫn dùng.

💡 origin_link nên là URL sản phẩm chuẩn (...-i.<shop>.<item> hoặc /product/<shop>/<item>). Link rút gọn (s.shopee.vn/xxx) được server tự resolve về URL chuẩn trước (nếu không sẽ mất tracking).

affiliate_id là ID tĩnh của tài khoản affiliate (công khai, nằm trong mọi link). Cấu hình phía server qua env SHOPEE_AFFILIATE_ID hoặc config.affiliateId; có thể override từng request bằng trường affiliateId trong body.

Cashback & SubIds

Shopee cho gắn tối đa 5 SubId vào mỗi link; khi có đơn, báo cáo trả lại đúng các SubId → dùng để quy đơn về từng user.

⚠️ SubId chỉ chấp nhận [a-zA-Z0-9], tối đa 40 ký tự — không dấu gạch dưới, không ký tự đặc biệt. Vi phạm → server trả 400 INVALID_SUBID trước khi tạo link.
SubIdÝ nghĩaVí dụ
subId1userId — người nhận cashback (truyền qua trường userId)u12345
subId2Nguồn / nền tảngweb, app
subId3Nhãn / chiến dịchcashback
subId4, subId5Tuỳ ý (mã đơn, click id…)—

Luồng cashback:

  1. User bấm "lấy link" → gọi POST /api/link kèm userId → link gắn subId1 = userId.
  2. User mua hàng qua link đó.
  3. Cron định kỳ gọi GET /api/report/by-subid?subIds=<userId> → ra đơn + hoa hồng → cộng cashback.
💡 Nên cache (userId, originalLink) → shortLink ở DB riêng — link Shopee là vĩnh viễn. (Thực ra link an_redir là tất định nên có thể tự dựng, nhưng cache vẫn giảm số lần gọi.)

Xác thực

Nếu config.apiKey khác rỗng, mọi request /api/* phải kèm header:

x-api-key: <apiKey của bạn>

⭐ Hướng dẫn tích hợp (cho backend / AI)

🤖 Cho AI agent: đọc bản tối ưu máy tại /llms.txt (markdown thuần, đầy đủ endpoint + code).

Base URL: https://shopee-api.apps.neooi.com  ·  Header bắt buộc: x-api-key: <API_KEY> cho mọi /api/*.

Đặt ở env backend của bạn: SHOPEE_API=https://shopee-api.apps.neooi.com, SHOPEE_API_KEY=<key>. Mọi response JSON có ok:true/false; lỗi kèm code + error.

💰 Đơn vị tiền: Shopee lưu ×100000. /api/conversions ĐÃ quy về VND; /api/report thô thì CHƯA (tự chia 100000).
🧩 Một nguồn duy nhất = shopee-aff. Gọi mọi thứ qua API này: POST /api/link (tạo link), GET /api/product (giá + hoa hồng dự kiến trước mua — proxy AddLiveTag bên dưới, bạn không cần gọi AddLiveTag trực tiếp), GET /api/conversions (hoa hồng THẬT sau mua). ⚠️ Tiền trả cashback luôn lấy từ /api/conversions, KHÔNG dùng số dự kiến của /api/product (số này tính trên giá niêm yết × rate hiện tại, có thể lệch).

Luồng 1 — Tạo link cashback (khi user bấm "lấy link")

Nên cache (userId, originalLink) → shortLink ở DB của bạn (link vĩnh viễn) để khỏi gọi lại.

async function getCashbackLink(userId, originalLink) {
  const cached = await db.links.findOne({ userId, originalLink });
  if (cached) return cached.shortLink;
  const r = await fetch(process.env.SHOPEE_API + "/api/link", {
    method: "POST",
    headers: { "content-type": "application/json", "x-api-key": process.env.SHOPEE_API_KEY },
    body: JSON.stringify({ originalLink, userId }), // userId: chỉ [a-zA-Z0-9], ≤ 40 ký tự
  });
  const j = await r.json();
  if (!j.ok) throw new Error(`link fail ${j.code}: ${j.error}`);
  await db.links.insert({ userId, originalLink, shortLink: j.shortLink, at: Date.now() });
  return j.shortLink; // https://s.shopee.vn/an_redir?origin_link=...&affiliate_id=...&sub_id=userId-...
}

Luồng 2 — Đối soát + cashback + clawback (cron)

Dùng /api/conversions (đã chuẩn hoá: 1 dòng/order, có userId, status, commission VND, isFraud). Gợi ý cron: mỗi 1–2h lấy 3–7 ngày + mỗi ngày quét 30–45 ngày.

async function reconcile() {
  const j = await fetch(process.env.SHOPEE_API + "/api/conversions?days=30&size=100",
    { headers: { "x-api-key": process.env.SHOPEE_API_KEY } }).then(r => r.json());
  if (!j.ok) { alertAdmin(j.code, j.error); return; }  // NO_REPORT_COOKIE → cập nhật /cookie.html
  for (const c of j.conversions) {
    if (!c.matched) { await saveUnmatched(c); continue; }              // đơn rụng sub_id → chờ gán tay
    if (c.status === "CANCELLED" || c.status === "REFUNDED") {
      await clawback(c.orderSn);                                        // thu hồi nếu đã trả (P3)
    } else if (c.status === "COMPLETED" && !c.isFraud) {
      await creditCashback(c.orderSn, c.userId, c.commission);         // idempotent theo orderSn
    }
  }
}
💡 Chỉ trả cashback khi status==="COMPLETED" && !isFraud; CANCELLED/REFUNDED → thu hồi. orderSn làm khoá UNIQUE (không cộng trùng). Đơn matched:false → lưu "chờ gán", gán bằng POST /api/conversions/map.

Giám sát

Gọi GET /api/selfcheck hằng ngày (200 = khỏe, 503 = lỗi — tiện gắn UptimeRobot). Server cũng tự chạy mỗi 24h và báo Telegram khi cookie report hết hạn.

Endpoints

GET /health

Kiểm tra server sống. Không yêu cầu x-api-key.

{ "ok": true, "service": "shopee-aff-api", "mode": "stateless", "endpoints": [ ... ] }

GET /api/product (giá + hoa hồng DỰ KIẾN trước mua)

Thông tin sản phẩm trước khi mua, để hiển thị cho khách. shopee-aff proxy AddLiveTag bên dưới (Shopee chặn server lấy trực tiếp). ⚠️ Số là dự kiến (giá niêm yết × rate hiện tại) — tiền trả cashback lấy từ /api/conversions.

Query: url=<link SP shopee> hoặc itemId=<id>&shopId=<id>
curl -H "x-api-key: <key>" "https://shopee-api.apps.neooi.com/api/product?url=https://shopee.vn/product/<shop>/<item>"
{
  "ok": true,
  "product": {
    "itemId": 56259982883, "shopId": 331177632,
    "name": "1kg lạp xưởng 5 vị ...", "shopName": "...",
    "price": 152000,              // VND (giá niêm yết)
    "commission": 16720,         // VND — DỰ KIẾN (estimate:true)
    "sellerRatePercent": 7, "shopeeRatePercent": 4, "totalRatePercent": 11,
    "cap": 40000, "isCapped": false,
    "sales": 305, "rating": "4.80", "image": "https://...", "category": ["Bách Hóa Online","Đồ ăn vặt"],
    "estimate": true
  }
}

GET /api/conversions  ⭐ khuyên dùng cho backend

Report đã chuẩn hoá: 1 dòng / order, tự parse userId, trạng thái chuẩn, tiền VND, kèm item. Tự áp dụng gán tay (map).

Query: days=30, size=100, unmatched=1 (chỉ đơn chưa map), status=COMPLETED|CANCELLED|REFUNDED|PENDING, userId=<id>
curl -H "x-api-key: <key>" "https://shopee-api.apps.neooi.com/api/conversions?days=30"
{
  "ok": true,
  "summary": { "total": 2, "matched": 0, "unmatched": 2, "commission": 0, "byStatus": { "COMPLETED": 2 } },
  "conversions": [
    {
      "orderSn": "2609153X4NF8KA", "checkoutId": "2431354...",
      "userId": "", "subId": "----", "matched": false, "manual": false,
      "commission": 0,                 // VND (đã ÷100000)
      "status": "COMPLETED",           // COMPLETED|CANCELLED|REFUNDED|PENDING
      "isFraud": true,                 // true = Shopee từ chối hoa hồng
      "orderValue": 91520, "itemName": "Sữa Rửa Mặt ...",
      "purchaseTime": 1789436248, "completeTime": 1789891472,
      "device": "App", "source": "Zalo",
      "items": [ { "itemId": 46309158593, "name": "...", "shopName": "...",
                   "price": 104000, "actual": 91520, "qty": 1, "commission": 0,
                   "isFraud": true, "fraudReason": "..." } ],
      "raw": { "order_status": "COMPLETED", "conversion_status": 3, "cancel_reason": null }
    }
  ]
}

Quy user: userId có sẵn mỗi dòng (từ sub_id hoặc gán tay). matched:false = đơn rụng sub_id → chờ gán. Clawback: theo dõi status + isFraud. Xem code ở Hướng dẫn tích hợp.

POST /api/conversions/map

Gán tay order_sn → userId khi đơn rụng sub_id (unmatched). Tự áp dụng trong /api/conversions. Lưu bền trên volume.

curl -X POST https://shopee-api.apps.neooi.com/api/conversions/map \
  -H "x-api-key: <key>" -H "Content-Type: application/json" \
  -d '{"orderSn":"2609153X4NF8KA","userId":"u12345"}'   # userId="" để xoá gán

GET /api/conversions/map → { ok, map: { orderSn: userId } }.

GET /api/report (shape thô — ưu tiên /api/conversions)

Lấy danh sách đơn chuyển đổi. Đọc bằng cookie — xem mục Cookie report.

Query params
ParamMặc địnhMô tả
days7Số ngày gần nhất
page1Trang
size50Số đơn mỗi trang
curl -H "x-api-key: <key>" "https://shopee-api.apps.neooi.com/api/report?days=7"

Dữ liệu theo checkout; sub_id nằm ở utm_content (chuỗi subId1-subId2-...), đơn nằm trong mảng orders:

{
  "ok": true, "total": 2,
  "list": [
    {
      "checkout_id": "2431354...",
      "purchase_time": 1789436248,
      "utm_content": "u12345-web-cashback",        // ← sub_id (subId1-subId2-subId3...)
      "affiliate_id": 17384700594,
      "conversion_status": 3,                       // mã số trạng thái chuyển đổi
      "gross_commission": 0,
      "estimated_total_commission": 0,             // hoa hồng dự kiến
      "device": "App",
      "orders": [
        { "order_sn": "2609153X4NF8KA", "order_id": "2431354...",
          "order_status": "COMPLETED", "display_order_status": 3,
          "complete_time": 1789891472 }
      ]
    }
  ]
}

Quy user: utm_content.split("-")[0] = userId (subId1). Hoa hồng: estimated_total_commission (dự kiến) hoặc gross_commission (khi xác nhận). Khoá idempotent: order_sn trong orders[]. Xem code đối soát ở mục Hướng dẫn tích hợp.

GET /api/report/by-subid

Lọc đơn theo SubID — lấy đơn của một user cụ thể.

ParamMặc địnhMô tả
subIds—Danh sách SubID cách nhau dấu phẩy (thường là userId)
days7Số ngày gần nhất
curl -H "x-api-key: <key>" "https://shopee-api.apps.neooi.com/api/report/by-subid?subIds=u12345&days=30"
{ "ok": true, "total": 40, "matchedCount": 3, "subIds": ["u12345"], "matched": [ ... ] }

GET /api/selfcheck

Tự kiểm tra hệ thống (4 mục: affiliate_id, tạo link, tracking, cookie report). Trả 200 nếu ok, 503 nếu lỗi — tiện gắn uptime monitor.

curl -H "x-api-key: <key>" "https://shopee-api.apps.neooi.com/api/selfcheck"
{ "ok": true, "at": "...", "checks": [
  { "name": "affiliate_id",  "ok": true, "detail": "…0594" },
  { "name": "build_link",    "ok": true, "detail": "ok" },
  { "name": "link_tracking", "ok": true, "detail": "301 + utm_source/utm_content đúng" },
  { "name": "report_cookie", "ok": true, "detail": "ok (N đơn / 1 ngày)" }
] }

POST /api/notify/config

Cấu hình kênh thông báo (Telegram/webhook), lưu runtime trên volume. Ghi đè config.notify.

curl -X POST https://shopee-api.apps.neooi.com/api/notify/config \
  -H "x-api-key: <key>" -H "Content-Type: application/json" \
  -d '{"botToken":"123:ABC","chatId":"-5373990315","enabled":true}'
{ "ok": true, "enabled": true, "telegram": { "botSet": true, "chatId": "-5373990315" }, "hasWebhook": false }

GET /api/notify/config → trạng thái hiện tại (không lộ token). Thêm webhook để gửi POST JSON tới URL của bạn.

GET /api/notify/test

Gửi 1 tin test đến Telegram/webhook đã cấu hình.

curl -H "x-api-key: <key>" "https://shopee-api.apps.neooi.com/api/notify/test"

Mã lỗi

Mọi lỗi trả cùng cấu trúc, kèm hint khi có:

{ "ok": false, "code": "NO_REPORT_COOKIE", "error": "...", "hint": "..." }
HTTPcodeÝ nghĩa & cách xử lý
400MISSING_LINKThiếu originalLink.
400INVALID_SUBIDuserId/subIds có ký tự không hợp lệ. Chỉ [a-zA-Z0-9].
400MISSING_COOKIEPOST cookie nhưng body rỗng.
401—Sai hoặc thiếu x-api-key.
404—Sai endpoint.
500NO_AFFILIATE_IDServer chưa cấu hình affiliate_id (env SHOPEE_AFFILIATE_ID / config.affiliateId).
502SHOPEE_FAIL_2Không nhận diện được sản phẩm từ link. Dùng link shopee.vn hợp lệ.
503NO_REPORT_COOKIEChưa cấu hình cookie report. Vào /cookie.html dán cookie.
500INTERNAL_ERRORLỗi khác (vd cookie report hết hạn — Shopee trả 90309999). Cập nhật cookie mới.

Report đọc bằng cookie affiliate.shopee.vn (không bị chặn TLS/captcha như tạo link). Cookie sống ~1–2 tuần.

Cập nhật cookie
  1. Mở /cookie.html, nhập API key.
  2. Đăng nhập affiliate.shopee.vn → trang Báo cáo chuyển đổi → F12 → Network → request report/list → Request Headers → copy header Cookie.
  3. Dán vào ô Cookie → Lưu → Test.
✅ Khi cookie hết hạn (report lỗi 90309999) → server tự gửi cảnh báo Telegram/webhook nhắc vào /cookie.html.
Tần suất gọi report (khuyến nghị cho cron phía backend cashback)
NhịpKhoảng lấyMục đích
Mỗi 1–2 giờ3–7 ngàyBắt đơn mới nhanh
Mỗi ngày 1 lần30–45 ngàyCập nhật xác nhận/hủy (thu hồi cashback)

Gọn nhất: 1 cron mỗi 2 giờ, lấy 30 ngày. Đừng gọi dày dưới 1 giờ (dữ liệu Shopee cập nhật chậm).

Thông báo (Telegram / Webhook)

Server tự bắn thông báo khi cookie report hết hạn. Cấu hình config.notify:

"notify": {
  "enabled": true, "cooldownSec": 300,
  "telegram": { "botToken": "123:ABC", "chatId": "123456789" },
  "webhook": "https://..."
}
  1. Chat @BotFather → /newbot → lấy botToken.
  2. Nhắn 1 tin cho bot, mở https://api.telegram.org/bot<token>/getUpdates → lấy chat.id.
  3. Điền vào config.notify.telegram (production: File Mount config.json trên Dokploy).
  4. Kiểm tra: GET /api/notify/test.

Cơ chế & Lý do thiết kế

Mục này ghi lại cách hệ thống hoạt động bên dưới và vì sao chọn cách đó, để bạn hiểu rõ và tự đánh giá.

Ba hướng tạo link & lựa chọn

HướngCơ chếTrạng thái
Open API chính thứcGraphQL + chữ ký SHA256 (app_id/secret)❌ Shopee không duyệt cấp quyền cho tài khoản này
Puppeteer (lái Chrome thật)Gọi API nội bộ batchCustomLink trong Chrome đã login❌ Đã gỡ — dính captcha + chặn IP liên tục, nặng nề, mong manh
an_redir (đang dùng)Ghép chuỗi tới endpoint chuyển hướng công khai của Shopee✅ Nhẹ, không captcha/proxy/đăng nhập

Code: src/linkBuilder.js. Các bước:

  1. Nhận originalLink + userId/subIds + affiliateId (từ env/config).
  2. Chuẩn hoá link (resolveToCanonical): nếu là link rút gọn (s.shopee.vn/xxx) thì theo redirect (chỉ đọc header Location, không tải trang) để lấy URL sản phẩm chuẩn /product/<shop>/<item>. Lý do: an_redir chỉ gắn tracking đầy đủ khi origin_link là URL sản phẩm chuẩn; nếu để link rút gọn thì mất tracking.
  3. Ghép sub_id: subId1..subId5 nối bằng dấu - (bỏ đuôi rỗng), subId1 = userId.
  4. Dựng link:
    https://s.shopee.vn/an_redir?origin_link=<url chuẩn>&affiliate_id=<id>&sub_id=<s1-s2-...>
  5. Khi user click → Shopee trả 301 về trang sản phẩm, tự gắn: utm_source=an_<affiliate_id>, utm_content=<sub_id>, utm_medium=affiliates, uls_trackid=... (phiên tracking) → hoa hồng quy về đúng affiliate + user.
✅ Không có bước nào cần Chrome/cookie/captcha/proxy. Server chỉ gọi mạng khi phải resolve link rút gọn; link sản phẩm chuẩn thì thuần ghép chuỗi.

Logic đọc report (/api/report)

Code: src/shopee.js + src/cookieStore.js.

Cách kiểm chứng hệ thống chạy đúng

Tự động (mỗi ngày): hệ thống có sẵn GET /api/selfcheck — chạy 4 phép kiểm:

Phép kiểmXác nhận điều gì
affiliate_idĐã cấu hình affiliate_id
build_linkTạo được link an_redir
link_trackingClick link → 301 + utm_source=an_<id> + utm_content đúng
report_cookieCookie report còn sống (bắt sớm khi hết hạn)
curl -H "x-api-key: <key>" https://shopee-api.apps.neooi.com/api/selfcheck
{ "ok": true, "at": "...", "checks": [ { "name": "affiliate_id", "ok": true, ... }, ... ] }

Thủ công — phép thử quy đơn 100% (nên làm 1 lần):

  1. Tạo link với userId test → click → mua 1 đơn nhỏ → gọi /api/report/by-subid?subIds=<userId> → đơn phải hiện với utm_content chứa userId.
  2. Click: click link từ điện thoại/mạng thật → sau vài giờ xem mục Hiệu suất/Lưu lượng trong affiliate.shopee.vn (click gom theo utm_content).
💡 Bằng chứng kỹ thuật đã có: link an_redir sinh ra cùng bộ param tracking (utm_source=an_<id>, utm_medium=affiliates) y hệt link affiliate chính thống khi resolve. Nhưng phép thử mua đơn test là cách xác nhận quy đơn 100%.

Nguồn tham khảo

⚠️ Minh bạch: cách an_redir dựa trên tài liệu Shopee bản SG + nguồn cộng đồng, và được kiểm chứng thực nghiệm trên endpoint thật của Shopee — không phải spec API chính thức cho VN. Mô hình cashback cũng cần tự đối chiếu Điều khoản Affiliate Shopee (phần hoàn tiền/tự mua/công cụ tự động) trước khi scale.