# Turnstile

> Solve a Cloudflare Turnstile widget through your own proxy.

Source: https://docs.peak.fo/docs/tasks/turnstile

Solves a Cloudflare Turnstile widget and returns the token the site expects. The solve runs through your proxy.

## Request [#request]

`POST https://api.peak.fo/solve`

| Field       | Type     | Required | Description                                                                                                      |
| ----------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------- |
| `task_type` | `string` | Yes      | `turnstiletask`                                                                                                  |
| `url`       | `string` | Yes      | The page the widget is on.                                                                                       |
| `sitekey`   | `string` | Yes      | The widget's sitekey. See [Find the sitekey](/docs/find-sitekey).                                                |
| `proxy`     | `string` | Yes      | Your proxy, as `protocol://user:pass@host:port`. Or send it in [proxy parameters](/docs/proxies#proxy-parameters). |
| `action`    | `string` | No       | The widget's `data-action`, if the page sets one.                                                                |
| `cdata`     | `string` | No       | The widget's `data-cdata`, if the page sets one.                                                                 |

## Example [#example]

The Python examples use [requests](https://requests.readthedocs.io) (`pip install requests`). The Go examples use [tls-client](https://github.com/bogdanfinn/tls-client) (`go get github.com/bogdanfinn/tls-client`, Go 1.27+).

```bash tab="cURL" tab-group="language"
curl https://api.peak.fo/solve \
  -H "X-API-Key: pk_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "task_type": "turnstiletask",
    "url": "https://example.com/login",
    "sitekey": "0x4AAAAAAA...",
    "proxy": "http://user:pass@1.2.3.4:8080"
  }'
```

```python tab="Python" tab-group="language"
import requests

API_KEY = "pk_your_api_key"


def solve(task: dict) -> dict:
    """Sends a task to Peak Solutions and returns the response."""
    resp = requests.post(
        "https://api.peak.fo/solve",
        headers={"X-API-Key": API_KEY},
        json=task,
        timeout=120,
    )
    return resp.json()


if __name__ == "__main__":
    response = solve(
        {
            "task_type": "turnstiletask",
            "url": "https://example.com/login",
            "sitekey": "0x4AAAAAAA...",
            "proxy": "http://user:pass@1.2.3.4:8080",
        }
    )
    print(response)
```

```js tab="JavaScript" tab-group="language"
const API_KEY = "pk_your_api_key";

// Sends a task to Peak Solutions and returns the response.
async function solve(task) {
  const resp = await fetch("https://api.peak.fo/solve", {
    method: "POST",
    headers: {
      "X-API-Key": API_KEY,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(task),
  });
  return resp.json();
}

const response = await solve({
  task_type: "turnstiletask",
  url: "https://example.com/login",
  sitekey: "0x4AAAAAAA...",
  proxy: "http://user:pass@1.2.3.4:8080",
});
console.log(response);
```

```go tab="Go" tab-group="language"
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"

	http "github.com/bogdanfinn/fhttp"
	tls_client "github.com/bogdanfinn/tls-client"
	"github.com/bogdanfinn/tls-client/profiles"
)

const apiKey = "pk_your_api_key"

// Response is the body of every Peak Solutions response.
type Response struct {
	Success   bool            `json:"success"`
	Data      json.RawMessage `json:"data,omitempty"`
	Error     string          `json:"error,omitempty"`
	ErrorCode string          `json:"error_code,omitempty"`
	Cost      float64         `json:"cost,omitempty"`
}

// solve sends a task to Peak Solutions and returns the response.
func solve(client tls_client.HttpClient, task map[string]string) (*Response, error) {
	payload, err := json.Marshal(task)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest(http.MethodPost, "https://api.peak.fo/solve", bytes.NewReader(payload))
	if err != nil {
		return nil, err
	}
	req.Header.Set("X-API-Key", apiKey)
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var out Response
	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
		return nil, fmt.Errorf("HTTP %d: %w", resp.StatusCode, err)
	}
	return &out, nil
}

func main() {
	client, err := tls_client.NewHttpClient(tls_client.NewNoopLogger(),
		tls_client.WithTimeoutSeconds(120),
		tls_client.WithClientProfile(profiles.Chrome_152),
	)
	if err != nil {
		log.Fatal(err)
	}

	response, err := solve(client, map[string]string{
		"task_type": "turnstiletask",
		"url":       "https://example.com/login",
		"sitekey":   "0x4AAAAAAA...",
		"proxy":     "http://user:pass@1.2.3.4:8080",
	})
	if err != nil {
		log.Fatal(err)
	}

	out, _ := json.MarshalIndent(response, "", "  ")
	fmt.Println(string(out))
}
```

## Response [#response]

| Field                  | Type     | Description                                                        |
| ---------------------- | -------- | ------------------------------------------------------------------ |
| `data.token`           | `string` | The Turnstile token.                                               |
| `data.secondary_token` | `string` | Only returned when the widget also issues a second token.          |
| `cost`                 | `number` | What the solve was charged, in USD.                                |
| `error`                | `string` | On failure: what went wrong, in words.                             |
| `error_code`           | `string` | On failure: what went wrong, as a stable [code](/docs/api/errors). |

```json tab="Success"
{
  "success": true,
  "data": {
    "token": "0.AgAAAB..."
  },
  "cost": 0.0009
}
```

```json tab="Failure"
{
  "success": false,
  "error": "Challenge was flagged - try using a different proxy with a cleaner IP reputation",
  "error_code": "challenge_flagged"
}
```

## Errors [#errors]

A failed solve returns HTTP `200` with `"success": false`, and is not charged.

| `error_code`        | What to do                                                   |
| ------------------- | ------------------------------------------------------------ |
| `invalid_sitekey`   | Check the sitekey belongs to that page.                      |
| `invalid_action`    | Send the exact `data-action` from the page, or leave it out. |
| `invalid_cdata`     | Send the exact `data-cdata` from the page, or leave it out.  |
| `challenge_flagged` | Retry with a proxy that has a cleaner IP.                    |
| `proxy_error`       | Check the proxy format and that the proxy is reachable.      |
| `timeout`           | Retry, or use a faster proxy.                                |
| `solve_failed`      | Retry, if needed with a different proxy.                     |
| `solver_error`      | Retry.                                                       |

A request missing `sitekey`, `url` or `proxy` is rejected with HTTP `400` and `missing_fields`. For rejections like `insufficient_balance`, see [Error codes](/docs/api/errors).
