Skip to content

Ruby guide

Solve captchas from Ruby with one function

A small module on Net::HTTP and JSON creates a task, polls for the result and returns the text or token. No gems to install, works in plain scripts, Rails apps and background jobs.

  • Ruby 3.0+
  • Net::HTTP
  • Standard library only
  • No gems

Setup

Before you start

  • Ruby 3.0 or newer
  • Standard library only: net/http and json
  • A bypass.so API key (create one) with a positive balance

Install

terminal
ruby -v
mkdir bypass-demo && cd bypass-demo

Store your key

The examples read your key from the BYPASS_API_KEY environment variable, so it never lands in source control.

Shell
export BYPASS_API_KEY="your-api-key"

Check that the key works: curl -H "Authorization: Bearer $BYPASS_API_KEY" https://bypass.so/balance returns your balance.

Step 1

Add the helper

Save this file next to your code. It wraps the whole task lifecycle in one call, Bypass.solve(type, params), so the rest of your project never deals with polling.

  • createTask: sends your key, the task type and its fields as one flat JSON object.
  • Fast path: if the answer is already ready, it returns at once.
  • Polling: otherwise it checks /getTaskResult/{taskId} every two seconds until the result is ready or the timeout runs out.
  • Errors: any reply with a non-zero errorId, including a failed task, becomes an error carrying the errorCode, so you can branch on it.
  • taskId: kept with the solution, so you can report a wrong answer later.
bypass.rb
require "json"
require "net/http"
require "uri"

module Bypass
  API_URL = "https://bypass.so"

  # Raised for every API reply with a non-zero errorId.
  class Error < StandardError
    attr_reader :code, :task_id

    def initialize(code, description = "", task_id = nil)
      super("#{code}: #{description}")
      @code = code
      @task_id = task_id
    end
  end

  NETWORK_ERRORS = [SocketError, Timeout::Error, SystemCallError, OpenSSL::SSL::SSLError, EOFError].freeze

  module_function

  def key
    ENV.fetch("BYPASS_API_KEY", "")
  end

  # Creates a task and polls every poll_every seconds until it is ready.
  # Returns the solution hash plus "taskId".
  def solve(type, params, timeout: 120, poll_every: 2)
    client_key = key
    raise Error.new("ERROR_KEY_INVALID", "set the BYPASS_API_KEY environment variable") if client_key.empty?

    data = call(:post, "/createTask", body: { clientKey: client_key, type: type }.merge(params))
    task_id = data["taskId"]
    deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
    poll = "/getTaskResult/#{URI.encode_www_form_component(task_id)}?clientKey=#{URI.encode_www_form_component(client_key)}"

    until data["status"] == "ready"
      raise Error.new("ERROR_CAPTCHA_UNSOLVABLE", "task failed", task_id) if data["status"] == "failed"
      if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
        raise Error.new("CLIENT_TIMEOUT", "task #{task_id} was not ready after #{timeout}s", task_id)
      end

      sleep poll_every
      data = call(:get, poll)
    end
    (data["solution"] || {}).merge("taskId" => task_id)
  end

  # The token for widget types, or the text for recognition types.
  def answer(solution)
    solution["gRecaptchaResponse"] || solution["token"] || solution["text"]
  end

  def balance
    call(:get, "/balance", bearer: true)
  end

  def report_bad(task_id)
    call(:post, "/reportBad?task_id=#{URI.encode_www_form_component(task_id)}", bearer: true)
  end

  def call(method, path, body: nil, bearer: false)
    uri = URI(API_URL + path)
    req = method == :post ? Net::HTTP::Post.new(uri) : Net::HTTP::Get.new(uri)
    req["Content-Type"] = "application/json" if method == :post
    req.body = body ? JSON.generate(body) : "" if method == :post
    req["Authorization"] = "Bearer #{key}" if bearer

    res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30) do |http|
      http.request(req)
    end
    data = begin
      JSON.parse(res.body.to_s)
    rescue JSON::ParserError
      nil
    end
    raise Error.new("HTTP_ERROR", "HTTP #{res.code} without a JSON body") unless data.is_a?(Hash)
    if data["errorId"].to_i != 0
      raise Error.new(data["errorCode"] || "ERROR_UNKNOWN", data["errorDescription"].to_s, data["taskId"])
    end

    data
  rescue *NETWORK_ERRORS => e
    raise Error.new("HTTP_ERROR", e.message)
  end
