SDK Node.js
Thư viện chính thức của CaptchaSonic cho Node.js và TypeScript — hiện đại, dựa trên Promise, hỗ trợ nhiều phương thức truyền tải (gRPC / ConnectRPC / HTTP).
SDK Node.js của CaptchaSonic (captchasonic) là thư viện hiện đại, dựa trên Promise và ưu tiên TypeScript, dùng để giải CAPTCHA ở quy mô lớn. Mọi phương thức đều trả về một Promise, đi kèm đầy đủ định nghĩa kiểu, và chạy trên ba phương thức truyền tải có thể thay thế cho nhau — gRPC gốc (nhanh nhất, chỉ dành cho Node.js), ConnectRPC (chạy được trên Node.js và trình duyệt), và HTTP/JSON thuần. Các lỗi tạm thời được tự động thử lại với thời gian chờ tăng dần theo cấp số nhân.
SDK chạy được trên Node.js ≥ 18 và các trình duyệt hiện đại, tương thích với Express, Fastify, Next.js, React, Vue và Vite.
Cài đặt
npm install captchasonic
# or
yarn add captchasonic
# or
pnpm add captchasonic
Yêu cầu
| Yêu cầu | Ghi chú |
|---|---|
| Node.js | ≥ 18.0.0 (bắt buộc với truyền tải grpc) |
| Định dạng module | ES Module — gói được phát hành với "type": "module" |
| Trình duyệt | Mọi trình duyệt hiện đại có fetch; dùng truyền tải connect hoặc http |
Gói này chỉ phát hành dưới dạng ESM. Trong dự án ESM (có "type": "module" trong package.json, hoặc tệp .mjs), hãy import trực tiếp:
import { CaptchaSonic } from "captchasonic";
Từ tệp CommonJS, hãy tải bằng import() động:
// CommonJS (.cjs / "type": "commonjs")
const { CaptchaSonic } = await import("captchasonic");
TIP
Nếu bạn dùng TypeScript, hãy đặt "module": "NodeNext" (hoặc "ESNext") và "moduleResolution": "NodeNext" trong tsconfig.json để các định nghĩa kiểu đi kèm được phân giải đúng.
Xác thực
Tạo API key trong bảng điều khiển CaptchaSonic và truyền nó làm tham số đầu tiên của constructor:
import { CaptchaSonic } from "captchasonic";
const solver = new CaptchaSonic("YOUR_API_KEY");
Không bao giờ ghi cứng key vào mã nguồn. Hãy đọc key từ biến môi trường:
import { CaptchaSonic } from "captchasonic";
const solver = new CaptchaSonic(process.env.CAPTCHASONIC_API_KEY);
Bắt đầu nhanh
Mỗi loại captcha có một hàm trợ giúp solve* riêng, gửi tác vụ và trả về kết quả. Với tác vụ ảnh không cần bước thăm dò riêng — SDK tự xử lý.
solveRecaptchaV2TokentokenreCAPTCHA v2 (token) — Solve a reCAPTCHA v2 token challenge via browser automation (async — polls until ready).
solveRecaptchaV2Token(…)returnssolution.tokenimport { CaptchaSonic } from "captchasonic";
const solver = new CaptchaSonic(process.env.CAPTCHASONIC_API_KEY);
const result = await solver.solveRecaptchaV2Token({
websiteURL: "https://example.com/login",
websiteKey: "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
});
console.log(result.solution.gRecaptchaResponse);
// 03AGdBq25SxXT... ← drop into the g-recaptcha-response fieldfrom captchasonic import CaptchaSonic
solver = CaptchaSonic("YOUR_API_KEY")
result = solver.solve_recaptcha_v2_token(
website_url="https://example.com/login",
website_key="6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
)
print(result["token"])
# 03AGdBq25SxXT... ← drop this into the g-recaptcha-response fieldTrả về: các phương thức ảnh cho kết quả có đáp án nằm dưới
typedSolution(ví dụtypedSolution.grid.objects, các chỉ số ô được chọn); các phương thức token trả về token trong mapsolution.
TIP
Các phương thức dựa trên token (Turnstile, Cloudflare, reCAPTCHA v2/v3 token, popular-captcha token) gửi một tác vụ tự động hóa trình duyệt và thăm dò nội bộ cho đến khi token sẵn sàng — mặc định tối đa 120 giây.
Các loại CAPTCHA được hỗ trợ
Mọi phương thức ảnh đều nhận một đối tượng tùy chọn có kiểu duy nhất. Ảnh có thể là Uint8Array, Buffer của Node, hoặc đường dẫn tệp dạng chuỗi (đường dẫn tệp chỉ dùng được trên Node.js).
reCAPTCHA v2 (ảnh)
await solver.solveRecaptchaV2({
images: tiles, // typically 9 tiles for a 3×3 grid
question: "traffic lights", // plain text, or a Google class code like "/m/015qff"
});
// → result.typedSolution.grid.objects (number[] — selected tile indices)
PopularCaptcha (ảnh kiểu hCaptcha)
await solver.solvePopularCaptcha({
images: tiles, // 1–64 tiles
question: "Click each image with a cat",
questionType: "objectClassify", // "objectClassify" | "grid" | "objectClick" | "objectDrag"
examples, // optional reference images for objectClick
websiteURL: "https://example.com",
});
// objectClassify/grid → typedSolution.grid.objects
// objectClick → typedSolution.click
// objectDrag → typedSolution.drag
GeeTest
// nine-grid (question + images required)
await solver.solveGeetest({ type: "nine", question: "Select all bicycles", images: tiles });
// click / icon (question + images required)
await solver.solveGeetest({ type: "click", question: "the bear", images: tiles });
// slide puzzle (piece + background)
await solver.solveGeetest({ type: "slide", images: [piece], examples: [background] });
// swap puzzles
await solver.solveGeetest({ type: "match" });
await solver.solveGeetest({ type: "winlinze" });
Trả về: các loại grid/click nằm trong typedSolution.grid.objects (hoặc typedSolution.click); loại slide trả về typedSolution.slide.x.
Các bí danh type được chấp nhận:
| Chuẩn | Bí danh |
|---|---|
| lưới chín ô | "nine", "geetest_nine", "9" |
| click / biểu tượng | "click", "geetest_click", "icon" |
| slide | "slide", "geetest_slide" |
| match | "match", "geetest_match" |
| winlinze | "winlinze", "geetest_winlinze" |
OCR / ảnh sang văn bản
await solver.solveOcr({ images: [img] }); // general OCR
await solver.solveOcr({ images: [img], module: "mtcaptcha", maxLength: 4 });
await solver.solveOcr({ images: imgs, module: "bls", numeric: true, maxLength: 3 });
// → result.typedSolution.text.texts[0]
| Tùy chọn | Kiểu | Ghi chú |
|---|---|---|
module | "common" | "mtcaptcha" | "bls" | "morocco" | Mặc định "common" |
numeric | boolean | Chỉ chữ số (tự động bật với "bls") |
caseSensitive | boolean | Giữ nguyên chữ hoa/thường |
minLength / maxLength | number | Giới hạn độ dài |
TikTok
await solver.solveTikTok({ type: "click", question: "Select the shape", images });
await solver.solveTikTok({ type: "whirl", question: "Rotate to match", images, examples }); // examples required
await solver.solveTikTok({ type: "slide", question: "Slide to fit", images, examples }); // examples required
Trả về: click nằm trong typedSolution.click; whirl/slide trả về typedSolution.slide.x.
type chấp nhận "click"/"tiktok_click", "whirl"/"tiktok_whirl", "slide"/"tiktok_slide".
Binance
await solver.solveBinance({ type: "grid", question: "Select the bicycle", images });
await solver.solveBinance({ type: "slide", images: [puzzle], examples: [background] });
Trả về: grid nằm trong typedSolution.grid.objects; slide trả về typedSolution.slide.x.
type chấp nhận "grid"/"binance_grid" và "slide"/"binance_slide".
AWS WAF
solveAwsWaf nhận các tham số theo vị trí. question có định dạng "type:category:target".
await solver.solveAwsWaf(tiles, "grid:vehicles:cars");
Trả về: các chỉ số ô được chọn trong typedSolution.grid.objects.
Ảnh trượt (cục bộ, không dùng AI)
Phát hiện độ lệch trượt cục bộ bằng phát hiện đường viền. Nhận một ảnh ghép hoặc [background, piece].
const r = await solver.solveSlideImage({ images: ["slide_bg.png", "piece.png"] });
console.log(r.typedSolution?.slide?.x); // pixel offset, e.g. 142
Trả về: độ lệch trượt tính bằng pixel tại typedSolution.slide.x.
Các phương thức token (tự động hóa trình duyệt)
Các phương thức này gửi tác vụ và thăm dò nội bộ cho đến khi nhận được token (tối đa thời gian thăm dò, mặc định 120 giây).
solveTurnstiletokenCloudflare Turnstile — Solve a Cloudflare Turnstile token challenge (async — polls until ready).
solveTurnstile(…)returnssolution.tokenawait solver.solveTurnstile({ websiteURL, websiteKey, proxy }); // proxy optional
await solver.solveRecaptchaV2Token({ websiteURL, websiteKey, proxy }); // proxy optional
await solver.solveRecaptchaV3Token({ websiteURL, websiteKey, proxy }); // proxy optional
await solver.solvePopularCaptchaToken({ websiteURL, websiteKey, proxy, metadata }); // proxy optional
await solver.solveCloudflare({ websiteURL, websiteKey, proxy }); // proxy REQUIREDsolver.solve_turnstile(website_url=..., website_key=..., proxy=...) # proxy optional
solver.solve_recaptcha_v2_token(website_url=..., website_key=..., proxy=...) # proxy optional
solver.solve_recaptcha_v3_token(website_url=..., website_key=..., proxy=...) # proxy optional
solver.solve_popular_captcha_token(website_url=..., website_key=..., proxy=...) # proxy optional
solver.solve_cloudflare(website_url=..., website_key=..., proxy=...) # proxy REQUIREDTrả về: token nằm trong map solution của phản hồi (ví dụ result.solution.token hoặc result.solution.gRecaptchaResponse, tùy loại captcha).
Sử dụng TypeScript
SDK xuất ra các kiểu cho mọi đối tượng tùy chọn và phản hồi. Hãy import chúng bằng import type.
import { CaptchaSonic } from "captchasonic";
import type { SolveGeetestOptions, GetTaskResultResponse } from "captchasonic";
const solver = new CaptchaSonic(process.env.CAPTCHASONIC_API_KEY!);
const opts: SolveGeetestOptions = {
type: "nine",
question: "Select all bicycles",
images: tiles,
};
const result = await solver.solveGeetest(opts);
console.log(result.typedSolution?.grid?.objects);
Các kiểu được xuất
import type {
CaptchaSonicOptions,
ImageInput,
SolvePopularCaptchaOptions,
SolveRecaptchaV2Options,
SolveGeetestOptions,
SolveOcrOptions,
SolveTikTokOptions,
SolveBinanceOptions,
SolveTurnstileOptions,
SolvePopularCaptchaTokenOptions,
SolveRecaptchaV2TokenOptions,
SolveRecaptchaV3TokenOptions,
SolveCloudflareOptions,
SolveSlideImageOptions,
GeetestSubtype,
TikTokSubtype,
BinanceSubtype,
Task,
CreateTaskResponse,
GetTaskResultResponse,
} from "captchasonic";
ImageInput là Uint8Array | Buffer | string.
Hỗ trợ proxy
Các phương thức token / tự động hóa trình duyệt nhận một chuỗi proxy tùy chọn theo dạng http://user:pass@host:port:
await solver.solveTurnstile({
websiteURL: "https://example.com",
websiteKey: "0x4AAAAAAA...",
proxy: "http://user:[email protected]:8080",
});
WARNING
solveCloudflare luôn yêu cầu proxy — trường proxy là bắt buộc với phương thức này. Các phương thức token khác chạy không proxy khi bỏ qua proxy.
Với hCaptcha doanh nghiệp, bạn cũng có thể truyền metadata (rqdata, rqtoken, fingerprint) cho solvePopularCaptchaToken.
Cấu hình
Truyền một đối tượng tùy chọn làm tham số thứ hai của constructor. Chỉ các tùy chọn bên dưới được hỗ trợ.
const solver = new CaptchaSonic("YOUR_API_KEY", {
transport: "connect", // "grpc" (default) | "connect" | "http"
timeout: 180_000, // max poll wait in ms (alias: timeoutMs); per-call default 30000
pollingInterval: 5_000, // polling frequency in ms (default 2000)
baseUrl: "https://api.captchasonic.com", // override endpoint (alias: url)
});
| Tùy chọn | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
transport | "grpc" | "connect" | "http" | "grpc" | Giao thức truyền dữ liệu (xem bảng bên dưới) |
timeout / timeoutMs | number | 30000 mỗi lệnh gọi | Thời gian chờ yêu cầu; timeout cũng giới hạn thời gian chờ thăm dò |
pollingInterval | number | 2000 | Tần suất thăm dò các tác vụ token |
url / baseUrl | string | theo từng phương thức truyền tải | Ghi đè endpoint API |
Phương thức truyền tải
| Phương thức truyền tải | Môi trường | Giao thức |
|---|---|---|
grpc | Chỉ Node.js | gRPC nhị phân qua HTTP/2 — độ trễ thấp nhất, gửi ảnh dưới dạng nhị phân thô |
connect | Node.js và trình duyệt | ConnectRPC qua fetch |
http | Node.js và trình duyệt | REST/JSON thuần qua fetch |
TIP
Trong trình duyệt, hãy dùng connect (khuyến nghị) hoặc http. gRPC gốc chỉ chạy trên Node.js. Với connect/http, ảnh được tự động mã hóa base64 trước khi gửi; với grpc, ảnh được gửi dưới dạng nhị phân thô không tốn thêm chi phí.
Xử lý lỗi
Mọi lỗi ở mức API đều ném ra SonicError, kế thừa từ Error có sẵn. Lỗi này mang một errorId dạng số và đặt name thành tên lỗi tương ứng.
import { CaptchaSonic, SonicError } from "captchasonic";
try {
const result = await solver.solveGeetest({ type: "nine", question: "bicycles", images });
} catch (err) {
if (err instanceof SonicError) {
console.error(err.errorId); // 1–6
console.error(err.name); // e.g. "InvalidApiKeyError"
console.error(err.message);
} else {
throw err; // network / unexpected
}
}
| id | Python exception | Node errorName | Meaning | Action |
|---|---|---|---|---|
0 | SonicError | SonicError | Base class for every SDK error — catches anything below. | Inspect `error.errorId` (Node) / `err.error_id` (Python) and branch. |
1 | InvalidApiKeyError | InvalidApiKeyError | API key is missing, malformed, or revoked. | Verify the key in your dashboard. |
2 | InsufficientBalanceError | InsufficientBalanceError | Account balance can't cover the task. | Add funds. |
3 | DailyLimitExceededError | DailyLimitExceededError | Daily quota exhausted. | Wait for the daily reset or upgrade your plan. |
4 | MinuteLimitExceededError | MinuteLimitExceededError | Per-minute rate limit hit. | Slow down requests / add exponential backoff. |
5 | QuotaExceededError | QuotaExceededError | Plan quota exhausted. | Upgrade your plan. |
6 | PlanExpiredError | PlanExpiredError | Subscription has expired. | Renew your subscription. |
Every concrete row inherits from SonicError — catch it once to handle all SDK failures, or branch on errorId / exception subclass for granular control. Transient gRPC errors are retried automatically with exponential backoff (up to 3 attempts).
TIP
Các lỗi gRPC tạm thời được tự động thử lại với thời gian chờ tăng dần theo cấp số nhân (tối đa 3 lần), nên thường bạn chỉ cần xử lý các trường hợp SonicError ở trên.
Các hàm hỗ trợ tài khoản
const balance = await solver.getBalance(); // → number (USD)
const health = await solver.healthCheck(); // → { healthy: boolean, version: string }
Nếu bạn cần kiểm soát trực tiếp việc gửi và thăm dò, có sẵn các phương thức tác vụ mức thấp:
const created = await solver.createTask(task); // submit a Partial<Task>
const result = await solver.getTaskResult(taskId); // poll for a result
Khắc phục sự cố
require is not defined / Cannot use import statement outside a module — gói này chỉ dùng ESM. Hãy dùng import trong dự án ESM, hoặc await import("captchasonic") từ CommonJS. Xem Cài đặt.
Truyền tải grpc lỗi trong trình duyệt — gRPC gốc chỉ dùng được trên Node.js. Hãy chuyển sang transport: "connect" hoặc transport: "http".
InvalidApiKeyError ở mọi lệnh gọi — xác nhận key được truyền làm tham số đầu tiên của constructor và không vô tình là undefined (ví dụ do thiếu biến môi trường).
Phương thức token bị hết thời gian chờ — tác vụ token thăm dò tối đa timeout mili giây (mặc định 120000). Hãy tăng timeout và kiểm tra websiteURL / websiteKey khớp với trang đích. Với Cloudflare, bắt buộc phải có proxy hợp lệ.
Ảnh đường dẫn tệp không tải được — đường dẫn tệp dạng chuỗi được đọc đồng bộ và chỉ dùng được trên Node.js; trong trình duyệt, hãy truyền Uint8Array thay thế.