直接在业务代码里拼 HTTP 请求调用 CaptchaAI 的 in.php / res.php,用不了多久提交、轮询、重试逻辑就会和主业务代码缠在一起。更稳妥的做法是封装成独立的包:本文从零搭建一个符合 Go 习惯的 CaptchaAI 客户端库——context.Context 管生命周期,可替换 http.Client 支持代理,类型化错误值区分能否重试。
这个库要解决三件事:
context.Context统一管理生命周期和取消。- 可替换
http.Client,接代理不用改内部逻辑。 - 类型化错误值区分能不能重试。
常见场景:
- 批量抓取
- CI 集成测试
- 内部工具统一接入
Go 客户端库项目结构
captchaai/
├── client.go # Main client and solve logic
├── errors.go # Error types
├── types.go # Request/response structs
└── client_test.go # Tests
四个文件各管一摊:
client.go——核心提交/轮询逻辑errors.go——错误类型定义types.go——参数结构体client_test.go——单元测试
错误类型设计
// errors.go
package captchaai
import "fmt"
// APIError represents a CaptchaAI API error response.
type APIError struct {
Code string
Message string
}
func (e *APIError) Error() string {
return fmt.Sprintf("captchaai: %s (%s)", e.Message, e.Code)
}
// IsFatal returns true if this error should not be retried.
func (e *APIError) IsFatal() bool {
switch e.Code {
case "ERROR_WRONG_USER_KEY", "ERROR_KEY_DOES_NOT_EXIST",
"ERROR_ZERO_BALANCE", "ERROR_IP_NOT_ALLOWED":
return true
}
return false
}
// TimeoutError indicates the solve exceeded the configured timeout.
type TimeoutError struct {
TaskID string
}
func (e *TimeoutError) Error() string {
return fmt.Sprintf("captchaai: task %s timed out", e.TaskID)
}
设计原则:能不能重试只在
IsFatal()里判断一次,业务代码不用逐个错误码写分支。
常见的坑:
- 忘记查
IsFatal()导致死循环重试 - 把网络 error 和
*APIError混在一起处理
请求参数定义
// types.go
package captchaai
import "time"
// ClientOption configures the CaptchaAI client.
type ClientOption func(*Client)
// WithPollInterval sets the polling interval between result checks.
func WithPollInterval(d time.Duration) ClientOption {
return func(c *Client) { c.pollInterval = d }
}
// WithTimeout sets the maximum time to wait for a solution.
func WithTimeout(d time.Duration) ClientOption {
return func(c *Client) { c.timeout = d }
}
// RecaptchaV2Params holds parameters for reCAPTCHA v2 solving.
type RecaptchaV2Params struct {
SiteKey string
PageURL string
Invisible bool
Cookies string
}
// RecaptchaV3Params holds parameters for reCAPTCHA v3 solving.
type RecaptchaV3Params struct {
SiteKey string
PageURL string
Action string
}
// TurnstileParams holds parameters for Cloudflare Turnstile solving.
type TurnstileParams struct {
SiteKey string
PageURL string
Action string
CData string
}
// ImageParams holds parameters for image/OCR CAPTCHA solving.
type ImageParams struct {
Base64Image string
CaseSensitive bool
MinLength int
MaxLength int
}
type submitResponse struct {
Status int `json:"status"`
Request string `json:"request"`
}
type pollResponse struct {
Status int `json:"status"`
Request string `json:"request"`
}
参数结构体和验证码类型的对应关系:
| 结构体 | 类型 | 必填字段 |
|---|---|---|
| RecaptchaV2Params | reCAPTCHA v2 | SiteKey、PageURL |
| RecaptchaV3Params | reCAPTCHA v3 | SiteKey、PageURL |
| TurnstileParams | Turnstile | SiteKey、PageURL |
| ImageParams | 图片/OCR | Base64Image |
CaptchaAI Go 客户端核心逻辑
// client.go
package captchaai
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
)
const (
submitURL = "https://ocr.captchaai.com/in.php"
resultURL = "https://ocr.captchaai.com/res.php"
defaultPollInterval = 5 * time.Second
defaultTimeout = 180 * time.Second
)
// Client interacts with the CaptchaAI API.
type Client struct {
apiKey string
httpClient *http.Client
pollInterval time.Duration
timeout time.Duration
}
// New creates a CaptchaAI client with the given API key and options.
func New(apiKey string, opts ...ClientOption) *Client {
c := &Client{
apiKey: apiKey,
httpClient: http.DefaultClient,
pollInterval: defaultPollInterval,
timeout: defaultTimeout,
}
for _, opt := range opts {
opt(c)
}
return c
}
// WithHTTPClient sets a custom HTTP client (e.g., for proxy support).
func WithHTTPClient(hc *http.Client) ClientOption {
return func(c *Client) { c.httpClient = hc }
}
func (c *Client) submit(ctx context.Context, params url.Values) (string, error) {
params.Set("key", c.apiKey)
params.Set("json", "1")
req, err := http.NewRequestWithContext(ctx, http.MethodPost, submitURL, nil)
if err != nil {
return "", fmt.Errorf("captchaai: build request: %w", err)
}
req.URL.RawQuery = params.Encode()
resp, err := c.httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("captchaai: submit: %w", err)
}
defer resp.Body.Close()
var result submitResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("captchaai: decode submit response: %w", err)
}
if result.Status != 1 {
return "", &APIError{Code: result.Request, Message: "submit failed"}
}
return result.Request, nil
}
func (c *Client) poll(ctx context.Context, taskID string) (string, error) {
deadline := time.After(c.timeout)
for {
select {
case <-ctx.Done():
return "", ctx.Err()
case <-deadline:
return "", &TimeoutError{TaskID: taskID}
case <-time.After(c.pollInterval):
}
params := url.Values{
"key": {c.apiKey},
"action": {"get"},
"id": {taskID},
"json": {"1"},
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, resultURL+"?"+params.Encode(), nil)
if err != nil {
return "", fmt.Errorf("captchaai: build poll request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
continue // Retry on network error
}
var result pollResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
resp.Body.Close()
continue
}
resp.Body.Close()
if result.Request == "CAPCHA_NOT_READY" {
continue
}
if result.Status == 1 {
return result.Request, nil
}
return "", &APIError{Code: result.Request, Message: "solve failed"}
}
}
// SolveRecaptchaV2 solves a reCAPTCHA v2 challenge.
func (c *Client) SolveRecaptchaV2(ctx context.Context, p RecaptchaV2Params) (string, error) {
params := url.Values{
"method": {"userrecaptcha"},
"googlekey": {p.SiteKey},
"pageurl": {p.PageURL},
}
if p.Invisible {
params.Set("invisible", "1")
}
if p.Cookies != "" {
params.Set("cookies", p.Cookies)
}
taskID, err := c.submit(ctx, params)
if err != nil {
return "", err
}
return c.poll(ctx, taskID)
}
// SolveRecaptchaV3 solves a reCAPTCHA v3 challenge.
func (c *Client) SolveRecaptchaV3(ctx context.Context, p RecaptchaV3Params) (string, error) {
params := url.Values{
"method": {"userrecaptcha"},
"version": {"v3"},
"googlekey": {p.SiteKey},
"pageurl": {p.PageURL},
}
if p.Action != "" {
params.Set("action", p.Action)
}
taskID, err := c.submit(ctx, params)
if err != nil {
return "", err
}
return c.poll(ctx, taskID)
}
// SolveTurnstile solves a Cloudflare Turnstile challenge.
func (c *Client) SolveTurnstile(ctx context.Context, p TurnstileParams) (string, error) {
params := url.Values{
"method": {"turnstile"},
"sitekey": {p.SiteKey},
"pageurl": {p.PageURL},
}
if p.Action != "" {
params.Set("action", p.Action)
}
if p.CData != "" {
params.Set("data", p.CData)
}
taskID, err := c.submit(ctx, params)
if err != nil {
return "", err
}
return c.poll(ctx, taskID)
}
// SolveImage solves an image/text CAPTCHA from base64.
func (c *Client) SolveImage(ctx context.Context, p ImageParams) (string, error) {
params := url.Values{
"method": {"base64"},
"body": {p.Base64Image},
}
if p.CaseSensitive {
params.Set("regsense", "1")
}
if p.MinLength > 0 {
params.Set("min_len", strconv.Itoa(p.MinLength))
}
if p.MaxLength > 0 {
params.Set("max_len", strconv.Itoa(p.MaxLength))
}
taskID, err := c.submit(ctx, params)
if err != nil {
return "", err
}
return c.poll(ctx, taskID)
}
// GetBalance returns the current account balance.
func (c *Client) GetBalance(ctx context.Context) (float64, error) {
params := url.Values{
"key": {c.apiKey},
"action": {"getbalance"},
"json": {"1"},
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, resultURL+"?"+params.Encode(), nil)
if err != nil {
return 0, err
}
resp, err := c.httpClient.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
var result pollResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return 0, err
}
return strconv.ParseFloat(result.Request, 64)
}
submit 提交任务拿 ID,poll 定期查 res.php 直到出结果、超时或 context 取消——外层一旦取消,轮询立刻停下,不留空转。WithHTTPClient 换个带代理的 http.Client,全部请求就走代理。
只是网络不稳定时才需要代理,先排查连通性,别急着加代理层。
实战:查询余额并识别验证码
package main
import (
"context"
"fmt"
"log"
"time"
"your-module/captchaai"
)
func main() {
client := captchaai.New("YOUR_API_KEY",
captchaai.WithTimeout(120*time.Second),
captchaai.WithPollInterval(5*time.Second),
)
ctx := context.Background()
// Check balance
balance, err := client.GetBalance(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Balance: $%.2f\n", balance)
// Solve reCAPTCHA v2
token, err := client.SolveRecaptchaV2(ctx, captchaai.RecaptchaV2Params{
SiteKey: "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
PageURL: "https://staging.example.com/qa-login",
})
if err != nil {
var apiErr *captchaai.APIError
if errors.As(err, &apiErr) && apiErr.IsFatal() {
log.Fatalf("Fatal API error: %s", apiErr.Code)
}
log.Fatal(err)
}
fmt.Printf("Token: %s...\n", token[:40])
// Solve with context timeout
solveCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
turnstileToken, err := client.SolveTurnstile(solveCtx, captchaai.TurnstileParams{
SiteKey: "0x4AAAAAAADnPIDROrmt1Wwj",
PageURL: "https://example.com/checkout",
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Turnstile: %s...\n", turnstileToken[:40])
}
先查余额能提前发现密钥或欠费问题;SolveTurnstile 单独包一层 60 秒超时,不同接口给不同预算更贴近真实业务。
YOUR_API_KEY建议从环境变量读取,不要硬编码进代码仓库。
跑通这套代码大致是:
New()建 clientGetBalance查余额SolveRecaptchaV2拿 token
常见报错与排查
排查前先确认:
- 网络能不能连
ocr.captchaai.com - 余额和 Key 是否有效
| 问题 | 原因 | 处理方式 |
|---|---|---|
context deadline exceeded |
识别耗时超过 context 超时 | 调大 context 超时或客户端 WithTimeout |
captchaai: submit failed (ERROR_ZERO_BALANCE) |
账户余额不足 | 到 CaptchaAI 控制台的余额页面充值 |
| 轮询一直不返回结果 | 网络异常,或接口地址配置错误 | 检查网络连通性;核对 submitURL、resultURL |
errors.As 报编译错误 |
忘记导入 errors 包 |
在 import 里加上 "errors" |
| 自定义 HTTP 客户端没生效 | 忘了传 WithHTTPClient 选项 |
在 New() 里传入该选项 |
常见问题
轮询间隔要设多长比较合适?
默认 5 秒较均衡:太短浪费配额,太长拉长耗时。延迟敏感可缩短到 2 秒,批量任务反而应调大。
go get 拉依赖很慢或提示模块找不到,怎么办?
国内访问 proxy.golang.org 常不稳定,执行 go env -w GOPROXY=https://goproxy.cn,direct 切国内镜像即可。
这套客户端覆盖了 CaptchaAI 支持的哪些验证码类型?
目前实现 reCAPTCHA v2/v3、Turnstile、图片/OCR;hCaptcha、FunCaptcha 目前不支持,GeeTest v4 尚处“即将支持”阶段。
内部工具用 go get 直接拉,还是本地 vendor 更稳?
只在自己项目用,go mod vendor 最省心;对外发布就打语义化版本 tag,让对方用 go get 导入。
为什么用 ClientOption 函数式选项?
加新配置不用改 New() 签名,是 Go 库常见写法。
相关文章
下一步
开始搭建你的 Go CAPTCHA 客户端——先拿到 CaptchaAI API Key。
相关指南: