ReCaptchaV2: solving reCaptcha v2
TIP
Create the task with the createTask method and get the result with the getTaskResult method.
The task type types
that we support:
ReCaptchaV2Task
this task type require your own proxies.ReCaptchaV2EnterpriseTask
this task type require your own proxies.ReCaptchaV2TaskProxyLess
is using the server's built-in proxy.ReCaptchaV2EnterpriseTaskProxyLess
is using the server's built-in proxy.
Create Task
Create a recognition task with the createTask method.
Before creating a task, you can learn the following
If you got invalid response, you can learn the following
Task Object Structure
Properties | Type | Required | Description |
---|---|---|---|
Type | String | Required | ReCaptchaV2Task ReCaptchaV2TaskProxyLess |
websiteURL | String | Required | Web address of the website using hcaptcha, generally it's fixed value. (Ex: https://google.com) |
websiteKey | String | Required | The domain public key, rarely updated. (Ex: b989d9e8-0d14-41sda0-870f-97b5283ba67d) |
proxy | String | Optional | Learn Using proxies |
pageAction | String | Optional | some site in anchor endpoint have sa param ,it's action value |
enterprisePayload | Object | Optional | Enterprise Payload. Learn how to get reCaptcha s-data |
isInvisible | Bool | Optional | if recaptcha don't have pageAction, reload request body content flag have "fi" |
apiDomain | String | Optional | Domain address from which to load reCAPTCHA Enterprise. For example: • http://www.google.com/ • http://www.recaptcha.net/ Don't use a parameter if you don't know why it's needed. |
userAgent | String | Optional | Browser's User-Agent which is used in emulation. It is required that you use a signature of a modern browser, otherwise Google will ask you to "update your browser". |
cookies | Array | Optional | Learn Using Cookies |
Example Request
txt
POST https://api.capsolver.com/createTask
Host: api.capsolver.com
Content-Type: application/json
json
{
"clientKey": "YOUR_API_KEY",
"task": {
"type": "ReCaptchaV2Task",
"websiteURL": "https://www.google.com/recaptcha/api2/demo",
"websiteKey": "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
"enterprisePayload": {
"s": "SOME_ADDITIONAL_TOKEN" //Optional
},
"isInvisible": false,
"pageAction": "submit", // Optional
"apiDomain": "", //Optional
"userAgent": "", //Optional
//Optional
"cookies": [
{
"name": "__Secure-3PSID",
"value": "AIKkIs3ch7YsxxxxYIzRqNZPGm60cdHozgwfUW1o8MF3kRcf8clJscTI6OtCqVpqNF8I88pLBJkUgQ"
},
{
"name": "__Secure-3PAPISID",
"value": "TKS1iVpGxYbxxxk0n2o/AytXQTb6RUALqxSEL"
}
],
"proxy": "ip:port:user:pass" //Optional
}
}
After you submit the task to us, you should receive in the response a 'taskId' if it's successful. Please read errorCode: full list of errors if you didn't receive the task id.
Example Response
json
{
"errorId": 0,
"errorCode": "",
"errorDescription": "",
"taskId": "61138bb6-19fb-11ec-a9c8-0242ac110006"
}
Getting Results
After you have the taskId, you need to submit the taskId to retrieve the solution. Response structure is explained in getTaskResult.
Depending on the system load, you will get the results within the interval of 1s
to 10s
Example Request
json
POST https://api.capsolver.com/getTaskResult
Host: api.capsolver.com
Content-Type: application/json
{
"clientKey": "YOUR_API_KEY",
"taskId": "61138bb6-19fb-11ec-a9c8-0242ac110006"
}
Example Response
json
{
"errorId": 0,
"errorCode": null,
"errorDescription": null,
"solution": {
"userAgent": "xxx", //userAgent
"expireTime": 1671615324290, //expiration of the token
"gRecaptchaResponse": "3AHJ....." //solution token
},
"status": "ready"
}
Use SDK Request
python
#pip install --upgrade capsolver
#export CAPSOLVER_API_KEY='...'
import capsolver
# capsolver.api_key = "..."
solution = capsolver.solve({
"type": "ReCaptchaV2TaskProxyLess",
"websiteURL": "https://www.google.com/recaptcha/api2/demo",
"websiteKey": "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
})
go
package main
import (
"fmt"
capsolver_go "github.com/capsolver/capsolver-go"
"log"
)
func main() {
// first you need to install sdk
//go get github.com/capsolver/capsolver-go
capSolver := capsolver_go.CapSolver{ApiKey: "..."}
solution, err := capSolver.Solve(map[string]any{
"type": "ReCaptchaV2TaskProxyLess",
"websiteURL": "https://www.google.com/recaptcha/api2/demo",
"websiteKey": "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
})
if err != nil {
log.Fatal(err)
return
}
fmt.Println(solution)
}
Sample Code
python
# pip install requests
import requests
import time
# TODO: set your config
api_key = "YOUR_API_KEY" # your api key of capsolver
site_key = "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-" # site key of your target site
site_url = "https://www.google.com/recaptcha/api2/demo" # page url of your target site
def capsolver():
payload = {
"clientKey": api_key,
"task": {
"type": 'ReCaptchaV2TaskProxyLess',
"websiteKey": site_key,
"websiteURL": site_url
}
}
res = requests.post("https://api.capsolver.com/createTask", json=payload)
resp = res.json()
task_id = resp.get("taskId")
if not task_id:
print("Failed to create task:", res.text)
return
print(f"Got taskId: {task_id} / Getting result...")
while True:
time.sleep(3) # delay
payload = {"clientKey": api_key, "taskId": task_id}
res = requests.post("https://api.capsolver.com/getTaskResult", json=payload)
resp = res.json()
status = resp.get("status")
if status == "ready":
return resp.get("solution", {}).get('gRecaptchaResponse')
if status == "failed" or resp.get("errorId"):
print("Solve failed! response:", res.text)
return
token = capsolver()
print(token)
go
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
)
type capSolverResponse struct {
ErrorId int32 `json:"errorId"`
ErrorCode string `json:"errorCode"`
ErrorDescription string `json:"errorDescription"`
TaskId string `json:"taskId"`
Status string `json:"status"`
Solution map[string]any `json:"solution"`
}
func capSolver(ctx context.Context, apiKey string, taskData map[string]any) (*capSolverResponse, error) {
uri := "https://api.capsolver.com/createTask"
res, err := request(ctx, uri, map[string]any{
"clientKey": apiKey,
"task": taskData,
})
if err != nil {
return nil, err
}
if res.ErrorId == 1 {
return nil, errors.New(res.ErrorDescription)
}
uri = "https://api.capsolver.com/getTaskResult"
for {
select {
case <-ctx.Done():
return res, errors.New("solve timeout")
case <-time.After(time.Second):
break
}
res, err = request(ctx, uri, map[string]any{
"clientKey": apiKey,
"taskId": res.TaskId,
})
if err != nil {
return nil, err
}
if res.ErrorId == 1 {
return nil, errors.New(res.ErrorDescription)
}
if res.Status == "ready" {
return res, err
}
}
}
func request(ctx context.Context, uri string, payload interface{}) (*capSolverResponse, error) {
payloadBytes, err := json.Marshal(payload)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "POST", uri, bytes.NewReader(payloadBytes))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
responseData, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
capResponse := &capSolverResponse{}
err = json.Unmarshal(responseData, capResponse)
if err != nil {
return nil, err
}
return capResponse, nil
}
func main() {
apikey := "YOUR_API_KEY"
ctx, cancel := context.WithTimeout(context.Background(), time.Second*120)
defer cancel()
res, err := capSolver(ctx, apikey, map[string]any{
"type": "ReCaptchaV2TaskProxyLess",
"websiteURL": "https://www.google.com/recaptcha/api2/demo",
"websiteKey": "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
})
if err != nil {
panic(err)
}
fmt.Println(res.Solution["gRecaptchaResponse"])
}
javascript
// npm install axios
const axios = require('axios');
const api_key = "YOUR_API_KEY";
const site_key = "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-";
const site_url = "https://www.google.com/recaptcha/api2/demo";
async function capsolver() {
const payload = {
clientKey: api_key,
task: {
type: 'ReCaptchaV2TaskProxyLess',
websiteKey: site_key,
websiteURL: site_url
}
};
try {
const res = await axios.post("https://api.capsolver.com/createTask", payload);
const task_id = res.data.taskId;
if (!task_id) {
console.log("Failed to create task:", res.data);
return;
}
console.log("Got taskId:", task_id);
while (true) {
await new Promise(resolve => setTimeout(resolve, 1000)); // Delay for 1 second
const getResultPayload = {clientKey: api_key, taskId: task_id};
const resp = await axios.post("https://api.capsolver.com/getTaskResult", getResultPayload);
const status = resp.data.status;
if (status === "ready") {
return resp.data.solution.gRecaptchaResponse;
}
if (status === "failed" || resp.data.errorId) {
console.log("Solve failed! response:", resp.data);
return;
}
}
} catch (error) {
console.error("Error:", error);
}
}
capsolver().then(token => {
console.log(token);
});
java
package org.example.capsolver;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class ReCaptchaV2 {
public static String API_KEY = "YOUR_API_KEY";
public static String SITE_KEY = "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-";
public static String SITE_URL = "https://www.google.com/recaptcha/api2/demo";
public static void capsolver() throws IOException, InterruptedException {
JSONObject param = new JSONObject();
Map<String, Object> task = new HashMap<>();
task.put("type", "ReCaptchaV2TaskProxyLess");
task.put("websiteKey", SITE_KEY);
task.put("websiteURL", SITE_URL);
param.put("clientKey", API_KEY);
param.put("task", task);
String taskId = createTask(param);
if (Objects.equals(taskId, "")) {
System.out.println("Failed to create task");
return;
}
System.out.println("Got taskId: "+taskId+" / Getting result...");
while (true){
Thread.sleep(1000);
String token = getTaskResult(taskId);
if (Objects.equals(token, null)) {
continue;
}
System.out.println(token);
break;
}
}
public static String requestPost(String url, JSONObject param) throws IOException {
URL ipapi = new URL(url);
HttpURLConnection c = (HttpURLConnection) ipapi.openConnection();
c.setRequestMethod("POST");
c.setDoOutput(true);
OutputStream os = null;
os = c.getOutputStream();
os.write(param.toString().getBytes("UTF-8"));
c.connect();
BufferedReader reader = new BufferedReader(
new InputStreamReader(c.getInputStream())
);
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{ sb.append(line); }
return sb.toString();
}
public static String createTask(JSONObject param) throws IOException {
String parsedJsonStr = requestPost("https://api.capsolver.com/createTask", param);
JSONObject responseJson = new JSONObject(parsedJsonStr);
return responseJson.get("taskId").toString();
}
public static String getTaskResult(String taskId) throws IOException {
JSONObject param = new JSONObject();
param.put("clientKey", API_KEY);
param.put("taskId", taskId);
String parsedJsonStr = requestPost("https://api.capsolver.com/getTaskResult", param);
JSONObject responseJson = new JSONObject(parsedJsonStr);
String status = responseJson.getString("status");
if (status.equals("ready")) {
JSONObject solution = responseJson.getJSONObject("solution");
return solution.get("gRecaptchaResponse").toString();
}
if (status.equals("failed") || responseJson.getInt("errorId")!=0) {
System.out.println("Solve failed! response: "+parsedJsonStr);
return "error";
}
return null;
}
}