Quickstart
Three steps: create a site, run the check on your page, and verify the token on your server.
1. Create a site
In the dashboard, create a site with a name and the hostnames your pages are served from, like shop.example.com or *.example.com. You get two keys:
- the sitekey (
ace_site_…), which is public and goes in your page; - the secret (
ace_secret_…), which stays on your server. It’s shown once, so store it with your other server secrets right away, for example asACE_SECRET.
New sites start in shadow mode, so you can roll out safely: nobody sees a check yet, so log each decision, and don’t refuse anything on it yet.
Note
Real keys only run on pages served over https from a hostname listed on the site.
2. Run the check on your page
Load the client with a script tag and place the check in your form. It runs on its own, and the form is sent with a token in ace-token.
<script src="https://hc.acecaptcha.com/v1/client.js" defer></script><form action="/login" method="post"> <input name="email" type="email" autocomplete="username" required> <input name="password" type="password" autocomplete="current-password" required> <div class="ace-captcha" data-sitekey="ace_site_xxxxxxxxxxxxxxxxxxxxxx" data-action="login" ></div> <button>Sign in</button></form>The check takes no space until it’s needed: in enforce mode, when it isn’t clean, a short visible check appears there. Most visitors never see it. Allow hc.acecaptcha.com in your Content Security Policy if you have one: see CSP.
Developing locally? Start with the test keys: they work on localhost and need no site.
3. Verify on your server
Your backend POSTs the token and your secret to siteverify, once per token, and acts on the decision in the reply. Each sample below gives up after 5 seconds, retries a temporary fault once, and lets you choose per action whether an outage fails open or closed.
// verify.mjs (Node 18+)const SITEVERIFY = 'https://hc.acecaptcha.com/v1/siteverify'/** * Redeems a token. Returns 'allow', 'allow_limited' or 'block'. * failOpen: what this action does when AceCaptcha can't answer. */export async function verifyAce(token, { action, remoteip, failOpen = false } = {}) { const outage = failOpen ? 'allow_limited' : 'block' const body = JSON.stringify({ secret: process.env.ACE_SECRET, response: token, action, remoteip }) for (let attempt = 0; attempt < 2; attempt++) { let reply, data try { reply = await fetch(SITEVERIFY, { method: 'POST', headers: { 'content-type': 'application/json' }, body, signal: AbortSignal.timeout(5000), }) data = await reply.json() } catch { return outage // network failure, 5 s timeout or unreadable reply } if (data['error-codes']?.includes('internal-error')) { if (attempt === 1) return outage const wait = Math.min(Number(reply.headers.get('retry-after')) || 1, 5) await new Promise((resolve) => setTimeout(resolve, wait * 1000)) continue } if (!data.success) return 'block' // missing, invalid, expired or used token if (data.mode === 'shadow') { console.info('acecaptcha shadow', action, data.decision) return 'allow' } return data.decision // act on decision, never on success alone } return outage}// In your route (Express shown):// const decision = await verifyAce(req.body['ace-token'], { action: 'login', remoteip: req.ip })// if (decision === 'block') return res.status(403).send('Please try again.')// if (decision === 'allow_limited') { /* proceed, with tighter limits */ }<?php// verify.php (PHP 8 with the curl extension)const ACE_SITEVERIFY = 'https://hc.acecaptcha.com/v1/siteverify';/** * Redeems a token. Returns 'allow', 'allow_limited' or 'block'. * $failOpen: what this action does when AceCaptcha can't answer. */function ace_verify(string $token, string $action = '', ?string $remoteIp = null, bool $failOpen = false): string{ $outage = $failOpen ? 'allow_limited' : 'block'; $body = json_encode(array_filter([ 'secret' => getenv('ACE_SECRET'), 'response' => $token, 'action' => $action, 'remoteip' => $remoteIp, ], fn ($value) => $value !== null && $value !== '')); for ($attempt = 0; $attempt < 2; $attempt++) { $retryAfter = 1; $ch = curl_init(ACE_SITEVERIFY); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $body, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 5, CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$retryAfter) { if (stripos($line, 'retry-after:') === 0) { $retryAfter = max(1, (int) trim(substr($line, 12))); } return strlen($line); }, ]); $raw = curl_exec($ch); $data = is_string($raw) ? json_decode($raw, true) : null; if (!is_array($data)) { return $outage; // network failure, 5 s timeout or unreadable reply } if (in_array('internal-error', $data['error-codes'] ?? [], true)) { if ($attempt === 1) { return $outage; } sleep(min($retryAfter, 5)); continue; } if (empty($data['success'])) { return 'block'; // missing, invalid, expired or used token } if (($data['mode'] ?? '') === 'shadow') { error_log("acecaptcha shadow {$action} {$data['decision']}"); return 'allow'; } return $data['decision']; // act on decision, never on success alone } return $outage;}// In your form handler:// $decision = ace_verify($_POST['ace-token'] ?? '', 'login', $_SERVER['REMOTE_ADDR']);// if ($decision === 'block') { http_response_code(403); exit('Please try again.'); }// if ($decision === 'allow_limited') { /* proceed, with tighter limits */ }# verify.py (Python 3.9+, pip install requests)import osimport timeimport requestsSITEVERIFY = "https://hc.acecaptcha.com/v1/siteverify"def verify_ace(token, action=None, remoteip=None, fail_open=False): """Redeems a token. Returns 'allow', 'allow_limited' or 'block'. fail_open: what this action does when AceCaptcha can't answer. """ outage = "allow_limited" if fail_open else "block" payload = {"secret": os.environ["ACE_SECRET"], "response": token} if action: payload["action"] = action if remoteip: payload["remoteip"] = remoteip for attempt in range(2): try: reply = requests.post(SITEVERIFY, json=payload, timeout=5) data = reply.json() except (requests.RequestException, ValueError): return outage # network failure, 5 s timeout or unreadable reply if "internal-error" in data.get("error-codes", []): if attempt == 1: return outage time.sleep(_retry_after(reply)) continue if not data.get("success"): return "block" # missing, invalid, expired or used token if data.get("mode") == "shadow": print("acecaptcha shadow", action, data.get("decision")) return "allow" return data["decision"] # act on decision, never on success alone return outagedef _retry_after(reply): try: return min(max(int(reply.headers.get("Retry-After", "1")), 1), 5) except ValueError: return 1# In your view (Flask shown):# decision = verify_ace(request.form.get("ace-token", ""), "login", request.remote_addr)# if decision == "block": abort(403)# if decision == "allow_limited": ... # proceed, with tighter limits// verify.go (Go 1.21+)package aceimport ( "bytes" "encoding/json" "log" "net/http" "os" "slices" "strconv" "time")const siteverifyURL = "https://hc.acecaptcha.com/v1/siteverify"var client = &http.Client{Timeout: 5 * time.Second}type verifyRequest struct { Secret string `json:"secret"` Response string `json:"response"` Action string `json:"action,omitempty"` RemoteIP string `json:"remoteip,omitempty"`}type verifyReply struct { Success bool `json:"success"` ErrorCodes []string `json:"error-codes"` Decision string `json:"decision"` Mode string `json:"mode"`}// Verify redeems a token and returns "allow", "allow_limited" or "block".// failOpen is what this action does when AceCaptcha can't answer.func Verify(token, action, remoteIP string, failOpen bool) string { outage := "block" if failOpen { outage = "allow_limited" } body, _ := json.Marshal(verifyRequest{os.Getenv("ACE_SECRET"), token, action, remoteIP}) for attempt := 0; attempt < 2; attempt++ { res, err := client.Post(siteverifyURL, "application/json", bytes.NewReader(body)) if err != nil { return outage // network failure or 5 s timeout } var reply verifyReply err = json.NewDecoder(res.Body).Decode(&reply) res.Body.Close() if err != nil { return outage // unreadable reply } if slices.Contains(reply.ErrorCodes, "internal-error") { if attempt == 1 { return outage } wait, err := strconv.Atoi(res.Header.Get("Retry-After")) if err != nil || wait < 1 { wait = 1 } time.Sleep(time.Duration(min(wait, 5)) * time.Second) continue } if !reply.Success { return "block" // missing, invalid, expired or used token } if reply.Mode == "shadow" { log.Printf("acecaptcha shadow %s %s", action, reply.Decision) return "allow" } return reply.Decision // act on decision, never on success alone } return outage}// In your handler:// ip, _, _ := net.SplitHostPort(r.RemoteAddr)// switch ace.Verify(r.FormValue("ace-token"), "login", ip, false) {// case "block":// http.Error(w, "Please try again.", http.StatusForbidden)// return// case "allow_limited":// // proceed, with tighter limits// }Important
success is not a verdict
success: true only means the token is genuine, unexpired and unused. Act on decision: proceed on allow, proceed with tighter limits on allow_limited, refuse on block.
Next steps
- Watch the decisions in your logs and in the dashboard’s usage stats. When you’re ready, switch the site to enforce mode.
- Use a different action per form (
login,signup,checkout) and send it to siteverify too. - No form, or a single-page app? See the client from JavaScript and single-page apps.