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.
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.
...-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.
[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ĩa | Ví dụ |
|---|---|---|
subId1 | userId — người nhận cashback (truyền qua trường userId) | u12345 |
subId2 | Nguồn / nền tảng | web, app |
subId3 | Nhãn / chiến dịch | cashback |
subId4, subId5 | Tuỳ ý (mã đơn, click id…) | — |
Luồng cashback:
- User bấm "lấy link" → gọi
POST /api/linkkèmuserId→ link gắnsubId1 = userId. - User mua hàng qua link đó.
- Cron định kỳ gọi
GET /api/report/by-subid?subIds=<userId>→ ra đơn + hoa hồng → cộng cashback.
(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)
/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.
/api/conversions ĐÃ quy về VND; /api/report thô thì CHƯA (tự chia 100000).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
}
}
}
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": [ ... ] }
POST /api/link
Tạo affiliate link gắn theo user. Stateless, phản hồi tức thì.
Body (JSON)| Trường | Kiểu | Bắt buộc | Mô tả |
|---|---|---|---|
originalLink | string | ✅ | Link Shopee (sản phẩm hoặc rút gọn s.shopee.vn) |
userId | string | — | Mã user nhận cashback → gắn vào subId1. Chỉ [a-zA-Z0-9], tối đa 40 ký tự. |
subIds | object | — | Ghi đè/bổ sung { subId1..subId5 } (userId thắng subId1). |
affiliateId | string | — | Override affiliate_id (mặc định lấy từ env/config server). |
curl -X POST https://shopee-api.apps.neooi.com/api/link \
-H "x-api-key: <key>" -H "Content-Type: application/json" \
-d '{"originalLink":"https://s.shopee.vn/xxxxx","userId":"u12345"}'
Response thành công
{
"ok": true,
"userId": "u12345",
"subIds": { "subId1": "u12345", "subId2": "web", "subId3": "cashback" },
"shortLink": "https://s.shopee.vn/an_redir?origin_link=...&affiliate_id=...&sub_id=u12345-web-cashback",
"longLink": "https://shopee.vn/product/<shop>/<item>"
}
shortLink là link gửi cho user (click sẽ được tracking). longLink là URL sản phẩm chuẩn đã resolve.
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.
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).
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| Param | Mặc định | Mô tả |
|---|---|---|
days | 7 | Số ngày gần nhất |
page | 1 | Trang |
size | 50 | Số đơ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ể.
| Param | Mặc định | Mô tả |
|---|---|---|
subIds | — | Danh sách SubID cách nhau dấu phẩy (thường là userId) |
days | 7 | Số 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": [ ... ] }
POST /api/report/cookie
Cập nhật cookie đọc report (lưu ở volume, bền qua redeploy). Thường dùng qua giao diện /cookie.html.
curl -X POST https://shopee-api.apps.neooi.com/api/report/cookie \
-H "x-api-key: <key>" -H "Content-Type: application/json" \
-d '{"cookie":"SPC_F=...; SPC_ST=...; csrftoken=...; ..."}'
{ "ok": true, "length": 1234, "updatedAt": "2026-09-30T..." }
GET /api/report/cookie → kiểm tra trạng thái: { ok, configured, length, updatedAt }.
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": "..." }
| HTTP | code | Ý nghĩa & cách xử lý |
|---|---|---|
| 400 | MISSING_LINK | Thiếu originalLink. |
| 400 | INVALID_SUBID | userId/subIds có ký tự không hợp lệ. Chỉ [a-zA-Z0-9]. |
| 400 | MISSING_COOKIE | POST cookie nhưng body rỗng. |
| 401 | — | Sai hoặc thiếu x-api-key. |
| 404 | — | Sai endpoint. |
| 500 | NO_AFFILIATE_ID | Server chưa cấu hình affiliate_id (env SHOPEE_AFFILIATE_ID / config.affiliateId). |
| 502 | SHOPEE_FAIL_2 | Không nhận diện được sản phẩm từ link. Dùng link shopee.vn hợp lệ. |
| 503 | NO_REPORT_COOKIE | Chưa cấu hình cookie report. Vào /cookie.html dán cookie. |
| 500 | INTERNAL_ERROR | Lỗi khác (vd cookie report hết hạn — Shopee trả 90309999). Cập nhật cookie mới. |
Cookie report & tần suất
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- Mở /cookie.html, nhập API key.
- Đăng nhập affiliate.shopee.vn → trang Báo cáo chuyển đổi → F12 → Network → request
report/list→ Request Headers → copy header Cookie. - Dán vào ô Cookie → Lưu → Test.
/cookie.html.| Nhịp | Khoảng lấy | Mục đích |
|---|---|---|
| Mỗi 1–2 giờ | 3–7 ngày | Bắt đơn mới nhanh |
| Mỗi ngày 1 lần | 30–45 ngày | Cậ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://..."
}
- Chat
@BotFather→/newbot→ lấy botToken. - Nhắn 1 tin cho bot, mở
https://api.telegram.org/bot<token>/getUpdates→ lấy chat.id. - Điền vào
config.notify.telegram(production: File Mount config.json trên Dokploy). - 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ướng | Cơ chế | Trạng thái |
|---|---|---|
| Open API chính thức | GraphQL + 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 |
Logic tạo link (/api/link)
Code: src/linkBuilder.js. Các bước:
- Nhận
originalLink+userId/subIds+affiliateId(từ env/config). - Chuẩn hoá link (
resolveToCanonical): nếu là link rút gọn (s.shopee.vn/xxx) thì theo redirect (chỉ đọc headerLocation, 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 đủ khiorigin_linklà URL sản phẩm chuẩn; nếu để link rút gọn thì mất tracking. - Ghép sub_id:
subId1..subId5nối bằng dấu-(bỏ đuôi rỗng),subId1 = userId. - Dựng link:
https://s.shopee.vn/an_redir?origin_link=<url chuẩn>&affiliate_id=<id>&sub_id=<s1-s2-...> - Khi user click → Shopee trả
301về 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.
Logic đọc report (/api/report)
Code: src/shopee.js + src/cookieStore.js.
- Gọi
affiliate.shopee.vn/api/v3/report/listbằng cookie (axios thuần). Lý do dùng cookie: endpoint report không bị kiểm vân tay TLS/captcha như endpoint tạo link, nên chỉ cần cookie hợp lệ là đọc được — không cần trình duyệt. - Cookie lưu ở
/data/report-cookie.json(volume bền), cập nhật qua /cookie.html (dán cookie hoặc nguyên câu cURL — trang tự tách). - sub_id của mỗi đơn nằm ở trường
utm_content(chuỗi nối-);/api/report/by-subidtáchutm_contentđể lọc theo user. - Cookie hết hạn (~1–2 tuần) → Shopee trả
90309999→ server tự cảnh báo (Telegram/webhook) nhắc cập nhật.
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ểm | Xác nhận điều gì |
|---|---|
affiliate_id | Đã cấu hình affiliate_id |
build_link | Tạo được link an_redir |
link_tracking | Click link → 301 + utm_source=an_<id> + utm_content đúng |
report_cookie | Cookie 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, ... }, ... ] }
- Trả 200 nếu tất cả ok, 503 nếu có lỗi (tiện cho uptime monitor).
- Server tự chạy self-check mỗi 24h và gửi cảnh báo Telegram/webhook nếu lỗi (vd cookie hết hạn) — bạn không cần làm gì.
- Muốn chủ động: trỏ UptimeRobot/BetterStack hoặc cron backend vào
/api/selfcheckhằng ngày; coi HTTP 503 là cảnh báo.
Thủ công — phép thử quy đơn 100% (nên làm 1 lần):
- Tạo link với
userIdtest → click → mua 1 đơn nhỏ → gọi/api/report/by-subid?subIds=<userId>→ đơn phải hiện vớiutm_contentchứauserId. - 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).
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
- Shopee Help — Affiliate Short Link Implementation Guide (bản SG, mô tả định dạng an_redir + sub_id): help.shopee.sg/.../171184
- Shopee Affiliate Open API — Tài liệu (cách "chính thức", cần duyệt): affiliate.shopee.vn/open_api/document
- Shopee Affiliate Sub ID — giải thích: miuravisual.com/shopee-affiliate-sub-id
- Affise — Shopee integration (góc nhìn network): help-center.affise.com/.../shopee
- wecantrack — Shopee conversion integration: wecantrack.com/shopee-integration