验证码
验证码令牌校验与控件发放。
1. 概览
基础路径:
https://api.infrai.cc/v1/captcha鉴权头:
Authorization: Bearer $INFRAI_API_KEYbash
# Call any /v1/captcha capability over raw HTTP — no SDK to install.
# curl:
curl https://api.infrai.cc/v1/captcha/... \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json"2. 方法 (1)
2.1captcha.verify
POST /v1/captcha/verify
校验来自浏览器的验证码令牌。
参数
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
token | string | 必填 | 验证码控件返回的令牌。≥ 1 chars |
vendor | "hcaptcha" | "recaptcha" | "turnstile" | "infrai" | 可选 | 固定使用某个供应商,而非自动路由。 |
remote_ip | string | 可选 | 用于风险评分的客户端 IP。 |
min_score | number | 可选 | 可接受的最低分(基于分数的供应商)。 |
返回
CaptchaVerifyResult { valid, score?, vendor, hostname?, action? }| 名称 | 类型 | 说明 |
|---|---|---|
success | boolean | 验证码校验是否通过 |
score | number | null | 0=机器人,1=人类(归一化)。0–1 |
hostname | string | null | 验证码被解决的站点主机名 |
action | string | null | 执行的操作(如 created、updated、deleted) |
challenge_ts | string | ISO 8601 时间戳:the captcha challenge was issued(ISO 8601)format: date-time |
vendor | string | 处理此请求的供应商 |
reasons | ("timeout-or-duplicate" | "invalid-input-response" | "invalid-sitekey" | "low-score" | "hostname-mismatch")[] | reasons contributing to the risk score列表 |
示例
一次性前置(每个范例都假定已完成):
bash
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."bash
curl -X POST https://api.infrai.cc/v1/captcha/verify \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"token": "sample"}'python
# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/captcha/verify",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={'token': 'sample'},
)
resp.raise_for_status()
print(resp.json())javascript
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/captcha/verify",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"token": "sample"}),
},
);
console.log(await resp.json());typescript
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/captcha/verify",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"token": "sample"}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);go
// Zero-install REST call — no SDK required (short-term the API is REST-only).
package main
import (
"bytes"
"fmt"
"net/http"
"os"
)
func main() {
body := []byte(`{"token": "sample"}`)
req, _ := http.NewRequest("POST", "https://api.infrai.cc/v1/captcha/verify", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("INFRAI_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
}java
// Zero-install REST call — no SDK required (short-term the API is REST-only).
import java.net.URI;
import java.net.http.*;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.infrai.cc/v1/captcha/verify"))
.header("Authorization", "Bearer " + System.getenv("INFRAI_API_KEY"))
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\"token\": \"sample\"}"))
.build();
HttpResponse<String> resp = HttpClient.newHttpClient()
.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(resp.body());csharp
// Zero-install REST call — no SDK required (short-term the API is REST-only).
using System;
using System.Net.Http;
var client = new HttpClient();
var req = new HttpRequestMessage(new HttpMethod("POST"), "https://api.infrai.cc/v1/captcha/verify");
var key = Environment.GetEnvironmentVariable("INFRAI_API_KEY");
req.Headers.Add("Authorization", "Bearer " + key);
req.Content = new StringContent("{\"token\": \"sample\"}", System.Text.Encoding.UTF8, "application/json");
var resp = await client.SendAsync(req);
Console.WriteLine(await resp.Content.ReadAsStringAsync());php
<?php
// Zero-install REST call — no SDK required (short-term the API is REST-only).
$ch = curl_init("https://api.infrai.cc/v1/captcha/verify");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer " . getenv("INFRAI_API_KEY"),
"Content-Type: application/json",
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"token\": \"sample\"}");
$response = curl_exec($ch);
curl_close($ch);
echo $response;ruby
# Zero-install REST call — no SDK required (short-term the API is REST-only).
require "net/http"
require "uri"
uri = URI("https://api.infrai.cc/v1/captcha/verify")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{ENV['INFRAI_API_KEY']}"
req["Content-Type"] = "application/json"
req.body = '{"token": "sample"}'
res = http.request(req)
puts res.bodyrust
// Zero-install REST call — no SDK required (short-term the API is REST-only). (uses the reqwest + tokio crates)
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::Client::new()
.post("https://api.infrai.cc/v1/captcha/verify")
.header("Authorization", format!("Bearer {}", env::var("INFRAI_API_KEY")?))
.header("Content-Type", "application/json")
.body(r#"{"token": "sample"}"#)
.send()
.await?;
println!("{}", resp.text().await?);
Ok(())
}高级:指定 vendor
默认情况下 infrai 会把每次调用智能路由到最佳可用供应商——无需自己挑选 vendor。作为高级逃生口,本能力支持可选的 vendor 入参以锁定某个供应商。本能力当前所有可用 vendor 可通过该能力 id 对应的 discovery 端点实时获取——参见 discovery API。
GET /v1/discovery/{capability}captcha.verify
3. 全部能力
本模块全部已路由能力——完整的对外 REST 契约。上方方法是带讲解的入门示例,此表是完整参考。
captcha.verifyPOST /v1/captcha/verifyVerify a client-submitted CAPTCHA token against the vendor and return the success result; idempotent.
参数 (10)
| 名称 | 类型 | 必填 | 说明 |
|---|---|---|---|
token | string | 必填 | One-time vendor response token from the client widget.≥ 1 chars |
vendor | string | null | 可选 | Pin to a specific vendor (turnstile/hcaptcha/recaptcha). Default: routed. |
ip | string | null | 可选 | End-user IP for vendor-side risk scoring. Alias: `remoteip`. |
remoteip | string | null | 可选 | Alias of `ip` (module accepts both; `ip = ip or remoteip`). |
action | string | null | 可选 | Action name bound at challenge time; rejected if mismatched (anti cross-form replay). |
expected_hostname | string | null | 可选 | If set, token hostname must match. |
score_threshold | number | null | 可选 | Minimum acceptable score [0,1]; below → fail with low-score reason.0–1 |
mode | "default_vendor" | "verified_account" | 可选 | Routing axis (CaptchaMode); orthogonal to widget_mode.default: "default_vendor" |
sitekey_label | string | 可选 | KeyPool entry name selecting which sitekey/secret to verify against (multi-sitekey accounts).default: "default" |
idempotency_key | string | null | 可选 | Carries one-time-token semantics; duplicate replay → CAPTCHA_IDEMPOTENCY_KEY_CONFLICT. |
4. 完整示例
本模块的生产级端到端范例:先一次性配置,再运行业务流程,尽量覆盖本模块的多数 API。
单文件可运行 Python 程序(仅标准库、无 SDK):拷贝后填入 INFRAI_API_KEY 运行,即可按真实业务流逐步体验本模块核心 API——每一步都真实调用并计费,后续步骤复用前一步返回的真实字段。12 行 helper 就是全部集成代码。
python
#!/usr/bin/env python3
"""Infrai · captcha — runnable real-app example (single file, zero deps).
Copy this file, set your key, run it: every step is a REAL call to
api.infrai.cc, billed at the real (tiny) per-call price, printing the
live JSON response. Get a key at https://infrai.cc/login (Google/
GitHub sign-in grants $2 free credit); add funds at
https://infrai.cc/billing. No SDK — the 12-line helper below is the
entire integration."""
import json
import os
from urllib import error, request
KEY = os.environ.get("INFRAI_API_KEY") or "ifr_..." # <- your key
BASE = "https://api.infrai.cc"
# Same raw HTTPS POST/GET as every per-method example on this page —
# wrapped once for reuse. There is nothing else to it: no SDK.
def infrai(method, path, body=None):
req = request.Request(
BASE + path, method=method,
data=json.dumps(body).encode() if body is not None else None,
headers={"Authorization": f"Bearer {KEY}",
"Content-Type": "application/json"})
try:
with request.urlopen(req, timeout=60) as r:
return json.loads(r.read())
except error.HTTPError as e:
return json.loads(e.read())
def show(label, resp):
print(f"\n== {label} ==")
print(json.dumps(resp, indent=2, ensure_ascii=False))
return resp
# 1) capture token — client widget handoff
r1 = show("capture token", {"note": "Render the CAPTCHA widget in the browser, then copy the one-time token into the verify step below."})
# 2) captcha.verify — POST /v1/captcha/verify · Verify a client-submitted CAPTCHA token against the vendor and return the success result; idempotent.
r2 = show("captcha.verify", infrai("POST", "/v1/captcha/verify", {"token":"<client-captcha-token>","remote_ip":"203.0.113.5"}))
一次性前置(每个范例都假定已完成):
bash
# No SDK to install — every call is a plain HTTPS request.
# Get a project key by signing in at https://infrai.cc/login (Google/GitHub gives
# you $2 free credit; email sign-in starts at $0). On 402 INSUFFICIENT_CREDIT, add
# funds at https://infrai.cc/billing (or POST /v1/account/topup and open the
# returned checkout_url).
export INFRAI_API_KEY="ifr_..."bash
# 1) Auth: every call is a raw HTTPS request to the Infrai gateway carrying
# only your project key. No SDK, no install.
# Get your key: sign in with Google/GitHub at https://infrai.cc/login for a
# project key + $2 free credit (email sign-in starts at $0). On 402
# INSUFFICIENT_CREDIT, add funds at https://infrai.cc/billing (or POST
# /v1/account/topup and open the returned checkout_url).
export INFRAI_API_KEY="ifr_..." # from https://infrai.cc/login
# 2) captcha.verify
curl -X POST https://api.infrai.cc/v1/captcha/verify \
-H "Authorization: Bearer $INFRAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"token": "<client-captcha-token>", "remoteip": "203.0.113.5"}'
python
# 1) Auth: every call is a raw HTTPS request carrying only your project key.
# No SDK to install — just the `requests` library.
import os, requests
BASE = "https://api.infrai.cc"
HEADERS = {
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
"Content-Type": "application/json",
}
# 2) captcha.verify
# Zero-install REST call — no SDK required (short-term the API is REST-only).
import os, requests
resp = requests.post(
"https://api.infrai.cc/v1/captcha/verify",
headers={
"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}",
},
json={'token': '<client-captcha-token>', 'remoteip': '203.0.113.5'},
)
resp.raise_for_status()
print(resp.json())
javascript
// 1) Auth: every call is a raw HTTPS request carrying only your project key.
// No SDK to install — just the built-in fetch().
const BASE = "https://api.infrai.cc";
const HEADERS = {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
};
// 2) captcha.verify
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/captcha/verify",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"token": "<client-captcha-token>", "remoteip": "203.0.113.5"}),
},
);
console.log(await resp.json());
typescript
// 1) Auth: every call is a raw HTTPS request carrying only your project key.
// No SDK to install — just the built-in fetch(), typed.
const BASE = "https://api.infrai.cc";
const HEADERS: Record<string, string> = {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
};
// 2) captcha.verify
// Zero-install REST call — no SDK required (short-term the API is REST-only).
const resp = await fetch(
"https://api.infrai.cc/v1/captcha/verify",
{
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.INFRAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({"token": "<client-captcha-token>", "remoteip": "203.0.113.5"}),
},
);
if (!resp.ok) throw new Error(`infrai ${resp.status}`);
const data: unknown = await resp.json();
console.log(data);