00一分钟读懂与全景架构Overview & Classic Architecture
用户在手机微信里对「小微」说一句需求,小微就在微信云端隔离环境里并行打开多个小程序、公众号或网页替用户办事。本协议只解决一件事:用户放心放权、运行时管好票据生命周期、开发者随时能核验身份并在关键点叫停交给真人。 A user tells their WeChat Personal Agent ("XiaoWei") what they need. In WeChat's isolated Cloud Runtime, XiaoWei operates multiple Mini Programs, Official Account pages, and websites on their behalf. This protocol guarantees three things: clean user consent, strict ticket lifecycle control, and verifiable identity with merchant-controlled human gates.
一次代办的五个步骤Five steps of a delegated task
前置标准授权Standard pre-auth
小微访问目标小程序前弹出标准授权框,默认打包授权登录、隐私协议与 getSetting 权限,并选定有效期。
Before opening an app, a standard sheet grants login, privacy, and getSetting scopes in one tap with a chosen lifetime.
云端隔离运行Isolated cloud run
小微在微信托管的云运行时打开多个小程序或网页,按用户与应用独立隔离,票据与凭证不进入大模型。
XiaoWei opens Mini Programs or pages in isolated per-user, per-app runtimes; tokens never enter the LLM.
登录取码/门禁Login or HITL gate
页面调用 wx.agentLogin():有票据直接返码;无票据/失效报错并引导补授;命中商家按钮门禁则请用户点确认。
The page calls wx.agentLogin(): valid ticket returns a code; missing/expired errors and triggers re-auth; merchant HITL gate asks the user to click.
后端单次换码One-step exchange
后端将 code 与出站层附加的 WeChat-Agent-Proof 交给微信,一步确认用户 openid、权限范围与票据状态。
Your backend forwards the code and WeChat-Agent-Proof to WeChat, verifying openid, scopes, and grant status in one call.
受限会话与回收Scoped & revocable
开发者签发独立受限会话;支付等高危操作永不自动执行;票据到期或用户一键撤销即刻作废。
You issue a separate scoped session; payments always require the user; expiry or revocation invalidates immediately.
三方各自负责什么Who is responsible for what
- 掌控Controls
- 主账号、前置打包授权与有效期(总是/本次/限时)Master account, pre-auth bundle & grant TTL
- 永不交出Never shares
- 手机登录态、
session_key、支付密码Phone sessions,session_key, payment PINs - 随时可以Can always
- 响应商家按钮确认、接管操作或撤销授权Confirm merchant gates, take over, or revoke
- 负责Provides
- 标准化授权框、票据失效检测、隔离环境与出站证明Consent UI, ticket expiry checks, isolation & proofs
- 强制执行Enforces
- 开发者声明的
data-wxap-hitl按钮门禁与手势核验Developerdata-wxap-hitlgates & gesture checks - 默认不信任Treats as untrusted
- 大模型输出与网页脚本;撤销/到期毫秒级失效LLM output & page JS; instant invalidation on revoke/expiry
- 分级接入Tiered adoption
- 从 L1 零代码开关到 L4 代办登录,按业务风险自选L1 switch-on to L4 delegated login by risk appetite
- 自主门禁Own HITL policy
- 可要求在登录或敏感操作前必须用户点击(每次或记一次)Can require user click before login/writes (always or remember)
- 不需要Doesn't need to
- 手写签名算法或管理密钥(微信生态内零加密代码)Implement crypto or manage keys inside WeChat
你需要做什么:四个接入级别What you need to do: four integration levels
接入级别决定开发者为 Agent 开放多少业务深度;任何级别都可以叠加用户介入(HITL)能力,且绝不改变普通用户原有体验。 Integration levels control how deeply you open your service to Agents. Human-in-the-loop (HITL) controls combine cleanly with every level and never alter regular users' flows.
| 接入级别Level | 你要做的事What you do | 工作量Effort | 你获得的能力What you get |
|---|---|---|---|
| L1开关即用Switch-on | 在 MP 管理后台打开开关Turn on the switch in MP Admin | 0 行代码No code | Agent 在隔离环境中浏览页面;登录与敏感操作自动交给用户Agents browse in isolation; logins and sensitive actions go to the user |
| L2前端适配 + HITLFrontend + HITL | 读取 Agent 状态;给敏感/登录按钮加 data-wxap-hitl 与策略属性Read Agent status; mark login/sensitive controls with data-wxap-hitl | 几行属性/前端A few attributes | 声明必须真人操作的区域,配置「总是点击」或「确认一次后总是授权」Enforce user-only regions with "always click" or "confirm once, remember" |
| L3后端识别Backend-verified | 登记接口,后端核验 WeChat-Agent-ProofRegister endpoints; verify WeChat-Agent-Proof | 一个后端调用One backend call | 后端可信识别 Agent 流量与票据状态,实施独立风控限频Reliably verify Agent traffic and ticket status for separate risk rules |
| L4代办登录Delegated login | 接入 wx.agentLogin(可组合 HITL 登录按钮)与换码接口Adopt wx.agentLogin (optionally gated by HITL button) + exchange API | 一个登录接口One login endpoint | 建立受限 Agent 会话,在用户与商家双重授权下代办查单、填单等Scoped Agent session for orders and drafts under dual user + merchant control |
01双向授权机制Bidirectional Authorization Model
Agent 访问商家服务不是单向放行,而是用户授权与商家确认策略的双向握手:用户通过标准前置授权框决定「小微能进哪家小程序、用哪些基础权限、授权多久」;开发者通过分级接入与 HITL 属性决定「即便用户已放权,哪些关键动作(含登录)仍需用户本人点一次确认」。 Agent access is a two-way handshake between user consent and merchant policy. The user decides which apps XiaoWei may enter, which bundled permissions it gets, and for how long; the developer decides which actions — including login itself — still require an explicit human click.
wx.agentLogin 的三条标准执行路径。有效权限始终取「用户票据 ∩ 商家策略 ∩ 平台安全底线」的交集。Left: standardized user pre-authorization and ticket lifecycle. Right: the three standard execution paths of wx.agentLogin. Effective authority is always the intersection of user ticket, merchant policy, and platform safety baseline.1.1 用户侧:标准化前置授权框(默认打包授权)1.1 User side: standardized pre-authorization sheet
当小微首次需要访问某个小程序或公众号网页,或该应用的授权票据已失效时,微信客户端在打开目标应用前弹出统一规格的原生授权框。为避免任务途中被一连串零散弹窗打断,授权框采用默认全选打包授权,用户一键确认即可流畅代办,也可按需展开取消单项。 Before XiaoWei opens an app for the first time — or after a previous ticket expires — WeChat shows a standardized native consent sheet. To avoid a storm of mid-task popups, it uses default bundled consent that the user can approve in one tap or fine-tune per item.
1.2 Runtime 对「无授权 / 票据失效」的完整处理1.2 How Runtime handles missing or expired user grants
由于用户可以选择「仅本次会话」或「限时有效」,也可能在手机设置里主动收回权限,云运行时必须把授权票据失效作为一等公民处理,而不是假设授权永远有效: Because users may pick "this session only" or a fixed TTL — or revoke at any time — the Cloud Runtime treats missing or expired tickets as a first-class state rather than an edge case:
| 票据状态Ticket state | 触发场景When it happens | Runtime 前端/接口行为Runtime behavior | 服务端与恢复动作Server & recovery |
|---|---|---|---|
| 无授权票据No grant | 用户从未授权该小程序,或在授权框点击拒绝User never authorized this app or tapped Decline | wx.agentLogin() 返回 40003 no_active_grant;出站层不附加 Proofreturns 40003 no_active_grant; egress attaches no Proof |
可由 Runtime / 页面触发弹出标准授权框,同意后重试取码Runtime/page triggers standard consent sheet; retry after approval |
| 票据已过期Expired | session_only 会话已结束,或 timed(如 24h)到达 grant_expires_atsession_only ended or timed TTL passed grant_expires_at |
wx.agentLogin() 返回 40007 grant_expired;wx.getSetting() 对应项重置为 falsereturns 40007 grant_expired; wx.getSetting() resets scopes to false |
推送 agent_session_revoked (grant_expired);触发标准授权框续期Pushes agent_session_revoked (grant_expired); prompts renewal sheet |
| 用户已撤销Revoked | 用户在微信「小微授权管理」中主动取消授权User revokes the app in WeChat Agent settings | control_epoch 递增,立即清除云端 Cookie;调用返 40006 grant_revokedcontrol_epoch increments, cloud cookies wiped; returns 40006 grant_revoked |
实时推送 agent_session_revoked (user_revoked);禁止自动重弹打扰Real-time push agent_session_revoked (user_revoked); no auto re-prompt |
| 单项权限未授Partial scope | 用户在打包授权框中单独取消了定位或地址开关User unchecked location or address in the bundle | wx.agentLogin() 仍正常;调 getLocation 等返回标准 auth denywx.agentLogin() works; getLocation returns standard auth deny |
不中断主流程;确需该权限时由 Runtime 发起单项补授权Main flow continues; Runtime prompts for the single scope only when needed |
1.3 开发者侧:wx.agentLogin 三路径与登录前 HITL 按钮门禁1.3 Developer side: 3-path wx.agentLogin & pre-login HITL button gate
开发者接入保持 L1–L4 分级,但为了满足商家在登录与敏感业务上的风控诉求,协议在 wx.agentLogin 上定义三条标准路径——商家可以通过组合 data-wxap-hitl 属性,在 wx.agentLogin 前放置一个受运行时保护的用户确认按钮,并自由配置「每次都需要点」或「点一次后记住」。
Integration stays tiered (L1–L4), while giving merchants full control over human intervention — even before login. wx.agentLogin follows three standard paths, and merchants can place a runtime-enforced user confirmation button ahead of login using data-wxap-hitl attributes.
Runtime 有有效票据,正常返回Valid ticket → returns code
用户已完成前置授权且票据未过期,同时开发者未配置登录门禁(或配置了 remember 且用户已确认过)。页面调用 wx.agentLogin() 直接返回一次性 code。
User has an active grant and no unsatisfied login gate (or remember was already confirmed). wx.agentLogin() immediately returns a one-time code.
无票据返回错误,向用户授权Error → prompt user grant
Runtime 没有有效票据(从未授权、session_only 结束、限时过期或已撤销)。wx.agentLogin() 返回明确错误码(40003 / 40006 / 40007),触发或引导向用户弹出标准授权框,完成后重试。
No active ticket (ungranted, expired TTL, or revoked). Returns explicit error (40003 / 40006 / 40007) and triggers the standard consent sheet to obtain a fresh ticket.
登录前自定义用户按钮(HITL Attr)Custom pre-login button via HITL attr
开发者在按钮上声明 data-wxap-hitl="login" 及 data-wxap-hitl-policy,要求必须先由用户点击按钮才放行 wx.agentLogin()。绕过按钮直接调接口将被 Runtime 拒绝(40008)。
Developer marks a button with data-wxap-hitl="login" and data-wxap-hitl-policy. Direct calls to wx.agentLogin() without user click are rejected with 40008.
按钮确认策略:always vs rememberButton confirmation policy: always vs remember
| 属性组合Attribute combination | 首次触发First time | 后续再次触发Subsequent times | 安全边界Security boundary |
|---|---|---|---|
data-wxap-hitl="login"data-wxap-hitl-policy="always" |
暂停 Agent,唤回用户本人点击按钮,颁发一次性手势证明后放行 wx.agentLogin()Pauses Agent; user clicks button; Runtime issues gesture attestation for wx.agentLogin() |
每次都必须用户本人重新点击,即使小微已有「总是允许」的前置授权User must click every time, even if the user chose "Always allow" globally | 高敏金融、企业内网、高客单账户;脚本和 Agent 均无法模拟点击Banking, enterprise, high-value accounts; unforgeable by Agent or JS |
data-wxap-hitl="login"data-wxap-hitl-policy="remember"data-wxap-hitl-key="shop_login" |
暂停 Agent,唤回用户点击按钮;原生确认条提供「记住此选择,后续自动允许」勾选框Pauses Agent; user clicks button with native checkbox "Remember and allow automatically" | 若用户勾选记住且前置票据仍有效,Runtime 自动放行 wx.agentLogin();否则再次请用户点击If checked and user grant is still active, Runtime auto-allows; otherwise asks again |
记忆许可按 (user, appid, hitl_key) 隔离,且受用户整体授权 TTL 约束,撤销或到期同步清除Scoped to (user, appid, hitl_key); cleared automatically when user grant expires or is revoked |
查看 wx.agentLogin 三路径与 HITL 按钮接入示例Show 3-path wx.agentLogin & HITL button example WXML / HTML + JS
<!-- 方式 A:每次代办登录都必须用户本人点击确认 -->
<button
data-wxap-hitl="login"
data-wxap-hitl-policy="always"
data-wxap-hitl-key="merchant_login"
bindtap="onAgentLoginTap">
确认授权小微登录我的账号
</button>
<!-- 方式 B:允许用户确认一次后选择「总是授权」 -->
<button
data-wxap-hitl="login"
data-wxap-hitl-policy="remember"
data-wxap-hitl-key="merchant_login"
bindtap="onAgentLoginTap">
允许小微登录(可记住本次确认)
</button>
async function doAgentLogin({ fromHitlButton = false } = {}) {
try {
// 若开发者在 MP 后台或按钮上要求 HITL 门禁,直接调用且无手势/记忆许可会抛出 40008
const { code, hitlConfirmed } = await wx.agentLogin({
state: csrfToken,
hitlKey: 'merchant_login'
});
// 路径 1 / 路径 3(确认后):携带 code 发给商家后端换取受限会话
return await exchangeAgentSession(code, csrfToken, hitlConfirmed);
} catch (err) {
if (err.errCode === 40003 || err.errCode === 40007) {
// 路径 2:无用户授权票据(40003)或票据已过期(40007)
// 通知 Runtime 弹出微信标准前置授权框,用户同意后再重试
await wx.requestAgentGrant({ reason: '需要您的授权以查询订单' });
return doAgentLogin({ fromHitlButton });
}
if (err.errCode === 40008) {
// 路径 3:命中开发者登录确认门禁,展示带 data-wxap-hitl="login" 的按钮引导用户点击
showMerchantConfirmLoginButton();
return;
}
// 40001 普通微信环境 / 40006 用户已撤销等:保持原有登录流程
fallbackToNormalLogin();
}
}
为什么用 HITL 属性组合就够了? 对开发者而言,只需声明 data-wxap-hitl 与 data-wxap-hitl-policy 即可跨小程序(WXML)、公众号 H5 与普通网页保持一致语法;而真正确保「Agent 不遵守时自动被拒、必须经用户客户端原生确认」的底层强制执行,则由下面 1.4 节的四层防绕过协议闭环保障。
Why HITL attributes suffice for developers: developers declare one uniform data-wxap-hitl + data-wxap-hitl-policy syntax across Mini Programs, H5, and Open Web, while actual non-bypassable enforcement is guaranteed by the 4-layer protocol in Section 1.4 below.
1.4 HITL 强制执行与防绕过协议(如何确保 Agent 无法自己点击或绕过)1.4 Enforcing HITL: preventing Agent self-clicks and bypasses
仅靠前端属性本身并不能阻止一个「不听话的 Agent」——Agent 仍可能尝试通过坐标/无障碍树强行点击按钮、注入脚本删除属性,或者跳过按钮直接调用 wx.agentLogin() / fetch()。协议通过四层强制闭环彻底堵死绕过路径:
Frontend markup alone cannot stop a disobedient Agent from clicking coordinates directly, stripping attributes via DOM scripting, or skipping the button to call wx.agentLogin() / fetch(). The protocol closes every bypass path with a 4-layer enforcement loop:
输入通道物理隔离(禁止 Agent 伪造真人输入)Physical input-channel isolation
云运行时宿主(Host)将输入管道严格拆为两条:大模型/自动化驱动发出的所有点击、键盘与提交操作均标记为不可信来源
input_source = AGENT,且沙盒禁止 Agent 通道执行任意 DOM 属性篡改脚本;只有经用户手机微信原生确认并由控制面签名回传的事件,才标记为input_source = HUMAN_VERIFIED并携带一次性hitl_attestation。The Cloud Runtime Host separates two input channels: all Agent-driven taps/keys carry untrustedinput_source = AGENT(with DOM attribute tampering blocked); only confirmations signed by native WeChat on the user's phone carryinput_source = HUMAN_VERIFIEDand a one-timehitl_attestation.按形态分层硬拦截:网页走浏览器内核,小程序走「宿主源标定 + 基础库事件合成层」Surface-native enforcement: Browser Engine for Web, Host + Base Library for Mini Programs
H5 与普通网页在浏览器内核层(InputRouter / Hit-Test)直接拦截命中
data-wxap-hitl的AGENT输入;小程序因为同时存在 WebView 与 Skyline(非浏览器 DOM)且为 View/Service 双线程架构,由宿主层标定不可伪造的输入源,并在小程序基础库事件合成层(如wx-component/events/touch.js、skyline/runtime/web-event.ts与tapMark跨线程链路)派发给开发者回调之前硬拦截并透传hitl_attestation(详析见下表)。H5 and Open Web enforce hit-testing directly inside the Browser Engine; Mini Programs — which run on both WebView and Skyline (non-DOM) with dual View/Service threads — pair Host-level input origin tagging with the Base Library event synthesis layer (touch.js/skyline/web-event.ts+ cross-threadtapMark) before dispatching to developer callbacks.客户端原生确认回传协议(Challenge → 手机确认 → 签发
hitl_attestation)Client native confirmation round-trip一旦拦截到
AGENT通道触碰 HITL 元素,运行时直接吞掉该事件(不触发开发者bindtap/click,向 Agent 返回HITL_INTERCEPTED),自动暂停 Agent 控制权,并向微信控制面发起CreateHitlChallenge;控制面在用户手机微信弹出原生确认卡(含应用名、按钮文案及remember策略下的「记住此选择」勾选框)。用户真实点击后,控制面签发短时一次性hitl_attestation(绑定agent_session_id、control_epoch、hitl_key、nonce)回传运行时,由内核以HUMAN_VERIFIED放行本次交互。When anAGENTinput hits a HITL target, the event is dropped before reaching page handlers, Agent control pauses, and Runtime sendsCreateHitlChallengeto WeChat Control Plane. WeChat renders a native confirmation card on the phone; upon a real tap, Control Plane mints a short-livedhitl_attestation(bound to session, epoch,hitl_key, and nonce) and unlocks the interaction.控制面策略前移与后端强验(堵死跳过按钮直接调 API)Control-plane policy & server verification (stops button-skipping)
为防止 Agent 或脚本完全不点按钮而直接调用
wx.agentLogin(),商家可在 MP 后台或已签名小程序代码包app.json中声明agentLoginHitl: "always" | "remember" | "none"。调用wx.agentLogin()时,Runtime 与控制面强制核验调用上下文是否携带有效hitl_attestation(或未过期的控制面记忆记录),否则拒返40008;换码接口code2agentSession返回由控制面权威签发的hitl_confirmed,高危写操作则将确认凭证绑定至WeChat-Agent-Proof供verify_proof强校验,确保安全最终防线不依赖客户端 JS。To stop direct calls towx.agentLogin()without tapping the button, merchants declareagentLoginHitl: "always" | "remember" | "none"in MP Admin or signedapp.json. Control Plane refuses to mint a login code (returning40008) without a validhitl_attestationor live remembered grant, and returns authoritativehitl_confirmedto the merchant backend — so security never rests solely on client JS.
架构取舍:小程序基础库层 vs 浏览器内核层Architecture trade-off: Mini Program Base Library vs. Browser Engine
| 方案Approach | 覆盖范围Coverage | 优势Strengths | 单独使用的局限Limitations if used alone |
|---|---|---|---|
| 仅小程序基础库层Base Library only | 小程序(WebView + Skyline)Mini Programs (WebView + Skyline) | 天然位于所有 tap / formSubmit 派发到开发者域之前;可直接复用 shouldCancelEvent 与 wrapTapMark 跨线程把确认态带给 Service 层 wx.agentLogin()Sits naturally before every developer event dispatch; reuses wrapTapMark to carry gesture state across View→Service threads to wx.agentLogin() |
① 覆盖不到公众号 H5、<web-view> 与普通网页;② 纯 JS 无法区分 CDP 注入的 Agent 点击与真人点击(DOM 里都是 isTrusted: true),必须依赖宿主输入源标定① Cannot cover OA H5, <web-view>, or Open Web; ② Pure JS cannot distinguish CDP Agent clicks from human clicks without Host origin tagging |
| 仅浏览器内核层Browser Engine only | H5、<web-view>、普通网页、WebView 小程序H5, <web-view>, Open Web, WebView MP |
原生位于 InputRouter / Hit-Test 层,抗页面 JS 篡改能力最强,天然统一所有网页形态Native InputRouter / Hit-Test interception; strongest DOM tamper resistance across all web surfaces | ① 覆盖不到小程序 Skyline(Flutter) 渲染引擎;② 小程序 WXML data-* 挂在 Exparser / Glass-Easel dataset 上未必直出为标准 DOM 属性;③ 浏览器手势上下文跨不过 WeixinJSBridge 到小程序 Service 逻辑层① Misses Mini Program Skyline (Flutter) renderer; ② WXML data-* lives on component dataset; ③ Browser user-gesture cannot cross WeixinJSBridge into the Service thread |
| 推荐:分层协同Recommended: Hybrid | 全 4 类形态 + WebView / SkylineAll 4 surfaces + WebView / Skyline | 宿主层统一做输入源隔离与手机确认回传;网页侧由浏览器内核直接拦截 DOM;小程序侧由基础库事件合成层消费宿主标定的 inputOrigin 并通过升级版 tapMark 把 hitl_attestation 跨线程送达 Service 层 wx.agentLogin();最终由控制面/服务端验票兜底Host enforces input origin & phone round-trip everywhere; Browser Engine intercepts Web DOM; Base Library consumes Host inputOrigin and forwards hitl_attestation via upgraded tapMark to Service wx.agentLogin(); Control Plane verifies authoritatively |
需维护「浏览器内核」与「小程序基础库」两个执行适配点,但共用同一套控制面 CreateHitlChallenge 与 hitl_attestation 协议Two thin enforcement adapters (Browser Engine + Base Library) sharing one unified Control Plane challenge & attestation protocol |
data-wxap-hitl="login" 按钮时如何被自动拒绝、唤回手机原生确认,以及控制面签发的 hitl_attestation 如何经跨线程上下文送达 wx.agentLogin() 与开发者后端。Shows how an Agent self-click on a data-wxap-hitl="login" button is automatically blocked, routed to native phone confirmation, and unlocked only via a Control-Plane-minted hitl_attestation verified end-to-end.02适用范围与接入级别Scope & Integration Levels
四类页面形态共享同一套双向授权与身份模型,区别只在于「如何证明页面归属」和「后端如何核验」。 All four surfaces share one bidirectional auth and identity model. They differ only in how page ownership is proven and how the backend verifies requests.
| 页面形态Surface | 前端与 HITL 接入Frontend & HITL | 归属证明Ownership proof | 后端核验Backend verification |
|---|---|---|---|
| 小程序Mini Program | 基础库 wx.* + WXML data-wxap-hitlBase library wx.* + WXML data-wxap-hitl | 代码包签名中的 AppIDAppID in signed package | WeChat-Agent-Proof → 微信服务端WeChat server |
| 公众号网页Official Account H5 | JS-SDK 扩展 + HTML data-wxap-hitlJS-SDK + HTML data-wxap-hitl | wx.config(同源持久有效)wx.config (persists per origin) | WeChat-Agent-Proof → 微信服务端WeChat server |
| 小程序 <web-view>MP <web-view> | 直接使用 H5 JS-SDK + data-wxap-hitlH5 JS-SDK + data-wxap-hitl | 页面自身的 wx.configPage's own wx.config | 与公众号网页相同Same as Official Account H5 |
| 普通网页Regular website | 无需 SDK,直接用 data-wxap-hitlNo SDK; standard data-wxap-hitl | /.well-known/wx-agent.json | WeChat-Agent-Token → 本地验签local verification |
前端适配(L2)与后端识别(L3)可以独立接入,未接入的商家始终保持原有行为。兼容模式下微信不添加任何请求头,也不修改 UA、URL 或请求体。 Frontend awareness (L2) and backend verification (L3) can be adopted independently, and merchants who opt out keep existing behavior. In compatible mode WeChat adds no headers and never alters UA, URL, or body.
03身份、票据与会话模型Identity, Tickets & Session Model
同一个云端页面可以先由小微操作,再交给用户点击确认——环境没变,但控制权与票据状态可能随时变化。因此协议把四个维度分开判断。 The same cloud page can be driven by XiaoWei and then handed to the user — the environment stays while controller and ticket state evolve. So the protocol separates four dimensions.
| 判断Question | 字段Fields | 由谁给出Source | 用来做什么Used for |
|---|---|---|---|
| 在哪里运行Where is it running? | env | 微信运行平台WeChat runtime | 区分云运行时与普通客户端,选择风控策略Distinguish cloud runtime from phone; pick risk policy |
| 谁在操作Who is in control? | controller, control_epoch | 微信控制面WeChat control plane | 区分 Agent 与用户;每次接管、过期或撤销递增 epoch,让在途旧请求失效Agent vs. user; epoch increments on takeover, expiry, or revoke |
| 代表哪位用户For which user? | openid, agent_openid, agent_session_id | 微信身份服务WeChat identity | 直接映射到商家已有用户账号,不新建账号、不碰手机 session_keyMaps straight to your existing user without touching phone session_key |
| 票据与权限Ticket & authority | grant_ref, grant_ttl_mode, grant_expires_at, scopes, hitl_confirmed, confirm_token | 用户授权 ∩ 商家策略 ∩ 平台规则User grant ∩ merchant policy ∩ platform rules | 确认授权票据未过期、权限覆盖本次动作,以及是否经过商家要求的按钮确认Confirms live ticket TTL, granted scopes, and whether merchant HITL confirmation occurred |
openid:用户在当前 AppID 下的既有身份。openid: the user's existing identity under your AppID.agent_openid:用户某个 Agent 在你这里的不透明标识,仅用于展示与审计,不能跨应用关联,本身不赋予权限。agent_openid: an opaque per-app Agent ID for display and audit only — non-linkable across apps, grants nothing on its own.grant_ref&grant_expires_at:用户在前置标准授权框签发的授权票据引用与到期时间(always模式仍受平台安全滚动上限保护)。grant_ref&grant_expires_at: reference and expiry timestamp of the user's pre-authorization ticket.hitl_confirmed:标明本次登录或操作是否经过了用户本人的显式按钮点击("explicit_click"/"remembered"/"none"),供商家后端二次核验。hitl_confirmed: indicates whether the action passed a human button gate ("explicit_click","remembered", or"none") for server-side enforcement.
保守归因: 后台定时请求、跨越接管或过期时刻的异步请求一律标记为 controller: "unknown"。不可逆操作不能只凭「当前是用户在操作」放行,必须核验用户的显式确认。
Conservative attribution: background timers or async requests crossing a takeover/expiry are marked controller: "unknown". Never approve irreversible writes without explicit confirmation.
04前端与 JS-SDK 接口Frontend & JS-SDK API
小程序与 H5 使用同一组扁平的 wx.* 接口,命名风格与 wx.login、wx.getSetting 一致,同时支持回调与 Promise。
Mini Programs and H5 share one flat set of wx.* APIs matching wx.login and wx.getSetting, supporting both callbacks and Promises.
接口一览API overview
| 接口API | H5 是否需要 wx.configH5 needs wx.config? | 作用Purpose |
|---|---|---|
wx.getAgentContext | 不需要No | 读取运行环境、当前操作方、control_epoch 与 grantStatus(active | none | expired | revoked),用于界面提示;不返回凭证。Reads env, controller, epoch, and grantStatus (active | none | expired | revoked) for UI hints; returns no credentials. |
wx.onAgentControlChange | 不需要No | 监听接管、归还、暂停、票据过期(grant_expired)、撤销与结束。Listens for takeover, handback, pause, grant_expired, revoke, and end. |
wx.requestAgentGrant | 不需要No | 在 wx.agentLogin 返回无票据或过期错误后,显式唤起微信标准前置授权框(用户拒绝或已主动撤销时不强制打扰)。Triggers the standardized consent sheet after a missing/expired ticket error (respects user-revoked cooldowns). |
wx.requestUserTakeover | 不需要No | 主动暂停 Agent,请用户完成验证码或动态风控步骤。Pauses the Agent and asks the user to finish a captcha or dynamic risk challenge. |
wx.agentLogin | 需要(每 Origin 一次)Yes (once per origin) | 按三路径规则获取一次性 code:有票直返、无票/失效报错、命中 HITL 按钮门禁时校验真人点击或记忆许可。3-path one-time code API: returns on active grant, errors on missing/expired, and enforces HITL login gates. |
<wx-open-agent-confirm> | 需要(openTagList)Yes (openTagList) | 防伪造的原生确认按钮,绑定订单金额与内容摘要,返回 confirmToken。Tamper-proof native confirmation sheet bound to order summary and payload digest. |
wx.agentLogin 失败与错误码规范wx.agentLogin error codes
所有非成功路径都返回明确错误码,便于页面精准区分「普通微信」「无票据/票据失效」与「商家要求按钮确认」,且永不影响原有登录方式。Every non-success path returns a distinct error code separating regular WeChat, missing/expired tickets, and merchant HITL login gates.
| errCode | 错误标识Error name | 原因Reason | 建议处理Suggested handling |
|---|---|---|---|
| 40001 | not_agent_runtime | 当前是普通微信客户端Regular WeChat client | 沿用原有 wx.login 或站点登录Use your normal login flow |
| 40002 | not_agent_controller | 当前处于用户接管态User is currently in control | 不建立 Agent 会话Do not establish an Agent session |
| 40003 | no_active_grant | Runtime 无该应用的用户授权票据Runtime holds no active user grant | 调用 wx.requestAgentGrant() 或由小微弹出标准授权框,同意后重试Trigger wx.requestAgentGrant() or let XiaoWei prompt the consent sheet |
| 40004 | endpoint_not_registered | 未在 MP 后台登记换码接口Exchange endpoint not registered | 在 MP 后台补登记登录接口Register the login endpoint in MP Admin |
| 40005 | config_required | H5 尚未完成 wx.configH5 has not called wx.config | 完成同源一次 wx.config 后调用Run wx.config once per origin first |
| 40006 | grant_revoked | 用户已主动撤销该应用的 Agent 授权User explicitly revoked authorization | 终止代办并清理前端状态,不自动重弹授权框Stop delegation and clear state; do not auto-reprompt |
| 40007 | grant_expired | 「仅本次会话」已结束或限时票据已到期Session-only ended or timed TTL expired | 清理旧会话,唤起标准授权框续期后重新取码Clear stale session, prompt renewal sheet, then retry |
| 40008 | user_confirm_required | 开发者要求登录前经用户点击按钮确认(未获本次手势或记忆许可)Developer requires a HITL button click before login | 展示带 data-wxap-hitl="login" 的确认按钮,待用户点击后在回调中再次调用Show the data-wxap-hitl="login" button and call again inside its click handler |
| 40009 | user_confirm_rejected | 用户在确认按钮/授权框中选择了拒绝User declined the confirmation prompt | 尊重用户选择,保持未登录态或转交人工Respect user refusal; stay logged out or hand over |
三层人工确认(HITL)体系Three levels of human confirmation (HITL)
从「属性标记」到「防伪造原生确认」,全面覆盖登录门禁、表单提交与高风险交易。From declarative attributes to tamper-proof native sheets — covering login gates, form submissions, and high-risk writes.
HITL 属性组合HITL attributes
用 data-wxap-hitl 标记元素:login(登录前确认按钮)、interaction(禁止 Agent 碰触)、submission(Agent 填表、用户提交)。配合 data-wxap-hitl-policy="always | remember" 与 data-wxap-hitl-key 控制「每次点」或「记一次」。
Mark elements with data-wxap-hitl: login (pre-login gate), interaction (no Agent touch), submission (Agent fills, user submits). Pair with data-wxap-hitl-policy="always | remember" and data-wxap-hitl-key.
主动接管Imperative takeover
页面在运行时调用 wx.requestUserTakeover(),适合滑块验证码、异常风控挑战等动态出现的场景。
Call wx.requestUserTakeover() at runtime — ideal for captchas and dynamic risk challenges.
防伪造原生确认Tamper-proof confirm
<wx-open-agent-confirm> 弹出微信原生确认页,绑定商品、金额与 payload-digest,确认后返回不可篡改的 confirmToken。
<wx-open-agent-confirm> opens a native WeChat sheet bound to items, amount, and payload-digest, yielding a confirmToken.
查看三层 HITL 完整属性与代码示例Show all 3 HITL levels example HTML / WXML
<!-- Level 1a: 登录确认门禁(支持 always / remember 策略) -->
<button data-wxap-hitl="login" data-wxap-hitl-policy="remember" data-wxap-hitl-key="order_login">
确认允许小微登录
</button>
<!-- Level 1b: 禁止触碰与提交确认 -->
<input name="sms_code" data-wxap-hitl="interaction">
<button type="submit" data-wxap-hitl="submission" data-wxap-hitl-policy="always">提交退款申请</button>
<!-- Level 3: 原生防伪造确认 -->
<wx-open-agent-confirm
id="confirm"
action-id="order_8891"
summary="明前龙井礼盒 · ¥128.00"
payload-digest="sha256:9f86d081...">
</wx-open-agent-confirm>
<script>
// Level 2: 动态风控接管
wx.requestUserTakeover({ mode: 'verification', reason: '请完成滑块验证' });
// Level 3: 获取原生确认票据
document.getElementById('confirm').addEventListener('confirm', e => {
submitOrder(e.detail.confirmToken);
});
</script>
已有基础库 / JS-SDK 接口在云端的行为(与前置授权联动)Existing APIs in Cloud Runtime (linked with pre-auth)
| 类别Category | 接口APIs | 行为Behavior |
|---|---|---|
| 隐私协议Privacy notice | wx.getPrivacySetting, wx.onNeedPrivacyAuthorization | 前置授权框已默认同意时直接返回 needAuthorization: false;票据失效后自动恢复为需授权Returns needAuthorization: false when covered by active pre-auth; reverts on expiry |
getSetting 授权项getSetting scopes | wx.getSetting, getLocation, chooseAddress / openAddress, chooseInvoiceTitle | 在有效前置授权范围内直接提供且 authSetting 为 true;用户单项关闭或票据过期时返回 false / auth deny 并支持按需补授Provided seamlessly under active bundle; returns false / auth deny if unchecked or expired |
| 必须本人操作User only | requestPayment, chooseWXPay, scanQRCode | 永不包含在前置打包授权中,始终转交用户或手机端完成Never bundled; always handed to the user or phone |
| 安全兼容Safe emulation | previewImage, closeWindow, getNetworkType | 正常返回,保证已有页面零报错Returns normally so existing pages do not break |
| Agent 期间禁用Disabled for Agent | startRecord, addCard, 分享转发类sharing APIs | 返回 unsupported_in_agent_runtimeReturns unsupported_in_agent_runtime |
05认证流程与服务端接口Flows & Server APIs
小程序、公众号网页与 <web-view> 共享同一套双向授权登录与换码流程:先确认用户票据与商家门禁,再一次取码、一次换码。 Mini Programs, Official Account pages, and <web-view> share one login flow: satisfy user ticket + merchant gate, then get a code once and exchange it once.
wx.agentLogin 三路径处理(正常直返、无票/失效唤授权、HITL 按钮确认),最终由微信出站层附加 WeChat-Agent-Proof 送达开发者后端。Covers standard pre-auth, the 3 paths of wx.agentLogin (active ticket, missing/expired re-auth, HITL button click), and egress WeChat-Agent-Proof exchange.账号不是按 openid 关联时When accounts aren't keyed by openid
如果站点使用手机号、密码或企业 SSO 等自有账号体系,可以增加一步绑定:微信请用户在手机上完成一次原站登录,商家把验证后的账号关联到云端的登录事务,云端随后用 Agent code 完成绑定并获得自己的受限会话。手机上的 Cookie 不会被复制到云端。 If your site uses phone, password, or enterprise SSO accounts, add one binding step: the user signs in once on their phone, you link the verified account to the cloud login transaction, and the cloud browser completes binding with its Agent code. Phone cookies are never copied to the cloud.
高风险操作、票据过期与撤销High-risk actions, expiry & revocation
下单、退款等操作需用户在原生确认页核对内容,后端核验内容摘要与最新 control_epoch。无论用户主动撤销还是限时票据到期,微信都会即时递增 epoch 并推送撤销事件。
For purchases and refunds, the user confirms details on a native sheet and the backend checks payload digest and control_epoch. Both revocation and TTL expiration immediately bump the epoch and push a revocation event.
control_epoch 已变化,在途写请求会被原子拒绝。If takeover, revocation, or TTL expiration occurs mid-flight, control_epoch advances and the in-flight write is atomically rejected.服务端接口Server APIs
code2agentSession
登录时调用。核验并消费 js_code 与 proof,返回用户身份、授权范围、票据有效期以及本次登录是否通过了商家 HITL 按钮确认。绝不签发或刷新手机端 session_key。Called at login. Verifies and consumes js_code and proof, returning identity, scopes, ticket TTL, and HITL confirmation status. Never touches phone session_key.
| 字段Field | 方向Direction | 说明Description |
|---|---|---|
js_code | 请求Request | 前端 wx.agentLogin() 得到的 codeCode returned by wx.agentLogin() |
proof | 请求Request | 请求头 WeChat-Agent-Proof 的值Value of the WeChat-Agent-Proof header |
target_uri | 请求Request | 收到该请求的接口地址Endpoint URL that received the request |
openid | 返回Response | 用户在当前 AppID 下的既有身份User's existing identity under your AppID |
agent_session_id | 返回Response | 本次任务的执行会话 IDThis task's execution session ID |
grant_ref, grant_ttl_mode | 返回Response | 用户授权票据引用与时效模式(always | session_only | timed)User grant ticket ref & lifetime mode (always | session_only | timed) |
grant_expires_at | 返回Response | 用户授权票据到期时间戳;商家会话有效期不应超过此值Ticket expiration timestamp; merchant session TTL should not exceed this |
hitl_confirmed | 返回Response | 登录前按钮确认状态:explicit_click(本次真人点击)、remembered(记忆放行)或 nonePre-login HITL state: explicit_click, remembered, or none |
scopes, control_epoch | 返回Response | 允许的操作范围与当前控制代次(后续请求不得低于此值)Allowed scopes and current control epoch |
查看完整请求与响应Show full request and response JSON
// POST https://api.weixin.qq.com/wxa/agent/code2session?access_token=ACCESS_TOKEN
{
"appid": "wx1234567890abcdef",
"js_code": "agcode_0a1b2c3d",
"proof": "wxap_v2_9f8e7d6c",
"target_uri": "https://shop.example.com/api/wx-agent/login"
}
// Response
{
"errcode": 0,
"openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
"agent_openid": "ag_7f3c91a2e4b8",
"agent_session_id": "agsess_20261122_x9k2",
"grant_ref": "grant_88219a",
"grant_ttl_mode": "timed",
"grant_expires_at": 1763699167,
"hitl_confirmed": "explicit_click",
"hitl_key": "merchant_login",
"scopes": ["agent:login", "privacy:agree", "scope.userLocation", "scope.address", "order:read"],
"env": "cloud_runtime",
"controller": "agent",
"control_epoch": 1,
"state": "csrf_9f2a8c",
"expires_at": 1763616367
}
verify_proof
高风险写操作时调用。确认证明有效、用户授权票据未过期未撤销、epoch 未过期,以及提交内容与用户确认的内容完全一致。Called for high-risk writes. Confirms valid proof, active non-expired grant, current epoch, and exact payload match.
| 字段Field | 方向Direction | 说明Description |
|---|---|---|
proof | 请求Request | 本次请求附带的 WeChat-Agent-ProofThe WeChat-Agent-Proof header on this request |
confirm_token | 请求Request | 用户在原生确认页确认后得到的票据Token from the user's native confirmation |
body_sha256 | 请求Request | 请求体的 SHA-256,用于防篡改SHA-256 of the raw request body |
valid, grant_active | 返回Response | 证明是否有效、授权票据是否仍在有效期内且未撤销Whether proof is valid and grant ticket is still live |
payload_digest_matched | 返回Response | 提交内容是否与用户确认的内容一致Whether the submission matches what the user confirmed |
control_epoch | 返回Response | 最新控制代次Latest control epoch |
失效与撤销事件推送Expiry & revocation event push
用户撤销授权、接管操作、session_only 会话结束或限时票据到期时,微信向 MP 消息推送地址发送 agent_session_revoked 事件(含 AgentSessionId、GrantRef、ControlEpoch 与 Reason: user_revoked | grant_expired | session_ended | user_takeover),收到后立即作废对应 Agent 会话。On revocation, takeover, session_only end, or TTL expiry, WeChat sends agent_session_revoked (with AgentSessionId, GrantRef, ControlEpoch, and Reason) to your MP push URL. Invalidate the Agent session immediately.
06开发者如何验证How Developers Validate
WeChat-Agent-Proof 与 WeChat-Agent-Token 是微信云运行时出站网关层(沙盒之外,页面脚本与大模型均不可见)在请求离开微信云端时自动注入的来源证明头,用来向开发者证实「请求确由微信托管运行时在有效用户授权内发出」。微信生态应用只需把 Proof 转交给微信服务端;普通网页用标准 JWT 库本地验签。
WeChat-Agent-Proof and WeChat-Agent-Token are origin-attestation headers injected by WeChat's Egress Layer (outside the sandbox, invisible to page JS and the LLM). WeChat apps forward the opaque proof to WeChat's server with zero crypto; regular websites verify the Ed25519 JWT locally.
WeChat-Agent-Proof | WeChat-Agent-Token | |
|---|---|---|
| 定位与适用场景Role & surfaces | 微信生态内(小程序、公众号网页、<web-view>)的登录换码、后端识别与高危写操作核验Inside WeChat (Mini Programs, OA H5, <web-view>) for login exchange, traffic ID, and high-risk writes | 微信生态外(普通网页 Open Web,无微信 AppID、无法调微信服务端)的 Agent 识别与登录入口校验Open Web (regular websites without a WeChat AppID) for Agent identification and login gate checks |
| 如何生成How it is minted | 请求命中 MP 后台登记接口且持有有效用户票据时,出站层向控制面注册一次性状态记录(强绑定 appid、agent_session_id、grant_ref、control_epoch、目标 URI、可选 body_sha256 与 hitl_attestation),将不透明句柄注入请求头On registered MP endpoints with an active grant, Egress registers a single-use state record on Control Plane (binding appid, session, grant, epoch, target URI, optional body_sha256 & hitl_attestation) and injects the opaque handle | 请求命中网站 /.well-known/wx-agent.json 声明路径时,出站签名服务将 iss、aud(网站 Origin)、jti、htm、htp 及可选 body_sha256 组装为 JSON,用微信 Ed25519 私钥实时签名注入请求头On paths declared in wx-agent.json, Egress builds a clean JSON claim set (iss, aud, jti, htm, htp, optional body_sha256) and signs it on the fly with WeChat's Ed25519 private key |
| 形态与有效期Format & TTL | 不透明字符串,60 秒,单次消费即作废Opaque string, 60 s, single use | 自包含 Ed25519 JWS/JWT,60 秒,靠 jti 缓存防重放Self-contained Ed25519 JWS, 60 s, replay-protected via jti |
| 开发者如何验证How to verify | 零加密代码:透传给 code2agentSession / verify_proof,由微信服务端原子核验状态与 HITL 确认记录Zero crypto: forward to code2agentSession / verify_proof for atomic verification | 本地离线验签:用缓存的微信公钥(JWKS)验证签名与目标路径,并将 jti 写入 Redis 120 秒Local verification: verify against cached WeChat JWKS and store jti in Redis for 120 s |
务必拒绝而非降级: 任何人都可以伪造同名请求头。在要求验证的接口上,缺少证明、验证失败、票据已过期、未通过商家要求的 hitl_confirmed 或 epoch 过期时,必须返回 401 / 403,绝不能退回为普通用户会话。
Reject, never downgrade: anyone can forge headers. On protected endpoints, missing proofs, expired grants, missing required hitl_confirmed, or stale epochs must return 401 / 403 — never fall back to a regular user session.
场景 A:登录换码(含票据有效期与 HITL 门禁核验)Scenario A: login exchange (with TTL & HITL check)
读取证明与 codeRead proof & code
从请求头取出
WeChat-Agent-Proof,从请求体取出code;任一缺失则拒绝。ExtractWeChat-Agent-Proofandcode; reject if either is missing.交给微信核验并检查商家策略Verify with WeChat & check policy
调用
code2agentSession。若商家要求每次登录必须用户本人点击,核验hitl_confirmed === 'explicit_click'(或允许'remembered')。Callcode2agentSession. If your risk policy requires a pre-login user click, verifyhitl_confirmedaccordingly.按票据有效期签发受限会话Issue TTL-bounded scoped session
将商家受限会话过期时间裁剪为
min(默认时长, grant_expires_at),签发独立HttpOnlyCookie 并记录scopes与epoch。Cap the scoped session lifetime atmin(defaultTtl, grant_expires_at), issue an isolatedHttpOnlycookie, and recordscopesandepoch.
查看示例代码Show example code Node.js
app.post('/api/wx-agent/login', async (req, res) => {
const proof = req.get('WeChat-Agent-Proof');
const { code } = req.body;
if (!proof || !code) return res.status(401).end();
const wx = await wechat.post('/wxa/agent/code2session', {
appid: APPID,
js_code: code,
proof,
target_uri: `https://${req.hostname}${req.originalUrl}`
});
if (wx.errcode !== 0) return res.status(401).end();
// 若商家配置了「总是需要用户点击登录按钮」,服务端二次强校验
if (REQUIRE_ALWAYS_CLICK && wx.hitl_confirmed !== 'explicit_click') {
return res.status(403).json({ error: 'user_confirm_required' });
}
const user = await users.findByOpenId(wx.openid);
const maxExp = Math.min(wx.expires_at, wx.grant_expires_at || wx.expires_at);
const sid = await sessions.create({
userId: user.id,
type: 'agent',
agentSessionId: wx.agent_session_id,
grantRef: wx.grant_ref,
scopes: wx.scopes,
epoch: wx.control_epoch,
expiresAt: maxExp
});
res.cookie('wx_agent_sid', sid, { httpOnly: true, secure: true, sameSite: 'lax' });
res.json({ ok: true, grantTtlMode: wx.grant_ttl_mode });
});
场景 B:高风险写操作Scenario B: high-risk writes
普通读请求直接放行Plain reads pass through
浏览、查询只需校验受限会话 Cookie 且未过期,无需额外调用微信。Reads only check the live scoped session cookie — no extra WeChat call.
计算请求体摘要Hash the request body
对原始请求体计算 SHA-256。Compute SHA-256 over the raw request body.
调用 verify_proofCall verify_proof
提交证明、确认票据与摘要;仅当票据仍有效、epoch 未过期且内容完全一致时执行,并配幂等键。Submit proof, confirm token, and digest; proceed only if grant is active, epoch is current, and payload matches.
查看示例代码Show example code Node.js
app.post('/api/orders/submit', requireAgentSession, async (req, res) => {
const proof = req.get('WeChat-Agent-Proof');
const { confirmToken, idempotencyKey } = req.body;
if (!proof || !confirmToken) return res.status(403).end();
const v = await wechat.post('/wxa/agent/verify_proof', {
appid: APPID,
agent_session_id: req.session.agentSessionId,
proof,
confirm_token: confirmToken,
expected_request: {
method: req.method,
target_uri: `https://${req.hostname}${req.originalUrl}`,
body_sha256: sha256(req.rawBody)
}
});
const ok = v.errcode === 0 && v.valid && v.grant_active
&& v.control_epoch >= req.session.epoch
&& v.confirmation?.payload_digest_matched;
if (!ok) return res.status(403).end();
res.json(await orders.submit(req.body, idempotencyKey));
});
场景 C:普通网页Scenario C: regular websites
验证签名Verify the signature
用微信公开的 JWKS 验证 Ed25519 签名、签发方、受众(你的 Origin)与有效期。Verify Ed25519 signature, issuer, audience (your origin), and expiry against WeChat's JWKS.
防止重放Prevent replay
把
jti写入缓存(120 秒),已存在则拒绝。Cachejtifor 120 s; reject duplicates.核对请求目标Check the target
确认令牌中的方法、路径(及可选请求体摘要)与当前请求一致。Verify HTTP method, path, and optional body digest match.
查看示例代码Show example code Node.js · jose
import { createRemoteJWKSet, jwtVerify } from 'jose';
const JWKS = createRemoteJWKSet(new URL('https://open.weixin.qq.com/.well-known/jwks.json'));
async function verifyAgentToken(req) {
const token = req.get('WeChat-Agent-Token');
const { payload } = await jwtVerify(token, JWKS, {
algorithms: ['EdDSA'],
issuer: 'https://open.weixin.qq.com/agent',
audience: `https://${req.hostname}`
});
const fresh = await redis.set(`jti:${payload.jti}`, 1, 'EX', 120, 'NX');
if (!fresh) throw new Error('replayed');
if (payload.htm !== req.method || payload.htp !== req.path) {
throw new Error('target mismatch');
}
return payload;
}
07普通网页接入Regular Web Pages
没有公众号或小程序的网站,不需要引入任何 SDK,只用 Web 标准文件与 data-wxap-hitl 属性即可接入。
Websites without an Official Account or Mini Program need no SDK — just one static JSON file and standard data-wxap-hitl attributes.
什么都不做Do nothing
Agent 以普通浏览器身份访问,不加任何请求头。遇到登录或支付时交给用户,任务结束后清除整个浏览环境。
Browses like a normal browser with no extra headers. Logins and payments go to the user; profile is wiped after the task.
放一个静态文件 + HITL 属性Host one JSON + HITL attrs
在 /.well-known/wx-agent.json 声明允许、禁止与登录门禁策略;在敏感或登录按钮上加 data-wxap-hitl 与 data-wxap-hitl-policy。
Declare rules in /.well-known/wx-agent.json; add data-wxap-hitl & data-wxap-hitl-policy to sensitive or login buttons.
识别 Agent 请求Recognize Agent requests
为声明的路径接收 WeChat-Agent-Token(Ed25519 JWS),签名对象是干净 JSON,不惧 CDN 或反代改写头。
Receive WeChat-Agent-Token (Ed25519 JWS) on declared paths — resilient to CDNs and reverse proxies.
wx-agent.json 字段wx-agent.json fields
| 字段Field | 说明Description |
|---|---|
policy.allow | Agent 可以自动访问的路径Paths the Agent may visit automatically |
policy.disallow | 禁止 Agent 进入的路径,优先级高于 allowPaths the Agent may not enter; overrides allow |
policy.hitl_paths | 必须由用户本人操作的页面Pages the user must operate personally |
attestation.paths | 需要附加 WeChat-Agent-Token 的接口,可选包含请求体摘要Endpoints receiving WeChat-Agent-Token, optionally with body hash |
auth.agent_login_url | Agent 登录入口,支持搭配 hitl_policy: "always" | "remember"Agent login entry; supports hitl_policy: "always" | "remember" |
查看完整示例Show full example JSON
{
"version": "2.0",
"policy": {
"allow": ["/products/*", "/orders/*"],
"disallow": ["/account/security/*"],
"hitl_paths": ["/checkout/confirm"]
},
"attestation": {
"paths": [
{ "path": "/auth/agent-login", "methods": ["GET", "POST"] },
{ "path": "/api/orders/*", "methods": ["POST"], "include_body_hash": true }
]
},
"auth": {
"agent_login_url": "https://example.com/auth/agent-login",
"hitl_policy": "remember"
}
}
08安全架构与威胁分析Security & Threats
核心原则是委托权限而不交出凭证。大模型和网页脚本都被视为不可信;授权票据签发、TTL 过期裁剪、HITL 真人手势校验与出站证明只发生在微信原生界面、控制面与出站层三个可信边界内。 Core principle: delegate authority without surrendering credentials. Both LLM output and page scripts are untrusted; grant tickets, TTL checks, HITL gesture verification, and egress proofs live strictly inside WeChat's three trusted boundaries.
威胁与防御Threats and defenses
| 威胁Threat | 攻击方式Attack | 防御Defense |
|---|---|---|
| 绕过登录确认按钮Bypassing HITL login | 页面脚本或 Agent 跳过 data-wxap-hitl="login" 按钮,直接调 wx.agentLogin() 或模拟 click()Page JS or Agent skips the HITL button or fires synthetic click() | Runtime 仅认微信原生界面回传的真人手势凭证;无凭证直接拒返 40008,且后端可二次验 hitl_confirmedRuntime only accepts native UI gesture proofs; returns 40008 otherwise; backend can enforce hitl_confirmed |
| 过期票据继续代办Stale / expired ticket | session_only 结束或限时票据到期后,残留沙盒继续发起请求Residual sandbox keeps calling after session end or TTL expiry | 控制面实时递增 control_epoch、出站层停止附加证明、wx.agentLogin 返 40007,并推送 agent_session_revokedControl plane bumps control_epoch, egress stops attaching proofs, API returns 40007, push invalidates backend session |
| code 被盗用Stolen code | XSS 窃取 code 后从外部提交XSS steals code and replays externally | 外部请求无出站层附加的 WeChat-Agent-Proof,换码失败External requests lack egress proof; exchange fails |
| 脚本或提示注入Prompt / JS injection | 恶意内容诱导 Agent 越权或窃取会话Malicious page content tricks Agent | Cookie 为 HttpOnly;前端不能自选 scopes;写操作需脚本不可见的出站证明HttpOnly cookies; frontend cannot request scopes; writes need script-invisible proofs |
| 撤销竞态Revocation race | 撤销或过期瞬间仍有请求在途In-flight request races revocation | epoch 递增后旧请求被原子拒绝,配合幂等键Bumped epoch atomically rejects stale requests + idempotency keys |
| 会话互相影响Session interference | Agent 登录导致手机端掉线Agent login kicks phone off | Agent 会话完全独立,永不刷新手机 session_keySeparate Agent session; never refreshes phone session_key |
| 点击劫持Clickjacking | 用 CSS 遮挡确认按钮误导用户CSS overlays mislead user taps | 授权框与确认条在微信原生层渲染,页面样式无法遮盖Consent sheets and HITL prompts render in native WeChat UI |
| 重定向泄漏Redirect leakage | 跳转将证明带往第三方域名Redirect leaks proof cross-origin | 每跳校验目标 Origin,跨域自动剥离证明Every hop verified; proofs stripped on cross-origin redirect |
隐私原则Privacy principles
- Cookie、code、授权票据、出站证明与确认票据均在底层托管,永不进入大模型上下文、页面快照或日志。Cookies, codes, grant tickets, egress proofs, and confirm tokens never enter LLM context, snapshots, or logs.
- 前置打包授权按目标 AppID 严格隔离:A 小程序获得的定位/地址授权绝不会共享给 B 小程序;换应用必须重新弹出标准授权框。Pre-authorized bundles are strictly per-AppID: location or address granted to App A is never shared with App B.
09灰度与验收Rollout & Verification
建议从只读场景起步,重点覆盖票据失效与 HITL 登录门禁两类关键验收用例。Roll out from read-only flows first, prioritizing ticket-expiry and HITL login-gate verification cases.
| 阶段Phase | 开放内容Scope | 上线前必须验证Must verify before launch |
|---|---|---|
| 1 | L1 开关 + L2 前端与 HITL 属性L1 Switch + L2 Frontend & HITL | 兼容模式下请求零变化;data-wxap-hitl="login" 的 always 与 remember 策略均无法被脚本模拟点击绕过Zero request change in compatible mode; synthetic clicks cannot bypass always or remember login gates |
| 2 | 标准前置授权 + L3/L4 代办登录Standard pre-auth + L3/L4 login | 打包授权同步覆盖登录、隐私协议与 getSetting;session_only 结束与限时票据到期准确返 40007 并能补授权恢复;手机端不受影响Bundled consent covers login, privacy & getSetting; expired/ended tickets return 40007 and recover cleanly; phone unaffected |
| 3 | 写操作与原生防伪造确认Writes & native confirm | 篡改请求体被拒;撤销/过期推送实时清理后端会话;旧 epoch 在途请求被原子拒绝Tampered payloads rejected; revoke/expiry push clears backend session; stale epochs rejected |
| 4 | 普通网页接入Regular websites | 跨域跳转移除令牌;jti 重放被拒;任务结束清除全部云端浏览环境Tokens stripped cross-origin; jti replay blocked; cloud browser profile wiped post-task |
10常见问题FAQ
前置授权框默认全部授权,会不会把支付等高风险权限也一并交出去?Does default bundled pre-auth also hand over high-risk actions like payment?
不会。默认打包授权仅包含代办登录、隐私保护指引以及 wx.getSetting 涵盖的常规项(如定位、收货地址、发票抬头等)。微信支付、生物核身与扫一扫属于平台安全底线,永远不会进入自动打包清单,必须由用户本人完成。
No. Bundled consent only covers delegated login, the privacy notice, and standard wx.getSetting items (location, address, invoice). WeChat Pay, biometrics, and QR scanning are never auto-bundled and always require the user.
开发者配置了 data-wxap-hitl-policy="remember",用户确认一次后是不是永远不再问了?With data-wxap-hitl-policy="remember", is confirmation remembered forever?
不是。记忆许可一方面按 (user, appid, hitl_key) 严格隔离,另一方面受用户前置授权有效期(TTL)约束:只要用户选择了「仅本次会话」或「限时有效」,或者在手机设置里撤销了该应用授权,记忆许可会同步失效,下次必须重新确认。此外,商家随时可把属性切回 always 强制每次点击。
No. Remembered confirmations are scoped to (user, appid, hitl_key) and bounded by the user's grant TTL: if the session ends, the TTL expires, or the user revokes access, the remembered gate resets too. Merchants can also switch to always at any time.
不改任何代码,我的服务会受影响吗?If I change nothing, will my service be affected?
不会。兼容模式下请求格式、UA 与请求头都保持不变,登录和敏感步骤会自动交给用户完成。
No. In compatible mode requests, UA, and headers stay identical, and logins or sensitive steps are handed to the user.
Agent 登录会让我手机上的登录失效吗?Will Agent login log out my phone?
不会。code2agentSession 与 code2Session 完全独立,永不签发或刷新手机端的 session_key。
No. code2agentSession is independent of code2Session and never issues or refreshes phone session_key.
为什么微信生态应用不需要 RFC 9421 或 JWT?Why don't WeChat apps need RFC 9421 or JWT?
云运行时由微信第一方托管,微信同时掌控网络出站与服务端核验接口,因此用一次性 WeChat-Agent-Proof 即可完成强认证。只有无法调用微信服务端的普通网页才使用 Ed25519 JWS。
WeChat operates both the Cloud Runtime egress and the verification server, so a one-time WeChat-Agent-Proof suffices. Only regular websites use Ed25519 JWS.