end

Good to know

Pass task fields as a hash in braces, for example Bypass.solve("MathCaptchaTask", { captchaText: "2+2" }). Without the braces Ruby reads them as keyword arguments.

Project layout used below:

files
bypass-demo/
  bypass.rb         the helper (step 1)
  solve_math.rb     your script (step 2)

Step 2

Solve any supported type

Every task type uses the same call. Only the type name and its fields change. Pick a tab to see a complete, runnable file, then run it with ruby solve_math.rb (rename to match the tab). Tabs marked soon are ready for launch day, but those types are not live yet.

solve_math.rb
require_relative "bypass"

solution = Bypass.solve("MathCaptchaTask", { captchaText: "12 + 30 = ?" })
puts solution["text"]
run it
ruby solve_math.rb

reCAPTCHA v3 and hCaptcha are coming soon

RecaptchaV3Task and HCaptchaTask are not live yet. Until launch, createTask returns ERROR_TASK_NOT_SUPPORTED and nothing is charged. Get notified when they ship.

Token types and your form

For reCAPTCHA, Turnstile and (once live) hCaptcha the token goes into the same form field the widget would fill: g-recaptcha-response, h-captcha-response or cf-turnstile-response. Send the exact URL of the page that shows the widget as websiteURL.

Step 3

Handle errors and retries

Some failures are worth a second try and some are not. A missing balance or a wrong key will fail again, so stop and fix it. An unsolvable task, a timeout or a network hiccup is worth one or two more attempts with a short pause. Bypass::Error carries the API code in e.code, and network errors are wrapped as HTTP_ERROR. Ruby’s retry keyword reruns the block for the codes worth another try.

retry.rb
require_relative "bypass"

RETRYABLE = %w[ERROR_CAPTCHA_UNSOLVABLE ERROR_INTERNAL HTTP_ERROR CLIENT_TIMEOUT].freeze

def solve_with_retry(type, params, attempts: 3)
  attempt = 0
  begin
    attempt += 1
    Bypass.solve(type, params)
  rescue Bypass::Error => e
    raise if !RETRYABLE.include?(e.code) || attempt >= attempts

    warn "attempt #{attempt}: #{e.code}, retrying"
    sleep 2 * attempt
    retry
  end
end

puts solve_with_retry("MathCaptchaTask", { captchaText: "12 + 30 = ?" })["text"]

Failed tasks cost nothing

The task price is held when you create a task and released if it fails. You are only charged when the result is ready.

Step 4

Check your balance and flag wrong answers

GET /balance and POST /reportBad use your key as a Bearer token. Report a task only when the target site actually rejected its answer. The refund is applied once per task, and the task is closed afterwards.

account.rb
require_relative "bypass"

def flag_wrong_answer(solution)
  result = Bypass.report_bad(solution["taskId"])
  puts "refunded units: #{result['refunded']} balance now: #{result['balanceUsd']}"
end

info = Bypass.balance
puts format("balance: $%.2f", info["balanceUsd"])

Scale

Solve many tasks in parallel

Each task is independent, so throughput grows with concurrency. Eight threads pull file names from a closed Queue. Each solve spends most of its time waiting on the network, so threads work well here despite the global interpreter lock. Start with a limit of 8 and adjust while you watch error rates and spend.

batch.rb
require_relative "bypass"

files = Dir.glob("captchas/*.png").sort
queue = Queue.new
files.each { |path| queue << path }
queue.close

workers = Array.new(8) do # at most 8 tasks in flight
  Thread.new do
    while (path = queue.pop)
      image_base64 = [File.binread(path)].pack("m0") # strict Base64
      begin
        text = Bypass.solve("ImageToTextTask", { imageBase64: image_base64 })["text"]
        puts "#{File.basename(path)}: #{text}"
      rescue Bypass::Error => e
        puts "#{File.basename(path)} failed: #{e.code}"
      end
    end
  end
end
workers.each(&:join)

Reference

Task type reference

What each type expects and returns. Prices are per 1,000 solved tasks; larger top-ups add bonus credit (see pricing).

