您已经有自己的网站或应用,并且有一个“订阅新闻通讯”表单?可以通过以下两种方式之一将它接入 Voaaro:
| 从您的服务器 | 从浏览器 | |
|---|---|---|
| 密钥 | 域名的应用密钥(mlk_…),须保密 | 表单的公钥(mlk_pub_…),在页面中可见 |
| 路径 | POST /api/v1/newsletter/subscribe | POST /api/v1/newsletter/public/{public_key}/subscribe |
| 防机器人 | 由您负责(由您的服务器决定) | 蜜罐、工作量证明、按 IP 限制、允许的来源 |
| 响应 | 详细信息(contact_id、状态) | 对任何地址都相同 |
无论哪种方式,订阅都遵循该域名默认表单(或所选表单)的设置:双重确认、订阅者归入的分组、确认邮件的语言和外观。更喜欢现成的页面?默认表单自带托管页面,可在控制台中修改。
从您的服务器
您应用的服务器使用覆盖该域名的应用密钥调用 Voaaro。sending_access 密钥就足够了:已经在发送邮件的应用也可以为其用户办理订阅。个人密钥会收到 401 restricted_api_key。如果密钥覆盖多个域名,请指定 domain(在请求体中或使用 ?domain=);不属于该密钥的域名返回 404。
Node / Bun
const { data, error } = await voaaro.newsletter.subscribe({
email: "ada@example.org",
firstName: "Ada",
topicIds: ["7a1c…"],
consent: { text: "I agree to receive the Acme newsletter.", ip: req.ip, userAgent: req.get("user-agent") },
})
if (data?.status === "pending") console.log("confirmation email sent")Python
r = voaaro.Newsletter.subscribe({
"email": "ada@example.org",
"first_name": "Ada",
"topic_ids": ["7a1c…"],
"consent": {"text": "I agree to receive the Acme newsletter.", "ip": request.remote_addr, "user_agent": request.user_agent.string},
})PHP
$r = $voaaro->newsletter->subscribe([
'email' => 'ada@example.org',
'firstName' => 'Ada',
'topicIds' => ['7a1c…'],
'consent' => ['text' => 'I agree to receive the Acme newsletter.', 'ip' => $_SERVER['REMOTE_ADDR'], 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''],
]);Go
sub, err := client.Newsletter.Subscribe(&voaaro.SubscribeRequest{
Email: "ada@example.org",
FirstName: "Ada",
TopicIds: []string{"7a1c…"},
Consent: &voaaro.SubscriptionConsent{Text: "I agree to receive the Acme newsletter.", Ip: r.RemoteAddr, UserAgent: r.UserAgent()},
})cURL
curl https://mail.example.com/api/v1/newsletter/subscribe \
-H "Authorization: Bearer $VOAARO_API_KEY" -H "Content-Type: application/json" \
-d '{
"email": "ada@example.org",
"first_name": "Ada",
"topic_ids": ["7a1c…"],
"consent": {"text": "I agree to receive the Acme newsletter.", "ip": "203.0.113.7", "user_agent": "Mozilla/5.0 …"}
}'{
"object": "subscription",
"email": "ada@example.org",
"status": "pending",
"contact_id": null,
"form_id": "2b8f4e10-6c3d-4a97-b5e2-19d7c0a4f863",
"double_opt_in": true
}| 字段 | 规则 |
|---|---|
email | 必填 |
first_name、last_name | 最多 100 个字符 |
properties | 已声明属性的值:{ "key": value } |
segment_ids(或 segments) | 订阅者归入的分组,在表单的分组之外额外添加 |
topics 或 topic_ids | 订阅主题:[{ "id", "subscription": "opt_in" | "opt_out" }],或一个 ID 列表(表示已订阅) |
form_id | 要遵循其设置的表单(须为该域名下处于启用状态的表单;已停用:409);否则使用默认表单 |
double_opt_in | 覆盖表单的设置 |
consent | { text, ip, user_agent },保存在订阅记录上,之后保存在联系人上,并附带密钥 ID;默认文字:表单的同意文字 |
domain | 当密钥覆盖多个域名时使用 |
- 双重确认(默认):响应为
"status": "pending",并使用设置中的发件人发出确认邮件(没有发件人时返回422,消息为double_opt_in : …)。联系人只有在点击链接后才会创建,因此此时contact_id为null。 - 未启用双重确认:
"status": "subscribed",立即创建(或重新订阅)联系人。 - 幂等:已订阅的地址保持订阅状态,不会收到新邮件;提供的字段会被更新,分组和订阅主题会被添加。对于该域名的所有表单,一个地址每 24 小时只会收到一封确认邮件(在整个实例中最多 3 封);超出后响应仍为
pending,但不发送邮件。未提及的订阅主题保持不变:API 不会取消任何勾选。 - 与其他
POST请求一样,支持Idempotency-Key(幂等性)。
查询地址的状态
GET /api/v1/newsletter/subscriptions/{email} 会返回某个地址在该域名中的订阅状态,例如用于在用户账户中显示“您已订阅”:
{
"object": "subscription",
"email": "ada@example.org",
"status": "subscribed",
"contact_id": "7c1d9e42-0a3b-4f6e-8d21-5b9f0c3e7a14",
"created_at": "2026-11-12T10:21:44Z",
"unsubscribed_at": null,
"source": "api",
"pending": null,
"topics": [{ "id": "7a1c…", "name": "News", "subscription": "opt_in" }],
"segments": [{ "id": "…", "name": "Website" }]
}status:subscribed、unsubscribed、pending(订阅尚未确认:pending 提供 form_id 和 created_at)或 none(未知地址)。如需退订,请参见从您的应用中退订。
从浏览器
没有服务器时(静态网站、落地页),浏览器可以使用表单的公钥直接调用 Voaaro:公钥为 mlk_pub_ 加 32 个十六进制字符。它不是机密:只能用于订阅该表单,以及凭退订链接管理偏好设置。您可以在控制台中查看公钥(表单的“您的应用”标签页),也可以从 GET /api/v1/forms/{id} 的 public_key 中读取。POST /api/v1/forms/{id}/rotate-key 会更换公钥:旧公钥立即失效。
| 方法 | 路径(/api/v1/newsletter/public/{public_key}/…) | 请求体 | 响应 |
|---|---|---|---|
POST | challenge | { object: "challenge", challenge, bits } | |
POST | subscribe | email、first_name、last_name、properties、topic_ids、consent、website、challenge、nonce | { object: "subscription", status: "pending" | "subscribed" } |
OPTIONS | 全部 | 204,CORS 预检 |
properties:仅限表单中的字段;缺少表单的必填字段时返回422。topic_ids:须为表单提供的订阅主题。consent:如果表单有同意文字,则为true(必须勾选该复选框,否则返回422);保存的文字为表单中的文字,并附带 IP 地址和浏览器信息。
允许的来源(CORS)
请在表单的 allowed_origins 字段中声明您页面的地址(最多 10 个,格式为 https://host[:port];测试时允许使用 http://localhost):
curl -X PATCH https://mail.example.com/api/v1/forms/$FORM_ID \
-H "Authorization: Bearer $VOAARO_API_KEY" -H "Content-Type: application/json" \
-d '{"allowed_origins": ["https://www.example.com", "http://localhost:5173"]}'只有这些来源会收到 Access-Control-Allow-Origin 响应头;其他来源会收到 403 origin_not_allowed。不带 Origin 请求头的请求(服务器调用)可以通过:CORS 只保护浏览器。无论 Content-Type 是什么,请求体都按 JSON 解析:以 text/plain 发送即可避免 OPTIONS 预检。
防机器人
- 蜜罐:一个隐藏的
website字段,真人会将其留空。如果该字段被填写,响应不变,但不会保存任何内容。 - 工作量证明(
require_challenge,默认为 true):每次订阅前,先请求一个挑战(POST …/challenge),然后寻找一个nonce(用十进制数字表示的数,最多 24 位),使SHA-256("<challenge>:<nonce>")以至少bits个零比特开头。每个挑战只能使用一次,并会过期;缺失、错误或已使用时返回400challenge_required。浏览器只需不到一秒即可完成计算,但对于想要批量订阅成千上万个地址的人来说代价很高。各 SDK 提供solveChallenge。 - 限制:每个 IP 地址每小时最多 20 次订阅,同时适用按 IP 计算的公开请求限制(限制):超出则返回
429。 - 无法枚举:对于有效地址,无论它是新地址、已订阅、已退订还是待确认,响应都相同(启用双重确认时为
pending,否则为subscribed)。任何人都无法通过您的表单检测某个地址是否已订阅。
双重确认才是保护您列表的真正手段:被第三方填写的地址只会收到一封确认邮件,如果收件人不点击,就不会有任何后续。
完整示例
一个 HTML 表单加上三十来行 JavaScript,无需任何库:
<form id="newsletter">
<input type="email" name="email" required placeholder="you@example.org" autocomplete="email">
<input type="text" name="first_name" placeholder="First name" autocomplete="given-name">
<!-- Honeypot: invisible, left empty by humans. -->
<input type="text" name="website" tabindex="-1" autocomplete="off" aria-hidden="true"
style="position:absolute;left:-10000px">
<button>Subscribe</button>
<p id="newsletter-message" role="status"></p>
</form>
<script type="module">
const API = "https://mail.example.com/api/v1/newsletter/public/mlk_pub_0123456789abcdef0123456789abcdef"
// POST as text/plain: no CORS preflight.
async function post(path, body = {}) {
const r = await fetch(`${API}/${path}`, { method: "POST", headers: { "Content-Type": "text/plain" }, body: JSON.stringify(body) })
const data = await r.json()
if (!r.ok) throw new Error(data.message)
return data
}
// Proof of work: SHA-256("<challenge>:<nonce>") must start with `bits` zero bits.
async function solveChallenge(challenge, bits) {
const encoder = new TextEncoder()
for (let nonce = 0; ; nonce++) {
const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(`${challenge}:${nonce}`)))
let zeros = 0
for (const byte of hash) {
zeros += byte === 0 ? 8 : Math.clz32(byte) - 24
if (byte !== 0) break
}
if (zeros >= bits) return String(nonce)
}
}
document.getElementById("newsletter").addEventListener("submit", async (event) => {
event.preventDefault()
const form = event.currentTarget
const message = document.getElementById("newsletter-message")
form.querySelector("button").disabled = true
try {
const { challenge, bits } = await post("challenge")
const nonce = await solveChallenge(challenge, bits)
const fields = Object.fromEntries(new FormData(form))
const { status } = await post("subscribe", { ...fields, challenge, nonce })
message.textContent = status === "pending" ? "Almost done: confirm with the link we just emailed you." : "Thanks, you are subscribed."
form.reset()
} catch (e) {
message.textContent = e.message
} finally {
form.querySelector("button").disabled = false
}
})
</script>使用 Node SDK 时(子路径 @deveryidea/voaaro/public 不依赖 Node:它可以在浏览器中运行,使用 fetch 和 crypto.subtle),subscribeWithChallenge 会请求挑战、求解并完成订阅。Python(voaaro.PublicForm(key, base_url=…) 或 client.public_form(key))、PHP(Voaaro::publicForm(key))和 Go(voaaro.NewPublicForm(key))提供相同的类,便于测试;每个 SDK 也单独提供工作量证明函数:solveChallenge、solve_challenge、PublicForm::solveChallenge、voaaro.SolveChallenge。
import { PublicForm } from "@deveryidea/voaaro/public"
const form = new PublicForm("mlk_pub_0123456789abcdef0123456789abcdef", { baseUrl: "https://mail.example.com" })
const { data, error } = await form.subscribeWithChallenge({ email: "ada@example.org", firstName: "Ada" })在终端中求解挑战后,可以发出同样的调用(没有 Origin,因此不进行 CORS 检查):
curl -X POST https://mail.example.com/api/v1/newsletter/public/mlk_pub_0123…/challenge
curl https://mail.example.com/api/v1/newsletter/public/mlk_pub_0123…/subscribe \
-H "Content-Type: application/json" \
-d '{"email": "ada@example.org", "first_name": "Ada", "website": "", "challenge": "v1.18.…", "nonce": "48213"}'默认订阅页面
每个域名都有一个默认表单:它决定通过 API 发起的订阅(未指定 form_id 时)如何处理,同时也是一个可直接分享的托管页面(https://mail.example.com/n/<id>)。
GET /api/v1/newsletter/default-form(如果密钥覆盖多个域名,请添加?domain=)返回该表单,并在首次读取时创建它:is_default: true、双重确认、名字字段、实例的语言。- 它与其他表单一样,可以通过
PATCH /api/v1/forms/{id}(字段)修改,也可以在控制台中修改(新闻通讯 › 订阅表单,“默认订阅页面”)。它无法删除(409):请将其停用("status": "disabled")。
适用于所有表单的外观字段:
| 字段 | 规则 |
|---|---|
image_url | 页首图片:https:// 地址,或以 base64 嵌入的 PNG、JPEG、GIF 或 WebP 图片(data:image/png;base64,…,最大 200 KB);不接受 SVG |
background_color | #rrggbb,默认为 #f6f6f7 |
accent_color | #rrggbb(按钮、链接) |
allowed_origins、require_challenge | 浏览器 API(见上文) |
is_default、public_key | 只读 |
页面不接受您提供的任何 HTML:文字会被转义,每个空行分隔一个段落,颜色和图片都经过校验。确认邮件会沿用强调色、背景色和图片(如果图片是 https:// 地址)。
预览
POST /api/v1/forms/{id}/preview 使用草稿中的字段渲染页面,但不保存任何内容:{ object: "form_preview", html }。page 用于选择要显示的界面:form(默认)、pending(“请查收邮件”)、subscribed、confirm(点击链接之后)。控制台会在隔离的框架中显示预览。
curl https://mail.example.com/api/v1/forms/$FORM_ID/preview \
-H "Authorization: Bearer $VOAARO_API_KEY" -H "Content-Type: application/json" \
-d '{"title": "The Acme letter", "background_color": "#fff8ec", "page": "pending"}'Webhook
无论通过哪种方式订阅,每次订阅都会产生订阅 webhook:联系人订阅时产生 contact.subscribed,双重确认完成时产生 contact.confirmed,并附带 source(api 表示来自您的服务器,public_api 表示来自浏览器,form 表示来自托管页面)。