### Install and Initialize Solver Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/quick-reference.md Install the package using npm and initialize the solver with your API key. ```javascript // Install package // npm install @2captcha/captcha-solver const TwoCaptcha = require("@2captcha/captcha-solver") const solver = new TwoCaptcha.Solver("YOUR_API_KEY") ``` -------------------------------- ### Installation Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/README.md Install the 2Captcha JavaScript library using npm. ```APIDOC ## Installation ```bash npm install @2captcha/captcha-solver ``` ``` -------------------------------- ### Example of Getting Provider Data Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/internal-utilities.md Shows how to use `getProviderData` to fetch and log the API endpoints for the '2captcha' provider. ```javascript const provider = getProviderData('2captcha') console.log(provider.in) // https://2captcha.com/in.php console.log(provider.res) // https://2captcha.com/res.php ``` -------------------------------- ### Proxy Format with Authentication Example Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/configuration.md Shows how to format a proxy string when authentication credentials are required. ```javascript // Proxy with auth proxy: 'user:pass@proxy.example.com:3128' ``` -------------------------------- ### Install 2Captcha JavaScript Library Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/README.md Install the @2captcha/captcha-solver npm package using npm. ```bash npm install @2captcha/captcha-solver ``` -------------------------------- ### Basic Proxy Format Example Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/configuration.md Illustrates the basic format for specifying a proxy without authentication. ```javascript // Basic proxy (no auth) proxy: '192.168.1.1:8080' ``` -------------------------------- ### Captcha Solving Usage Example Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Example of how to use a solver method and access the returned captcha ID and solution data. ```javascript const result = await solver.recaptcha({...}) console.log("Captcha ID:", result.id) console.log("Solution:", result.data) ``` -------------------------------- ### Example Usage of objectToURI Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/internal-utilities.md Shows how to convert a JavaScript object into a URL query string using objectToURI. ```javascript objectToURI({ key: 'abc123', action: 'getbalance', json: 1 }) // Returns: "?key=abc123&action=getbalance&json=1" ``` -------------------------------- ### Example Usage of castBool Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/internal-utilities.md Demonstrates the usage of the castBool utility function with various input types. ```javascript castBool(true) // Returns: 1 castBool(false) // Returns: 0 castBool(1) // Returns: 1 castBool(0) // Returns: 0 ``` -------------------------------- ### Account Registration Workflow with Captcha Solving Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/quick-reference.md This example shows how to handle captcha solving during an account registration process. It includes a check for sufficient balance before attempting to solve the captcha and then submitting the registration form with the solved token. ```javascript async function registerAccount() { const solver = new TwoCaptcha.Solver(process.env.API_KEY) // Check balance first const balance = await solver.balance() if (balance < 1) { throw new Error("Insufficient balance") } // Solve captcha on registration page const captcha = await solver.recaptcha({ pageurl: 'https://example.com/register', googlekey: 'registration_key' }) // Register with token const response = await fetch('https://example.com/register', { method: 'POST', body: JSON.stringify({ email: 'user@example.com', password: 'secure_password', 'g-recaptcha-response': captcha.data }) }) return response.json() } ``` -------------------------------- ### Install 2Captcha Solver with Yarn Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Install the @2captcha/captcha-solver package using Yarn. This is an alternative package manager for adding the library to your project. ```sh yarn add @2captcha/captcha-solver ``` -------------------------------- ### Example Usage of checkCaptchaParams Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/internal-utilities.md Demonstrates how to use checkCaptchaParams to validate parameters for a captcha method, including error handling. ```javascript try { checkCaptchaParams({ pageurl: 'https://example.com', googlekey: 'key123' }, 'userrecaptcha') console.log("Parameters valid") } catch (error) { console.log("Invalid parameters:", error.message) } ``` -------------------------------- ### Example of Renaming Parameters Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/internal-utilities.md Demonstrates how the `renameParams` function transforms common parameter names into their corresponding API names for requests. ```javascript const original = { userId: '123', sessionId: '456', minClicks: 2, maxClicks: 5 } const renamed = renameParams(original) // Returns: // { // s_s_c_user_id: '123', // s_s_c_session_id: '456', // min_clicks: 2, // max_clicks: 5 // } ``` -------------------------------- ### Error Handling Example Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/internal-utilities.md Demonstrates how to catch and log errors thrown by internal utility functions, such as `checkCaptchaParams`, which provide helpful context in their messages. ```javascript try { checkCaptchaParams({}, 'unknown_method') } catch (error) { console.log(error.message) // Error message with helpful context } ``` -------------------------------- ### Example Usage of sleep Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/internal-utilities.md Illustrates the use of the sleep function to introduce a delay in an asynchronous operation. ```javascript await sleep(5000) console.log("5 seconds have passed") ``` -------------------------------- ### Initialize 2Captcha Solver with API Key Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Initialize the TwoCaptcha solver instance with your API key. This is the basic setup required before making any API calls. ```js const TwoCaptcha = require("@2captcha/captcha-solver") const solver = new TwoCaptcha.Solver("") ``` -------------------------------- ### Error Handling Example Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Demonstrates how to catch and handle APIError exceptions thrown by captcha-solving methods, logging the error code and message. ```javascript try { const result = await solver.recaptcha({...}) } catch (error) { console.log("Error code:", error.code) console.log("Error message:", error.message) } ``` -------------------------------- ### TypeScript Configuration with Type Imports Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/configuration.md When using TypeScript, import types for compile-time checking to ensure type safety. This example demonstrates importing Solver and APIError types. ```typescript import { Solver, APIError } from '@2captcha/captcha-solver' const solver: Solver = new Solver("API_KEY") try { const result = await solver.recaptcha({ pageurl: 'https://example.com', googlekey: 'key...' }) } catch (error) { if (error instanceof APIError) { console.log(error.code) } } ``` -------------------------------- ### Web Scraping Workflow with Captcha Solving Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/quick-reference.md This example demonstrates how to integrate captcha solving into a web scraping process. It first solves a captcha and then submits the obtained token as part of a POST request to a target URL. ```javascript const solver = new TwoCaptcha.Solver(process.env.API_KEY) async function scrapeWithCaptcha(url) { try { // Solve captcha const captcha = await solver.recaptcha({ pageurl: url, googlekey: 'extracted_key' }) // Submit form with token const response = await fetch(url, { method: 'POST', body: JSON.stringify({ 'g-recaptcha-response': captcha.data }) }) return response.json() } catch (error) { console.error("Error:", error.message) } } ``` -------------------------------- ### Error Code Checking for Specific Scenarios Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/errors.md Shows how to handle different API error codes within a catch block. This example checks for specific codes like insufficient balance (9), queue full (11), and invalid API key (2), with a fallback for other errors. ```javascript try { const result = await solver.recaptcha({...}) } catch (error) { if (error.code === 9) { console.log("Insufficient balance") // Handle insufficient funds } else if (error.code === 11) { console.log("Queue full, retry later") // Implement backoff } else if (error.code === 2) { console.log("Invalid API key") // Check API key configuration } else { console.log("Other error:", error.message) } } ``` -------------------------------- ### TypeScript Usage with Error Handling Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/quick-reference.md Example of using the 2Captcha solver in TypeScript, including type imports and specific APIError handling. ```typescript import { Solver, APIError } from '@2captcha/captcha-solver' const solver: Solver = new Solver("API_KEY") try { const result = await solver.recaptcha({ pageurl: 'https://example.com', googlekey: 'key' }) console.log(result.data) } catch (error) { if (error instanceof APIError) { console.log("API Error:", error.code, error.message) } } ``` -------------------------------- ### Check Balance Before Submitting Captcha Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/errors.md Before submitting a captcha, check if your account balance is sufficient. This example also shows how to handle invalid or missing API key errors. ```javascript try { const balance = await solver.balance() if (balance < 1.00) { console.log("Insufficient balance") process.exit(1) } } catch (error) { if (error.code === 2 || error.code === 3) { console.log("Invalid or missing API key") process.exit(1) } } ``` -------------------------------- ### Minimal Solver Configuration Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/configuration.md Instantiate the Solver with only your API key for basic functionality. This is the most straightforward way to begin using the library. ```javascript const TwoCaptcha = require("@2captcha/captcha-solver") // Minimal configuration const solver = new TwoCaptcha.Solver("YOUR_API_KEY") ``` -------------------------------- ### Basic Usage - Solver Initialization and reCAPTCHA Solving Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/README.md Demonstrates how to initialize the Solver with an API key and solve a reCAPTCHA challenge. ```APIDOC ## Basic Usage ### Initialize Solver ```javascript const TwoCaptcha = require("@2captcha/captcha-solver") const solver = new TwoCaptcha.Solver("YOUR_API_KEY") ``` ### Solve reCAPTCHA ```javascript // Solve a reCAPTCHA const result = await solver.recaptcha({ pageurl: 'https://example.com', googlekey: 'sitekey_here' }) console.log(result.data) // The token ``` ``` -------------------------------- ### File Structure Overview Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/INDEX.md Illustrates the project's directory structure, highlighting key files and their purposes within the library. ```tree project/ ├── src/ │ ├── index.ts # Main export │ ├── structs/ │ │ ├── 2captcha.ts # Solver class │ │ ├── 2captchaError.ts # Error class │ │ ├── constants/ │ │ │ └── constants.ts # Configuration constants │ │ └── providers/ │ │ └── providers.ts # API endpoint provider │ └── utils/ │ ├── generic.ts # Utility functions │ ├── fetch.ts # HTTP client │ ├── checkCaptchaParams.ts # Parameter validation │ └── renameParams.ts # Parameter name mapping ├── dist/ # Compiled JavaScript └── package.json ``` -------------------------------- ### Get Account Balance Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Retrieves the current balance of your 2Captcha account. ```APIDOC ## Get Account Balance ### Description Use this method to check your current account balance on the 2Captcha service. ### Method Signature ```javascript solver.balance() ``` ### Request Example ```javascript solver.balance() .then((res) => { console.log(res) }) ``` ``` -------------------------------- ### Documentation File Structure Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/README.md Overview of the directory structure for the project's documentation files. ```bash output/ ├── README.md # This file ├── INDEX.md # Navigation guide (417 lines) ├── quick-reference.md # Quick lookup (448 lines) ├── configuration.md # Setup & config (362 lines) ├── types.md # Type definitions (651 lines) ├── errors.md # Error catalog (316 lines) └── api-reference/ ├── solver.md # Main API (1,372 lines) └── internal-utilities.md # Internals (395 lines) ``` -------------------------------- ### Initialize Solver with API Key from Environment Variable Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/configuration.md Read the API key from the TWOCAPTCHA_API_KEY environment variable to initialize the Solver. This promotes secure handling of sensitive credentials. ```javascript const TwoCaptcha = require("@2captcha/captcha-solver") // Read API key from environment const apiKey = process.env.TWOCAPTCHA_API_KEY if (!apiKey) { throw new Error("TWOCAPTCHA_API_KEY environment variable not set") } const solver = new TwoCaptcha.Solver(apiKey) ``` -------------------------------- ### Instantiate Solver Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Create a new Solver instance with your API key. You can optionally specify a custom polling frequency for balance checks. ```javascript const TwoCaptcha = require("@2captcha/captcha-solver") const solver = new TwoCaptcha.Solver("YOUR_API_KEY") // With custom polling interval const customSolver = new TwoCaptcha.Solver("YOUR_API_KEY", 3000) ``` -------------------------------- ### Solver Constructor Configuration Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/README.md Initialize the Solver with your API key, an optional polling frequency, and an option to enable CORS headers. ```javascript new Solver(apikey, pollingFrequency, enableACAO) // apikey (required): Your API key // pollingFrequency (default: 5000): ms between polls // enableACAO (default: true): CORS header ``` -------------------------------- ### Get Account Balance Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Use this method to retrieve your current account balance. Handles promise resolution for the balance. ```javascript solver.balance() .then((res) => { console.log(res) }) ``` -------------------------------- ### Import Solver and APIError (ES Modules) Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/INDEX.md Shows how to import the Solver and APIError classes using ES Modules syntax. An API key is needed to instantiate the solver. ```javascript import { Solver, APIError } from '@2captcha/captcha-solver' const solver = new Solver("API_KEY") ``` -------------------------------- ### Initialize Solver Reading API Key and Polling Interval from .env Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/configuration.md Load API key and polling interval from a .env file using the 'dotenv' package. This allows for easy configuration management in different environments. ```javascript require('dotenv').config() const solver = new TwoCaptcha.Solver( process.env.TWOCAPTCHA_API_KEY, parseInt(process.env.TWOCAPTCHA_POLLING_INTERVAL || "5000") ) ``` -------------------------------- ### Initialize Solver with API Key Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/errors.md Instantiate the Solver class with your 2Captcha API key. Ensure the API key is valid and correctly formatted (32 characters). ```javascript const solver = new Solver("YOUR_ACTUAL_API_KEY_HERE") ``` -------------------------------- ### Get Account Balance Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Retrieve your current account balance. This method returns a promise that resolves to the balance as a number. It may throw an APIError. ```javascript solver.balance() .then((balance) => { console.log("Account balance:", balance); }) .catch((err) => { console.log("Error:", err.message); }) ``` -------------------------------- ### Import Solver and APIError (CommonJS) Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/INDEX.md Demonstrates how to import the Solver and APIError classes using CommonJS module syntax. Requires an API key for solver initialization. ```javascript const TwoCaptcha = require("@2captcha/captcha-solver") const { Solver, APIError } = TwoCaptcha const solver = new Solver("API_KEY") ``` -------------------------------- ### Get Provider API Endpoints Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/internal-utilities.md Retrieves the 'in.php' and 'res.php' endpoint URLs for a given 2Captcha provider. Defaults to '2captcha' if no provider is specified. ```typescript function getProviderData(provider?: string): { name: string in: string res: string } ``` -------------------------------- ### Handle Parameter Validation Errors Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/errors.md Catch errors related to invalid parameters passed to the captcha solving methods. This example specifically checks for error code 23. ```javascript try { const result = await solver.imageCaptcha({ body: base64Image // Missing required image properties }) } catch (error) { if (error.code === 23) { console.log("Invalid parameters:", error.message) // Check required fields are present } } ``` -------------------------------- ### Solver Constructor Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Initializes a new instance of the Solver class. You can configure the API key, polling frequency, and ACAO header setting. ```APIDOC ## Constructor Solver ### Description Initializes a new Solver instance with your API key and optional configuration for polling frequency and ACAO header. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters (Constructor Arguments) - **apikey** (string) - Required - Your API key (32 characters). - **pollingFrequency** (number) - Optional - Interval in milliseconds between requests to the res.php API endpoint. Minimum 5000ms recommended. Defaults to 5000. - **enableACAO** (boolean) - Optional - Enable ACAO header in responses. Defaults to true. ### Example ```javascript const TwoCaptcha = require("@2captcha/captcha-solver") const solver = new TwoCaptcha.Solver("YOUR_API_KEY") // With custom polling interval const customSolver = new TwoCaptcha.Solver("YOUR_API_KEY", 3000) ``` ``` -------------------------------- ### Bounding Box Method Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Use this method to select objects on an image by providing markup instructions and the image. ```APIDOC ## Bounding Box Method ### Description Use Bounding Box Method when you need to select objects on the image. To do this, you need to pass the markup instructions and image for markup. ### Method `solver.boundingBox(params)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **image** (string) - Required - The image for markup, can be a base64 encoded string. * **textinstructions** (string) - Required - Instructions on what to select in the image (e.g., "Circle all the cars in the image."). * **imginstructions** (string) - Optional - Image instructions encoded in base64 format. ### Request Example ```javascript solver.boundingBox({ image: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAR4AAACwCAIAAAB...", textinstructions: "Circle all the cars in the image." }) ``` ### Response #### Success Response Returns coordinates for bounding boxes around detected objects. #### Response Example (See console output in the provided code snippet) ``` -------------------------------- ### Configure Proxy for Captcha Solving Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/configuration.md Proxy settings are applied per-captcha solve call. Ensure the proxy format and type are correctly specified. ```javascript const solver = new TwoCaptcha.Solver("API_KEY") // Proxies are set per-solve call solver.recaptcha({ pageurl: 'https://example.com', googlekey: 'key...', proxy: 'login:password@1.2.3.4:8080', proxytype: 'HTTP' }) ``` -------------------------------- ### Environment Variable for API Key Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/quick-reference.md Securely store your API key in a .env file and load it using dotenv for the solver initialization. ```javascript // Store API key in .env file // TWOCAPTCHA_API_KEY=your_key_here require('dotenv').config() const solver = new TwoCaptcha.Solver(process.env.TWOCAPTCHA_API_KEY) ``` -------------------------------- ### AudioCaptcha Parameters Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/types.md Defines parameters for the audio() method. Requires body and language, with an optional pingback. ```typescript interface paramsAudioCaptcha { body: string lang: string pingback?: string } ``` -------------------------------- ### audio(params) Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Solves audio captchas by recognizing MP3 audio. It requires the base64-encoded audio, language, and optionally a pingback URL. ```APIDOC ## audio(params) ### Description Solves audio captcha (MP3 audio recognition). ### Method POST (assumed, as it's a solving operation) ### Endpoint /solve/audio (assumed) ### Parameters #### Request Body - **body** (string) - Yes - Base64-encoded MP3 audio file (max 1 MB) - **lang** (string) - Yes - Audio language: `en`, `ru`, `de`, `el`, `pt`, `fr` - **pingback** (string) - No - Callback URL ### Request Example ```json { "body": "SUQzBAAAAAAAHFRTU0UAAAA...", "lang": "en" } ``` ### Response #### Success Response (200) - **data** (string) - The solved captcha answer #### Response Example ```json { "data": "[audio answer]" } ``` **Throws:** `APIError` ``` -------------------------------- ### Read Solver Configuration Properties Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/configuration.md Access the current API key and polling frequency settings of the Solver instance. This is useful for debugging or monitoring the solver's state. ```javascript const solver = new TwoCaptcha.Solver("YOUR_KEY", 3000) console.log(solver.apikey) console.log(solver.pollingFrequency) ``` -------------------------------- ### BoundingBox Parameters Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/types.md Defines parameters for the boundingBox() method. Requires an image and either textinstructions or imginstructions. ```typescript interface paramsBoundingBox { image: string textinstructions?: string imginstructions?: string } ``` -------------------------------- ### FunCaptcha Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Solves FunCaptcha (Arkoselabs) and returns a token. Requires the page URL and the public key. ```APIDOC ## FunCaptcha ### Description Solves FunCaptcha (Arkoselabs) and returns a token. Requires the page URL and the public key. ### Method `solver.funCaptcha(options)` ### Parameters #### Request Body Parameters - **pageurl** (string) - Required - The URL of the page where the FunCaptcha is located. - **publickey** (string) - Required - The public key for the FunCaptcha. ### Request Example ```javascript solver.funCaptcha({ pageurl: "https://funcaptcha.com/tile-game-lite-mode/fc/api/nojs/?pkey=804380F4-6844-FFA1-ED4E-5877CA1F1EA4&lang=en", publickey: "804380F4-6844-FFA1-ED4E-5877CA1F1EA4" }) .then((res) => { console.log(res); }) .catch((err) => { console.log(err); }) ``` ### Response #### Success Response - **captchaId** (string) - The ID of the submitted captcha. - **code** (string) - The solution token for the FunCaptcha. ``` -------------------------------- ### Initialize 2Captcha Solver with API Key and Polling Interval Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Initialize the TwoCaptcha solver with a custom polling interval. This controls how frequently the API is checked for results. ```js const apiKey = 'YOUR_API_KEY' const pollingInterval = 10 const solver = new TwoCaptcha.Solver(apiKey, pollingInterval) ``` -------------------------------- ### Solving reCAPTCHA V2 using Proxy Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Demonstrates how to solve reCAPTCHA V2 while specifying proxy details for the request. ```APIDOC ## Solving reCAPTCHA V2 using Proxy ### Description This example shows how to configure and use a proxy when solving reCAPTCHA V2. The proxy details are passed as an argument to the solving method. ### Method Signature ```javascript solver.recaptcha(options) ``` ### Parameters #### Body Parameters - **pageurl** (string) - Required - The URL of the page where the reCAPTCHA is located. - **googlekey** (string) - Required - The site key for the reCAPTCHA. - **proxy** (string) - Required - The type of proxy to use (e.g., 'HTTPS'). - **proxytype** (string) - Required - The proxy address and port in the format 'login:password@host:port'. ### Request Example ```javascript solver.recaptcha({ pageurl: 'https://2captcha.com/demo/recaptcha-v2', googlekey: '6LfD3PIbAAAAAJs_eEHvoOl75_83eXSqpPSRFJ_u', proxy: 'HTTPS', proxytype: 'login:password@123.123.123.123:3128' }) ``` ``` -------------------------------- ### Solve GeeTest Captcha with Fresh Challenge Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/errors.md Demonstrates solving a GeeTest captcha, emphasizing the importance of fetching a fresh challenge value for each solve attempt. Reusing stale challenge values will result in errors. ```javascript // DON'T reuse old challenge const staleChallenge = "..." // From 5 minutes ago // DO fetch fresh challenge each time const freshChallenge = await fetchChallengeFromWebsite() const result = await solver.geetest({ pageurl: '...', gt: '...', challenge: freshChallenge // Fresh value }) ``` -------------------------------- ### Creating Image Captcha Parameters Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/types.md Shows how to create a parameter object for the imageCaptcha method, specifying image data and length constraints. ```typescript const params: paramsImageCaptcha = { body: imageBase64, numeric: 4, min_len: 5, max_len: 5 } const result = await solver.imageCaptcha(params) ``` -------------------------------- ### Prosopo Parameters Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/types.md Defines parameters for the prosopo() method. Requires page URL and site key, with optional proxy and proxy type. ```typescript interface paramsProsopo { pageurl: string sitekey: string proxy?: string proxytype?: string } ``` -------------------------------- ### Basic Error Handling with APIError Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/errors.md Demonstrates how to catch and inspect API errors using a try-catch block. It checks if the error is an instance of APIError and logs its code, message, and original error details. ```javascript try { const result = await solver.recaptcha({ pageurl: 'https://example.com', googlekey: 'invalid_key' }) } catch (error) { if (error instanceof APIError) { console.log("Code:", error.code) console.log("Message:", error.message) console.log("Original:", error.err) } } ``` -------------------------------- ### Default Polling Interval for Interactive Use Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/configuration.md Instantiate the Solver without specifying a polling interval to use the default value, which is suitable for standard interactive applications. ```javascript // For interactive use, keep default (5000) const interactiveSolver = new TwoCaptcha.Solver("KEY") ``` -------------------------------- ### Binance Parameters Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/types.md Defines parameters for the binance() method. Requires page URL, site key, and validate ID, with optional user agent, proxy, and proxy type. ```typescript interface paramsBinance { pageurl: string sitekey: string validateId: string userAgent?: string proxy?: string proxytype?: string } ``` -------------------------------- ### Using CaptchaAnswer Type Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/types.md Illustrates how to type a variable with CaptchaAnswer and access its properties like data and id. ```typescript const answer: CaptchaAnswer = await solver.recaptcha({...}) console.log(answer.data) // Token string console.log(answer.id) // Captcha ID for reporting ``` -------------------------------- ### Change API Key at Runtime Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/configuration.md Update the Solver's API key dynamically after initialization. This allows for changing authentication credentials without re-instantiating the Solver object. ```javascript const solver = new TwoCaptcha.Solver("INITIAL_KEY") // Later, change the key solver.apikey = "NEW_API_KEY" ``` -------------------------------- ### Solve reCAPTCHA V2 with Proxy Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Demonstrates solving a reCAPTCHA V2 challenge while using a specified proxy. Ensure the proxy type and details are correctly formatted. ```javascript solver.recaptcha({ pageurl: 'https://2captcha.com/demo/recaptcha-v2', googlekey: '6LfD3PIbAAAAAJs_eEHvoOl75_83eXSqpPSRFJ_u', proxy: 'HTTPS', proxytype: 'login:password@123.123.123.123:3128' }) ``` -------------------------------- ### fetch() Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/internal-utilities.md A custom wrapper around the fetch API, designed for making HTTP requests within the library. It utilizes `node-fetch` in Node.js environments to provide a consistent fetching mechanism. ```APIDOC ## fetch() ### Description Custom fetch wrapper for HTTP requests. This utility is used internally for all network communications. ### Method ```typescript function fetch(url: string, options?: any): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **url** (string) - Required - The URL to fetch. * **options** (any) - Optional - Fetch options object. ### Returns A Promise that resolves with the Response object. ### Implementation Notes Uses `node-fetch` for Node.js environments. ``` -------------------------------- ### Basic Usage: Solve reCAPTCHA Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/README.md Demonstrates basic usage of the 2Captcha solver to solve a reCAPTCHA. Requires an API key and the target page URL and site key. ```javascript const TwoCaptcha = require("@2captcha/captcha-solver") const solver = new TwoCaptcha.Solver("YOUR_API_KEY") // Solve a reCAPTCHA const result = await solver.recaptcha({ pageurl: 'https://example.com', googlekey: 'sitekey_here' }) console.log(result.data) // The token ``` -------------------------------- ### binance(params) Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Solves Binance captcha. Requires the page URL, sitekey, and validateId. User-Agent and proxy details are optional. ```APIDOC ## binance(params) ### Description Solves Binance captcha. Requires the page URL, sitekey, and validateId. User-Agent and proxy details are optional. ### Method POST ### Endpoint /in.php ### Parameters #### Request Body - **pageurl** (string) - Yes - Full URL of page where you solve captcha - **sitekey** (string) - Yes - Value of `bizId`, `bizType`, or `bizCode` - **validateId** (string) - Yes - Dynamic value of `validateId` or `securityId` - **userAgent** (string) - No - Browser User-Agent (Windows browser recommended) - **proxy** (string) - No - Proxy: `login:password@123.123.123.123:3128` - **proxytype** (string) - No - Proxy type: `HTTP`, `HTTPS`, `SOCKS4`, `SOCKS5` ### Response #### Success Response (200) - **data** (string) - The solution to the captcha - **id** (string) - The captcha ID (useful for reporting good/bad) ### Throws `APIError` ``` -------------------------------- ### vkimage(params) Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Solves VK image captcha. Requires the captcha image as a base64 string and an array of steps. ```APIDOC ## vkimage(params) ### Description Solves VK image captcha. Requires the captcha image as a base64 string and an array of steps. ### Method POST ### Endpoint /in.php ### Parameters #### Request Body - **body** (string) - Yes - Captcha image as base64 string - **steps** (string) - Yes - Array of steps (e.g., `"[5,19,4,3,23,8,...]"`) ### Response #### Success Response (200) - **data** (string) - The solution to the captcha - **id** (string) - The captcha ID (useful for reporting good/bad) ### Throws `APIError` ``` -------------------------------- ### solver.binance Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Solves Binance captcha. Returns a token. Requires page URL, site key, validate ID, user agent, and proxy details. ```APIDOC ## solver.binance ### Description This method can be used to solve Binance captcha. Returns a token. ### Method ```javascript solver.binance ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pageurl** (string) - Required - The URL of the page with the Binance captcha. - **sitekey** (string) - Required - The site key for Binance captcha. - **validateId** (string) - Required - The validation ID for Binance captcha. - **userAgent** (string) - Required - The user agent string. - **proxy** (string) - Required - The proxy details in the format 'login:password@1.2.3.4:8888'. - **proxytype** (string) - Required - The type of proxy (e.g., 'HTTP', 'HTTPS', 'SOCKS'). ``` -------------------------------- ### KeyCaptcha Parameters Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/types.md Defines parameters for the keyCaptcha() method. Requires page URL, user ID, session ID, and web server signatures, with optional proxy details. ```typescript interface paramsKeyCaptcha { pageurl: string userId: string sessionId: string webServerSign: string webServerSign2: string pingback?: string proxy?: string proxytype?: string } ``` -------------------------------- ### Tencent Parameters Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/types.md Defines parameters for the tencent() method. Requires page URL and app ID, with optional pingback, proxy, and proxy type. ```typescript interface paramsTencent { pageurl: string appId: string pingback?: string proxy?: string proxytype?: string } ``` -------------------------------- ### Solver Configuration with Custom Polling Interval Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/configuration.md Configure the Solver to poll for captcha solutions at a custom interval. Note that the minimum recommended polling frequency is 5000ms. ```javascript // Check for solution every 3 seconds (minimum is 5000ms, this is just shown for example) const solver = new TwoCaptcha.Solver("YOUR_API_KEY", 3000) ``` -------------------------------- ### friendlyCaptcha(params) Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Solves Friendly Captcha. Requires the page URL and sitekey, with optional pingback URL and proxy details. ```APIDOC ## friendlyCaptcha(params) ### Description Solves Friendly Captcha. ### Method POST (assumed, as it's a solving operation) ### Endpoint /solve/friendlycaptcha (assumed) ### Parameters #### Request Body - **pageurl** (string) - Yes - Full URL of page with captcha - **sitekey** (string) - Yes - Value of `data-apikey` or `data-sitekey` - **pingback** (string) - No - Callback URL - **proxy** (string) - No - Proxy: `login:password@123.123.123.123:3128` - **proxytype** (string) - No - Proxy type: `HTTP`, `HTTPS`, `SOCKS4`, `SOCKS5` ### Request Example ```json { "pageurl": "https://example.com/signup", "sitekey": "your_friendly_site_key" } ``` ### Response #### Success Response (200) - **data** (string) - The solved captcha answer #### Response Example ```json { "data": "[friendlycaptcha answer]" } ``` **Throws:** `APIError` ``` -------------------------------- ### Batch Processing with Promise.allSettled Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/quick-reference.md Process multiple captcha solving requests in parallel using Promise.allSettled for robust handling of individual successes and failures. ```javascript // Process multiple captchas in parallel const results = await Promise.allSettled([ solver.recaptcha(params1), solver.recaptcha(params2), solver.recaptcha(params3) ]) results.forEach((result, index) => { if (result.status === 'fulfilled') { console.log(`Captcha ${index}: ${result.value.data}`) } else { console.log(`Captcha ${index} failed: ${result.reason.message}`) } }) ``` -------------------------------- ### KeyCaptcha Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md A token-based method to solve KeyCaptcha using provided user and session details. ```APIDOC ## KeyCaptcha ### Description Token-based method to solve KeyCaptcha. ### Method `solver.keyCaptcha(params)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **pageurl** (string) - Required - The URL of the page with the KeyCaptcha. * **userId** (string) - Required - The user ID for KeyCaptcha. * **sessionId** (string) - Required - The session ID for KeyCaptcha. * **webServerSign** (string) - Required - The web server signature for KeyCaptcha. * **webServerSign2** (string) - Required - The second web server signature for KeyCaptcha. ### Request Example ```javascript solver.keyCaptcha({ pageurl: "https://2captcha.com/demo/keycaptcha", userId: '184015', sessionId: '0917788cad24ad3a69813c4fcd556061', webServerSign: '02f7f9669f1269595c4c69bcd4a3c52e', webServerSign2: 'd888700f6f324ec0f32b44c32c50bde1' }) ``` ### Response #### Success Response Returns a token to bypass the KeyCaptcha. #### Response Example (See console output in the provided code snippet) ``` -------------------------------- ### Audio Captcha Solving Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Solves an audio captcha by sending the MP3 audio data and specifying the language. Supported languages are 'en', 'ru', 'de', 'el', 'pt', 'fr'. ```APIDOC ## Audio Captcha Solving ### Description Solves an audio captcha (MP3 format only). Requires the language parameter to be set (e.g., `lang = 'en'`). Supported languages include 'en', 'ru', 'de', 'el', 'pt', 'fr'. ### Method Signature ```javascript solver.audio(options) ``` ### Parameters #### Body Parameters - **body** (string) - Required - The base64 encoded audio data. - **lang** (string) - Required - The language of the audio. Supported values: "en", "ru", "de", "el", "pt", "fr". ### Request Example ```javascript solver.audio({ body: "SUQzBAAAAAAAHFRTU0UAAAA...", lang: "en" }) .then((res) => { console.log(res); }) .catch((err) => { console.log(err); }) ``` ``` -------------------------------- ### boundingBox(params) Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Solves bounding box (object selection) captcha by returning rectangular coordinates around objects. Requires an image and either text or image instructions. ```APIDOC ## boundingBox(params) ### Description Solves bounding box (object selection) captcha by returning rectangular coordinates around objects. Requires an image and either text or image instructions. ### Method POST ### Endpoint /boundingbox ### Parameters #### Request Body - **image** (string) - Required - Base64-encoded image for markup - **textinstructions** (string) - Optional - Text instructions (e.g., "Select cars") - **imginstructions** (string) - Optional - Base64-encoded instruction image Note: Either `textinstructions` or `imginstructions` is required. ### Request Example ```json { "image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...", "textinstructions": "Select cars in the image" } ``` ### Response #### Success Response (200) - **data** (object) - Contains the captcha solution details #### Response Example ```json { "captchaId": "1234567890", "data": { "box_2x": [10, 20, 30, 40], "box_2y": [50, 60, 70, 80] } } ``` ``` -------------------------------- ### VkImage Parameters Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/types.md Defines parameters for the vkimage() method. Requires body and steps. ```typescript interface paramsVkImage { body: string steps: string } ``` -------------------------------- ### Solve CaptchaFox (Proxy Required) Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Use this method to solve CaptchaFox. Requires URL, sitekey, userAgent, proxy, and proxytype. An api_server parameter is optional. ```typescript public async captchaFox(params: paramsCaptchaFox): Promise ``` -------------------------------- ### FriendlyCaptcha Parameters Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/types.md Defines parameters for the friendlyCaptcha() method. Requires page URL and site key, with optional pingback, proxy, and proxy type. ```typescript interface friendlyCaptcha { pageurl: string sitekey: string pingback?: string proxy?: string proxytype?: string } ``` -------------------------------- ### Optimize for Speed in Captcha Solving Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/configuration.md To achieve minimum latency, use a shorter polling interval and solve captchas one at a time. ```javascript // Use shorter polling interval (but not less than recommended) const solver = new TwoCaptcha.Solver("API_KEY", 5000) // Solve one at a time const result = await solver.recaptcha(params) ``` -------------------------------- ### prosopo Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Solves Prosopo captcha. Requires the full URL of the page and the sitekey. Proxy and proxy type are optional but recommended. ```APIDOC ## prosopo ### Description Solves Prosopo captcha. Requires the full URL of the page containing the captcha and the `sitekey`. Proxy and proxy type can be specified. ### Method `public async prosopo(params: paramsProsopo): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **paramsProsopo** (object) - Required - **pageurl** (string) - Yes - Full URL of page with captcha - **sitekey** (string) - Yes - Value of `data-apikey` or `data-sitekey` - **proxy** (string) - No - Proxy: `login:password@123.123.123.123:3128` - **proxytype** (string) - No - Proxy type: `HTTP`, `HTTPS`, `SOCKS4`, `SOCKS5` ### Request Example ```json { "pageurl": "http://example.com/page", "sitekey": "YOUR_SITE_KEY" } ``` ### Response #### Success Response (200) **CaptchaAnswer** (object) - The answer to the captcha. #### Response Example ```json { "captchaId": "1234567890", "code": "CAPTCHA_CODE" } ``` ### Throws `APIError` ``` -------------------------------- ### Solve Captcha with Proxy Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/quick-reference.md Use a proxy server for solving captchas by providing proxy details and type. ```javascript const result = await solver.recaptcha({ pageurl: 'https://example.com', googlekey: 'key', proxy: 'user:pass@proxy.com:8080', proxytype: 'HTTP' }) ``` -------------------------------- ### Solve KeyCaptcha Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Use this method to solve KeyCaptcha. Requires URL, userId, sessionId, webServerSign, and webServerSign2. Optional parameters include pingback, proxy, and proxytype. ```typescript public async keyCaptcha(params: paramsKeyCaptcha): Promise ``` -------------------------------- ### solver.prosopo Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Solves Prosopo captcha. Requires the page URL and site key. ```APIDOC ## solver.prosopo ### Description Use this method to solve Prosopo and obtain a token to bypass the protection. ### Method ```javascript solver.prosopo ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pageurl** (string) - Required - The URL of the page with the Prosopo captcha. - **sitekey** (string) - Required - The site key for Prosopo captcha. ``` -------------------------------- ### Basic Error Handling with Try/Catch Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/quick-reference.md Implement basic error handling for captcha solving operations using a try/catch block. ```javascript try { const result = await solver.recaptcha({...}) } catch (error) { console.log("Error:", error.message) } ``` -------------------------------- ### keyCaptcha Source: https://github.com/2captcha/2captcha-javascript/blob/master/_autodocs/api-reference/solver.md Solves KeyCaptcha. Requires the page URL and specific parameters (`userId`, `sessionId`, `webServerSign`, `webServerSign2`) from the page source. Optional parameters include pingback URL, proxy, and proxy type. ```APIDOC ## keyCaptcha ### Description Solves KeyCaptcha. Requires the URL of the page and specific parameters (`userId`, `sessionId`, `webServerSign`, `webServerSign2`) extracted from the page source. Optional parameters for callback URL, proxy, and proxy type are available. ### Method `public async keyCaptcha(params: paramsKeyCaptcha): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **paramsKeyCaptcha** (object) - Required - **pageurl** (string) - Yes - URL where captcha is located - **userId** (string) - Yes - Value of `s_s_c_user_id` parameter - **sessionId** (string) - Yes - Value of `s_s_c_session_id` parameter - **webServerSign** (string) - Yes - Value of `s_s_c_web_server_sign` parameter - **webServerSign2** (string) - Yes - Value of `s_s_c_web_server_sign2` parameter - **pingback** (string) - No - Callback URL - **proxy** (string) - No - Proxy: `login:password@123.123.123.123:3128` - **proxytype** (string) - No - Proxy type: `HTTP`, `HTTPS`, `SOCKS4`, `SOCKS5` ### Request Example ```json { "pageurl": "http://example.com", "userId": "USER_ID", "sessionId": "SESSION_ID", "webServerSign": "WEB_SERVER_SIGN", "webServerSign2": "WEB_SERVER_SIGN2" } ``` ### Response #### Success Response (200) **CaptchaAnswer** (object) - The answer to the captcha. #### Response Example ```json { "captchaId": "1234567890", "code": "CAPTCHA_CODE" } ``` ### Throws `APIError` ``` -------------------------------- ### Solve FunCaptcha Source: https://github.com/2captcha/2captcha-javascript/blob/master/README.md Solve FunCaptcha (Arkoselabs) by providing the page URL and public key. This method returns a token. ```javascript solver.funCaptcha({ pageurl: "https://funcaptcha.com/tile-game-lite-mode/fc/api/nojs/?pkey=804380F4-6844-FFA1-ED4E-5877CA1F1EA4&lang=en", publickey: "804380F4-6844-FFA1-ED4E-5877CA1F1EA4" }) .then((res) => { console.log(res); }) .catch((err) => { console.log(err); }) ```