reCAPTCHA
How to solve reCAPTCHA v2 in Ruby
Ruby ships everything needed to call GateSolver: Net::HTTP for requests and JSON for parsing. This guide wraps both in a small module and then hands the token to a Selenium session.
Why stay with the standard library
Ruby has many HTTP gems, and any of them can talk to the API. Net::HTTP is still a sensible default for a solver client: it is always installed, it supports TLS and timeouts, and the API only needs JSON POST requests to two endpoints. That keeps the client easy to drop into a Rails app, a Sidekiq worker, a Capybara test suite or a one file script without touching the Gemfile.
The flow is the same in every language. Your code sends the page URL and site key as a task, receives a task id, checks the result every three seconds, and gets back a token that the target site will verify with Google. Ruby only changes how pleasant that is to write.
A small Gate module
The module has one method for the HTTP round trip and one for the solve itself. Errors from the API become a custom exception class, so callers can rescue them separately from network failures such as Net::ReadTimeout.
require 'net/http'
require 'json'
require 'uri'
module Gate
ORIGIN = URI('https://gatesolver.com')
API_KEY = ENV.fetch('GATE_KEY', 'YOUR_API_KEY')
Error = Class.new(StandardError)
def self.post(path, payload)
Net::HTTP.start(ORIGIN.host, ORIGIN.port, use_ssl: true, open_timeout: 10, read_timeout: 30) do |http|
request = Net::HTTP::Post.new(path, 'Content-Type' => 'application/json')
request.body = JSON.generate(payload.merge(clientKey: API_KEY))
parsed = JSON.parse(http.request(request).body)
unless parsed['errorId'].to_i.zero?
raise Error, "#{parsed['errorCode']} #{parsed['errorDescription']}".strip
end
parsed
end
end
def self.recaptcha_v2(page_url, site_key)
task = { type: 'ReCaptchaV2TaskProxyLess', websiteURL: page_url, websiteKey: site_key }
task_id = post('/createTask', task: task).fetch('taskId')
41.times do
sleep 3
outcome = post('/getTaskResult', taskId: task_id) # one status check
case outcome['status']
when 'ready' then return outcome.dig('solution', 'gRecaptchaResponse')
when 'failed' then raise Error, 'task failed; no charge was made'
end
end
raise Error, "task #{task_id} timed out"
end
end
Net::HTTP.start with a block returns the block's value and closes the connection afterwards, which keeps the helper free of cleanup code. Forty one rounds of three seconds add up to just over two minutes, matching the 120 seconds after which an unsolved task is closed and left uncharged.
Keeping the connection open
Opening a new TLS connection for every poll is fine for occasional solves. If you run many of them, hold one Net::HTTP object per thread, call start once, and reuse it for all requests in that thread; the keep_alive_timeout setting controls how long an idle connection is kept. Net::HTTP objects are not safe to share between threads, so do not put a single instance in a constant used by a thread pool.
Using the token with selenium-webdriver
Install the gem with gem install selenium-webdriver. Recent versions find a matching ChromeDriver on their own through Selenium Manager, so a local Chrome is enough to start.
require 'selenium-webdriver'
require_relative 'gate'
form_url = 'https://example.com/feedback'
driver = Selenium::WebDriver.for(:chrome)
begin
driver.navigate.to(form_url)
widget = driver.find_element(css: '.g-recaptcha[data-sitekey]')
token = Gate.recaptcha_v2(form_url, widget.dom_attribute('data-sitekey'))
driver.execute_script(<<~JS, token)
var area = document.getElementById('g-recaptcha-response');
area.value = arguments[0];
var hook = document.querySelector('.g-recaptcha').getAttribute('data-callback');
if (hook && window[hook]) { window[hook](arguments[0]); }
JS
driver.find_element(css: 'form [type="submit"]').click
Selenium::WebDriver::Wait.new(timeout: 15).until { driver.current_url != form_url }
ensure
driver.quit
end
The squiggly heredoc keeps the JavaScript readable and strips the indentation. The token goes in as arguments[0], which avoids building a script string with the token pasted in. The ensure block closes Chrome even if the solve raises.
Capybara and Rails system tests
If the form belongs to your own Rails app, you will usually meet the widget in system tests that run against a staging configuration. Capybara exposes the same capability through page.execute_script, so the injection script above works unchanged; read the key with find('.g-recaptcha')['data-sitekey'] and the URL with current_url. Wrap the solve in a helper such as pass_recaptcha! and call it right before the click that submits the form.
For your own app it is often simpler to configure Google's documented test keys in the test environment. Keep the solver for suites that must run against the real widget configuration, such as smoke tests on a production-like stack.
Posting without a browser
Many forms do not need Chrome at all. Load the page with Net::HTTP, keep the Set-Cookie values, parse the HTML with Nokogiri to read the site key and hidden fields, then post URI.encode_www_form data including g-recaptcha-response. This path is lighter and faster, and it is the better choice for scheduled jobs such as checking that a partner's public enquiry form still accepts submissions.
Retrying in Sidekiq and plain Ruby
Retry only the two free, temporary codes: ERROR_CAPTCHA_UNSOLVABLE and ERROR_SERVICE_UNAVAILABLE. A retry inside a rescue with a counter is the idiomatic way to do it in plain Ruby. In a Sidekiq job, let those errors raise and rely on the job's retry settings, but rescue permanent codes such as ERROR_ZERO_BALANCE and ERROR_KEY_DENIED_ACCESS and stop the job, because no amount of retrying fixes an empty balance or a replaced key.
Watch the rate limit when many workers poll at once: 600 requests per minute per key in total. A pool of a few dozen concurrent solves polling every three seconds stays comfortably inside it, and there is no separate cap on how many tasks are open at the same time.
If the site refuses the token
Check these in order. First, the time between solve and submit: tokens are good for about two minutes and only once. Second, the page URL you sent: it should be the page that shows the widget, not the endpoint the form posts to. Third, the widget type: a badge in the corner instead of a checkbox means invisible reCAPTCHA, which needs isInvisible: true and usually a callback, as covered in the guide to invisible reCAPTCHA. Finally, if the site ties tokens to an IP, switch to ReCaptchaV2Task with the same proxy your session uses.
The full field list is on the reCAPTCHA v2 page, and the Selenium integration guide covers grids and remote browsers.
Common questions
Do I need any gems for the API client?
No. Net::HTTP, JSON and URI come with Ruby. Only the browser part needs the selenium-webdriver gem.
Which Ruby version works with this code?
Ruby 3.0 or newer runs it as written; Hash#dig and squiggly heredocs need 2.3 or later.
Can I use Faraday or HTTParty instead?
Yes. Any client that sends JSON POST requests works; only the helper method changes.
Is Net::HTTP thread safe?
A single Net::HTTP object is not. Create one per thread, or open a short connection per call as the example does.
How do I use this in a Capybara test?
Read the key with find, solve, then run the same injection script through page.execute_script before clicking submit.
Keep reading
- reCAPTCHA v2 solver$0.56 per 1,000 tasks, answers under 9 seconds.
- SeleniumThe reference Selenium setup in Python and Java: explicit waits, reCAPTCHA v2 and Turnstile tokens, callbacks, retries and Grid scaling.
- Solve invisible reCAPTCHA v2Spot the floating badge, send the task with isInvisible set, then hand the token to the page through its callback.
- Site keyThe public value a widget loads with, where it hides in HTML or scripts, and why token tasks require it.