Task type reference
Task typeMathCaptchaTaskYou sendcaptchaTextYou gettextPrice / 1k$0.35
Task typeImageToTextTaskYou sendimageBase64You gettextPrice / 1k$0.28
Task typeAudioCaptchaTaskYou sendaudioBase64You gettextPrice / 1k$0.35
Task typeRecaptchaV2TaskYou sendwebsiteURLwebsiteKeyYou getgRecaptchaResponse and token, plus tokenFieldPrice / 1k$0.56
Task typeTurnstileTaskYou sendwebsiteURLwebsiteKeyYou gettoken, plus tokenFieldPrice / 1k$0.84
Task typeRecaptchaV3TaskComing soonYou sendwebsiteURLwebsiteKeyactionYou getgRecaptchaResponse and token, plus tokenFieldPrice / 1kAt launch
Task typeHCaptchaTaskComing soonYou sendwebsiteURLwebsiteKeyYou gettoken, plus tokenFieldPrice / 1kAt launch

Errors

Troubleshooting

Errors and fixes
ErrorERROR_KEY_INVALIDSourceHTTP 403What it meansThe key is missing, mistyped or revoked.How to fix itCheck that BYPASS_API_KEY is set in the same shell that runs your code, with no quotes or spaces around it.
ErrorERROR_INSUFFICIENT_CREDITSSourceHTTP 402What it meansYour balance cannot cover the task price.How to fix itTop up from the dashboard. Nothing was charged for this request.
ErrorERROR_TASK_NOT_SUPPORTEDSourceHTTP 200What it meansThe type string is unknown, or the type is still coming soon (reCAPTCHA v3, hCaptcha).How to fix itCopy the exact name, for example TurnstileTask. Names are case-sensitive. Nothing is charged.
ErrorERROR_BAD_REQUESTSourceHTTP 400What it meansThe body is not valid JSON, or a field has the wrong type.How to fix itSend Content-Type: application/json and string values for clientKey, type and the task fields.
ErrorERROR_CAPTCHA_UNSOLVABLESourceHTTP 200What it meansThis task could not be completed.How to fix itYou are not charged. Check the image, sitekey and page URL, then submit a new task.
ErrorERROR_NOT_FOUNDSourceHTTP 404What it meansThe taskId is unknown or belongs to another key.How to fix itPoll with the taskId returned by your own createTask call, using the same key.
ErrorERROR_INTERNALSourceHTTP 500What it meansSomething went wrong on our side.How to fix itRetry after a short pause. The helper’s retry wrapper does this for you.
ErrorHelper timeoutSourceyour codeWhat it meansNo result inside your timeout.How to fix itToken types usually need several seconds. Keep at least 60–120 s and retry with a new task.
ErrorHTTP_ERRORSourceyour codeWhat it meansA proxy or network layer answered without JSON.How to fix itRetry with backoff. If it persists, check that your code calls https://bypass.so.

Every error body has the same shape: {"errorId":1,"errorCode":"…","errorDescription":"…"}. Full list in the API reference.

Production

Best practices

  • Keep the key out of code

    Read it from an environment variable or your secret store. Never commit it or ship it to a web page.

  • Solve right before submit

    Tokens are short-lived. Fill the form first, then request the token and submit at once.

  • Cap your concurrency

    Start with 5–10 parallel tasks and raise it while you watch error rates and spend.

  • Log every taskId

    It is the only thing you need to debug a result or report a wrong answer.

  • Match the page exactly

    Send the URL where the widget renders and the sitekey from that page, not from a different form.

  • Report wrong answers

    If a site rejects a solved result, call reportBad with its taskId. The price returns to your balance once.

FAQ

Questions

No. The API is two HTTPS endpoints that take and return JSON. The helper on this page is a single file that you own, can read in a few minutes and can change freely.

Math, image and audio tasks often finish while the createTask request is still open. The response then already has "status": "ready" and a solution, so the helper returns without polling. Token types always come back as processing first.

Every two seconds is a good default. Polling faster does not make a task finish sooner. Keep the overall timeout at 60 to 120 seconds for token types.

No. You pay only when a task comes back ready. If a site rejects a solved answer, call reportBad with its taskId and the price returns to your balance once. A reported task is closed, so submit a new one to try again.

Yes. Put bypass.rb in lib/ and require it. A solve can wait for several seconds, so run it in a background job rather than inside a web request.

Policy

Responsible use

Use it where you are allowed to

Automate pages you own, test environments you run, or sites whose terms permit automated access. Do not use bypass.so for fraud, account takeover, spam, scalping, evading bans or collecting personal data without a lawful basis. Keep request rates reasonable and stop when a site asks you to. Our acceptable use policy applies to every key, and keys used for abuse are closed.

Keep going

Next steps