微信 Personal Agent 认证协议 · 草案 v1.0 WeChat Personal Agent Auth Protocol · Draft v1.0
协议标准草案 v1.0 · 2026 年 11 月 Protocol Standard Draft v1.0 · November 2026

微信 Personal Agent 认证协议 WeChat Personal Agent Authentication Protocol

让用户的 Agent 安全地替用户办事,而不必交出账号 Let a user's Agent act on their behalf — without handing over the account

本协议定义个人 Agent 在微信托管云运行时中访问小程序、公众号网页、小程序 <web-view> 与普通网页时,如何被用户授权、如何向开发者证明身份,以及如何在关键时刻把控制权交还给用户。 This standard defines how a Personal Agent running in WeChat's managed Cloud Runtime is authorized by the user, proves itself to developers, and hands control back to the user at critical moments — across Mini Programs, Official Account pages, Mini Program <web-view>, and regular websites.

1个新前端接口 wx.agentLoginnew frontend API, wx.agentLogin
0行加密代码(微信生态应用)lines of crypto for WeChat apps
4类页面形态统一覆盖page surfaces, one model
3层人工确认与接管levels of human confirmation

00一分钟读懂The Protocol in a Minute

用户让个人 Agent 替自己办事,例如查订单、填退货单。Agent 在微信托管的隔离环境里打开你的小程序或网页。本协议回答一个问题:你的服务如何确认「这是某位用户授权的 Agent,正在授权范围内操作」,而无需把用户的账号交给大模型。 A user asks their Personal Agent to get something done — check an order, draft a return. The Agent opens your Mini Program or website inside an isolated environment managed by WeChat. This protocol answers one question: how can your service confirm "this is an Agent authorized by this user, acting within that authorization" — without the user's account ever being handed to an LLM.

全景图Overview用户在手机上一次授权,小微在微信云端操作多个小程序与网页;运行时统一管理授权票据、控制权、人工确认与可信出站,商家后端通过 wx.agentLogin 换码即可识别。The user grants once on their phone; Xiaowei operates multiple Mini Programs and web pages in WeChat's cloud. The runtime manages grant tickets, control, human confirmation, and trusted egress; merchants recognize the Agent through a single wx.agentLogin exchange.

一次代办的五个步骤Five steps of a delegated task

01

用户授权User authorizes

用户在授权框里一次确认:登录、隐私保护指引、位置与地址等,默认全部允许。

One tap on the authorization sheet: login, privacy policy, location, address — all allowed by default.

02

云端运行Runs in cloud

Agent 在隔离的云运行时中打开你的页面,存储按用户与任务隔离。

The Agent opens your page in an isolated Cloud Runtime, with storage isolated per user and task.

03

页面取码Page gets a code

页面调用 wx.agentLogin(),拿到一次性 code。

Your page calls wx.agentLogin() and receives a one-time code.

04

后端换码Backend exchanges

后端把 code 和微信附加的证明交给微信核验,得到用户 openid 与授权范围。

Your backend sends the code and WeChat's attached proof to WeChat, receiving the user's openid and scopes.

05

受限会话Scoped session

你为 Agent 签发独立的受限会话;付款等高风险动作仍由用户本人确认。

You issue the Agent a separate scoped session; high-risk actions like payment still need the user.

三方各自负责什么Who is responsible for what

用户User
持有Holds
主账号与最终决定权The master account and the final say
Agent 拿不到Agent never sees
手机上的登录态、支付密码Phone login sessions, payment PINs
随时可以Can always
接管操作或撤销任务Take over or revoke the task
微信云运行时WeChat Cloud Runtime
负责Provides
隔离环境、授权记录、出站证明Isolation, grant records, egress proofs
默认不信任Treats as untrusted
大模型输出与网页脚本LLM output and page scripts
保证Guarantees
撤销后立即失效Revocation takes effect immediately
开发者Developer
获得Receives
可核验的用户身份与授权范围Verifiable user identity and scopes
需要做Needs to
一次服务端换码调用Make one server-side exchange call
不需要Doesn't need to
实现签名算法或管理密钥Implement signatures or manage keys

你需要做什么:四个接入级别What you need to do: four integration levels

接入级别描述你愿意为 Agent 做多少适配。级别越高,你对 Agent 的判断越精细、能开放的业务越多;任何级别都不会改变普通用户的体验。「前端适配」和「后端识别」可以单独选择,「代办登录」需要先登记后端接口。 An integration level describes how much you adapt for Agents. Higher levels let you make finer decisions about Agents and open more business actions; no level changes the experience for regular users. "Frontend-aware" and "Backend-verified" can be adopted independently; "Delegated login" requires a registered backend endpoint.

接入级别Level 你要做的事What you do 工作量Effort 你获得的能力What you get
L1开关即用Switch-on在 MP 管理后台打开开关Turn on the switch in MP Admin0 行代码No codeAgent 可在隔离环境中访问页面;登录与敏感步骤自动交给用户Agents can browse your pages in isolation; logins and sensitive steps go to the user
L2前端适配Frontend-aware前端读取 Agent 状态,给敏感元素加 data-wxap-hitlRead Agent status in the frontend; mark sensitive elements with data-wxap-hitl几行前端A few lines of frontend显示 Agent 提示;指定必须本人操作的区域Show Agent hints; mark areas the user must operate
L3后端识别Backend-verified登记接口,后端核验微信附加的证明Register endpoints; verify WeChat's proof in the backend一个后端调用One backend call后端可以可信地识别 Agent 流量Your backend can reliably recognize Agent traffic
L4代办登录Delegated login接入 wx.agentLogin 与换码接口Adopt wx.agentLogin and the exchange API一个登录接口One login endpoint为 Agent 建立受限会话,代办查单、填写订单草稿等A scoped Agent session for checking orders, drafting purchases, etc.

为什么可以这么简单? 云运行时由微信第一方托管:微信同时掌握 Agent 的网络出口和服务端核验接口。因此微信生态应用不需要 RFC 9421 这类分布式签名,一次换码就能同时确认用户身份与请求来源。

Why can it be this simple? The Cloud Runtime is operated by WeChat itself, which controls both the Agent's network egress and the server-side verification API. WeChat apps therefore don't need distributed signatures like RFC 9421 — one exchange call confirms both user identity and request origin.

01双向授权Two-Way Authorization

授权有两个方向:用户 → 小微,在任务开始前一次问清、默认放行;开发者 → 小微,按业务风险决定开放到哪一级,并在需要时要求用户本人确认。两边的边界都清楚,小微才能放心地连续执行,而不是每一步都停下来询问。 Authorization flows two ways: user → Xiaowei, asked once and clearly before the task, allowed by default; and developer → Xiaowei, where the merchant decides how far to open up and when the user must confirm in person. When both boundaries are clear, Xiaowei can work continuously instead of stopping to ask at every step.

原则一Principle 1

一次问清Ask once, clearly

授权集中在任务开始前的一个授权框里,写明以谁的身份、在哪些应用、使用哪些信息、有效多久。

All grants live in one sheet before the task: on whose behalf, in which apps, using what information, for how long.

原则二Principle 2

默认放行Allow by default

授权框默认「全部允许 · 总是允许」,一次点击完成;授权范围内的步骤不再打断用户。

The sheet defaults to "Allow all · Always". One tap, and steps within that scope never interrupt the user again.

原则三Principle 3

只在三种情况中断Interrupt in only three cases

授权未覆盖、开发者要求本人确认、付款等不可委托的动作。除此之外,小微不应停下来询问。

The grant doesn't cover it, the developer requires the user, or the action can't be delegated (e.g. payment). Otherwise Xiaowei shouldn't stop to ask.

用户 → 小微:标准授权框User → Xiaowei: the standard authorization sheet

小微第一次需要进入某个小程序或公众号网页时,运行时弹出统一的授权框。授权项直接沿用开发者已经熟悉的机制:登录、隐私保护指引,以及 wx.getSetting 中的各项 scope。一个任务涉及多个应用时,合并在同一个授权框里。 The first time Xiaowei needs a Mini Program or Official Account page, the runtime shows one standard sheet. Its items reuse mechanisms developers already know: login, the privacy guide, and the scopes in wx.getSetting. A task spanning several apps gets a single combined sheet.

授权项Item对应现有机制Existing mechanism默认Default说明Notes
以你的身份登录Log in as youwx.agentLogin允许Allowed获得独立的受限会话,不影响手机上的登录A separate scoped session; the phone login is untouched
隐私保护指引Privacy guidewx.requirePrivacyAuthorize允许Allowed等同你点击「同意」,隐私接口不再拦截小微Same as tapping "Agree"; privacy-gated APIs no longer block Xiaowei
地理位置Locationscope.userLocation允许Allowed附近门店、配送范围等Nearby stores, delivery range, etc.
收货地址Shipping addressscope.address允许Allowed使用你在微信中保存的地址Uses the address saved in WeChat
发票抬头Invoice titlescope.invoiceTitle允许Allowed开具发票时使用Used when issuing invoices
手机号Phone numbergetPhoneNumber单独确认Separate consent敏感个人信息,单独展示,单独勾选Sensitive personal data; shown and consented separately
微信支付WeChat PayrequestPayment每次本人User every time不在授权范围内,每次付款都由你确认Never part of the grant; every payment is confirmed by you

只列必要的项: 授权框只展示该应用在《隐私保护指引》中声明、且本次任务确实需要的项目。默认全部允许,但每一项都清楚可见、可以取消勾选。

Only what's needed: the sheet lists only items the app declared in its privacy guide and that this task actually needs. Everything is allowed by default, but every item is visible and can be unchecked.

有效期Duration

默认Default

总是允许Always

之后访问该应用不再询问,直到你在「小微授权管理」中撤销;长期未使用(如 90 天)自动失效。

No more prompts for this app until you revoke it in Xiaowei settings; expires automatically after long inactivity (e.g. 90 days).

可选Option

一段时间For a while

例如 7 天。到期后下次使用时重新询问,并自动带入上次的选择。

E.g. 7 days. When it expires you're asked again, with your previous choices pre-filled.

可选Option

仅本次任务This task only

任务结束即失效,适合偶尔使用的应用。

Ends with the task — good for apps you rarely use.

授权票据与失效处理Grant tickets and expiry

用户的选择保存为一张授权票据,由微信服务端保管,按「用户 · 小微 · 应用」记录授权项、有效期,以及用户确认过的动作。运行时在每次需要时检查票据状态,开发者可以用 wx.getAgentSetting() 读取(形式与 wx.getSetting 一致)。 The user's choices are stored as a grant ticket on WeChat's servers, keyed by user · Xiaowei · app, recording items, duration, and actions the user has confirmed. The runtime checks it whenever needed; developers can read it with wx.getAgentSetting(), shaped like wx.getSetting.

票据状态State何时出现When运行时怎么做Runtime behaviorwx.agentLogin
有效Active已授权且未过期Granted and not expired正常执行,不打断Proceeds without interruption返回 codeReturns a code
未授权None首次进入该应用First visit to the app暂停当前步骤,向用户弹出授权框Pauses the step and shows the sheet40003 · none
已过期Expired「一段时间」或「仅本次」到期"For a while" or "This task" ended弹出续期授权框,预填上次的选择Shows a renewal sheet with previous choices40003 · expired
已撤销Revoked用户在授权管理中撤销The user revoked it in settings停止操作并清除会话;用户重新发起任务时才再次询问Stops and clears sessions; asks again only when the user starts a new task40003 · revoked
范围不足Insufficient任务需要新的授权项The task needs a new item只就新增项询问,已授权项不重复询问Asks only about the new item登录已授权则返回 codeReturns a code if login is granted

用户不在场时: 小微在后台执行时遇到未授权或过期,任务会暂停,并通过微信通知用户「小微需要你的授权才能继续」。用户点开即可在同一个授权框中完成,任务从暂停处继续。不会静默失败,也不会绕过授权继续执行。

When the user isn't around: if Xiaowei hits a missing or expired grant while running in the background, the task pauses and WeChat notifies the user: "Xiaowei needs your permission to continue." One tap opens the same sheet, and the task resumes where it stopped. It never fails silently and never proceeds without a grant.

wx.agentLogin 的三种结果The three outcomes of wx.agentLogin

登录决策Login decision页面只需处理「拿到 code」和「40003 后重试」两种情况,授权框和确认卡都由运行时负责展示。The page handles only two cases — "got a code" and "retry after 40003". The runtime shows the sheet and confirmation cards.
  1. 票据有效:静默返回 codeValid ticket: return a code silently

    不出现任何界面,页面照常把 code 发给后端换码。No UI at all; the page sends the code to its backend as usual.

  2. 没有有效票据:返回错误,同时向用户发起授权No valid ticket: return an error and ask the user

    立即返回 40003 grant_required,页面不会卡住;运行时同时弹出授权框。用户完成后触发 wx.onAgentGrantChange,页面重试即可。Returns 40003 grant_required immediately so the page never hangs, while the runtime shows the sheet. Once the user grants, wx.onAgentGrantChange fires and the page retries.

  3. 开发者要求本人确认:先由用户点击Developer requires the user: a tap comes first

    给登录按钮加 data-wxap-hitl="login"。小微点到这个按钮时,运行时在用户手机上弹出确认卡,用户确认后按钮事件才继续执行。Add data-wxap-hitl="login" to the login button. When Xiaowei reaches it, the runtime shows a confirmation card on the user's phone; the tap handler runs only after the user confirms.

开发者 → 小微:要求用户介入Developer → Xiaowei: requiring the user

商家出于风控需要,可以在任何操作或区域上要求用户本人确认或输入,包括登录按钮与整张账密表单。做法是在任意 DOM / WXML 节点层级(如整个 <form>、容器 <view>、单个 <input> 或 <button>,类似 Muse Poppy)声明人工确认属性,并沿子树向下继承生效,不需要新的接口。 For risk control, merchants can require human confirmation or direct input on any action or region — from a login button to an entire password form. Simply place the attributes on any DOM / WXML node level (a whole <form>, container <view>, single <input>, or <button>, like Muse Poppy); protection cascades down the subtree with no new API.

属性Attribute取值Values含义Meaning
data-wxap-hitllogin · submission · interaction介入类型:登录前确认、提交前确认、敏感区域/表单由用户本人完成(支持任意祖先节点声明并沿子树继承)Type: confirm before login, confirm before submit, or user-only region/form (can be placed on any ancestor and cascades to descendants)
data-wxap-confirmonce (默认)(default) · alwaysonce:用户确认一次后,在授权票据有效期内自动放行;always:每次都需要用户点击once: after one confirmation, auto-approved while the grant is valid; always: the user taps every time
data-wxap-action自定义字符串Custom string动作标识,用来记住「确认过一次」;省略时按页面路径与类型生成Action key for remembering "confirmed once"; derived from page path and type if omitted

确认与介入方式按节点类型与场景自动路由:login 与 submission 在小微对话中弹出原生确认卡,用户点一下即可,无需打开云端画面;interaction 若落在表单、容器或敏感输入框(如账密登录 <form data-wxap-hitl="interaction">),优先走 Secure Form(安全表单,Opaque Ref),敏感原文不经过大模型直接填入云端表单;仅当遇到支付密码、银行付款验证码或滑块等动态风控时,才切入实时画面人工接管。 Handling routes automatically by node type and scenario: login and submission show a one-tap native card in the Xiaowei chat; when interaction marks a form, container, or sensitive input (such as a password login <form data-wxap-hitl="interaction">), the runtime uses Secure Form (Opaque Ref) so plaintext secrets fill the cloud form without ever passing through the LLM; only payment PINs, bank OTPs, or visual captchas switch to live screen takeover.

Secure Form(安全表单):整表单 / 敏感输入框的零明文方案Secure Form: zero-plaintext filling for forms & sensitive inputs

当开发者把 data-wxap-hitl="interaction" 放在整张表单(如账密登录、实名认证)或单个敏感输入框上时,运行时在祖先链检测命中后禁止普通输入工具直接写入,改为通过 ref 关联客户端安全表单与云端 Runtime 表单: When data-wxap-hitl="interaction" appears on a form or any ancestor of an input, regular typing tools are blocked. Instead, a client Secure Form links to the cloud Runtime inputs via opaque references:

  1. Agent 观测表单结构并决定客户端安全表单Agent inspects structure & defines the client form

    Agent 读取云端受保护表单的标签与语义,调用 input_sensitive_info 决定向用户客户端展示的表单字段,并将每项精确绑定到云端真实输入框:小程序绑定 elementId,网页(公众号 / <web-view> / 普通网页)绑定 selector、frameId、文档 loader、URL 哈希与真实 DOM backendNodeId(页面导航或替换节点即失效)。The Agent reads field labels and calls input_sensitive_info to define the client form fields, binding each field to its exact cloud target: elementId for Mini Programs, or selector, frameId, document loader, URL hash, and DOM backendNodeId for web pages (invalidated on navigation or DOM replacement).

  2. 明文直入会话内存 Vault,模型仅见不透明引用Plaintext goes to Session Vault; LLM sees only an opaque ref

    客户端弹出独立安全表单(不写聊天草稿、不进聊天记录或重试队列,提交/关闭即清空)。用户提交后,原文直存会话进程内内存 Vault(无反查原文接口,会话关闭即销毁),模型仅收到随机不透明引用 [[opaque:kind:...]],敏感明文全程不进入模型上下文与日志。The client displays a standalone secure form (excluded from chat drafts, history, and retry queues; cleared on submit/close). Submitted values stay in an ephemeral in-memory Session Vault with no read-back API; the model receives only [[opaque:kind:...]].

  3. 一次性目标绑定注入与私密核对One-time target-bound injection & private check

    Agent 凭引用调用 fill_sensitive_info(ref)。运行时强校验「任务 × Runtime × 页面身份 × 目标输入框」一致,先消费销毁引用(失败或超时绝不重放),再由底层特权通道直注云端真实输入框(小程序走 mp_input,网页走服务端受控 CDP 原生输入),正常触发页面事件但不自动提交;底层私密回读仅向模型返回 filled / matched、mismatch 或 unknown。fill_sensitive_info(ref) verifies task, Runtime, page identity, and target node, consumes the one-time ref immediately (never replayed on error), and injects via privileged channel (mp_input or server-side CDP) without auto-submitting. Private verification returns only filled / matched, mismatch, or unknown.

  4. 隐私截图保护(封堵视觉通道回流)Privacy screenshot protection

    敏感值填入后若 Agent 需继续观测或截图,运行时在串行截图事务中临时对受保护 input/textarea 施加 -webkit-text-security: disc(圆点化),并隐藏已知敏感原文的 DOM 文本回显(不改真实 value),截图结束在 finally 恢复样式;期间 DOM 变更或恢复失败则丢帧或终止运行时。Subsequent screenshots run in a serialized transaction that applies -webkit-text-security: disc to protected inputs and hides known secret echoes in DOM text without mutating values, restoring styles in finally; DOM mutations or restore failures drop the frame or terminate the runtime.

Secure FormSecure Form任意层级标记 data-wxap-hitl="interaction" 的账密或敏感表单通过 ref 关联客户端安全表单与云端输入框,原文直入内存 Vault 并一次性注入,全程不经过大模型。A form or input marked data-wxap-hitl="interaction" at any tree level binds client Secure Form fields to cloud inputs via one-time ref; plaintext stays in the Session Vault and never reaches the LLM.
查看示例Show example WXML / HTML + JavaScript
<!-- 1. Button-level: ask the user once before login; remembered while the grant is valid -->
<button data-wxap-hitl="login" data-wxap-confirm="once" bindtap="login">Log in</button>

<!-- 2. Form-level (subtree inheritance): entire password form uses Secure Form (Opaque Ref) -->
<form data-wxap-hitl="interaction" action="/auth/password-login" method="post">
  <input name="username" autocomplete="username" placeholder="Account">
  <input name="password" type="password" placeholder="Password">
  <button type="submit">Sign in</button>
</form>
async function login() {
  try {
    const { code } = await wx.agentLogin();
    await api.post('/wx-agent/login', { code });
  } catch (e) {
    if (e.errCode === 40003) {
      // The runtime is already asking the user; retry once granted
      wx.onAgentGrantChange(res => res.granted && login());
    }
  }
}

后端也能强制: 前端属性决定「何时请用户确认」。如果需要服务端强制,code2agentSession 会返回 user_confirmation(是否确认、once / always、确认时间);也可以在 MP 后台把「登录需本人确认」设为首次或每次,由微信在服务端执行,修改页面无法绕过。

Enforceable on the backend: frontend attributes decide when to ask. For server-side enforcement, code2agentSession returns user_confirmation (confirmed, once / always, timestamp); or set "Login requires user confirmation" to first-time or every-time in MP Admin, enforced by WeChat's servers and impossible to bypass by editing the page.

让人和小微的边界一目了然Making the human–Agent boundary obvious

时刻Moment用户看到什么What the user sees
授权时Granting授权框写明「小微将以你的身份」使用哪些应用、哪些信息、有效多久The sheet states "Xiaowei will act as you" — which apps, which information, for how long
执行中Running小程序与网页顶部显示「小微正在操作」;用户接管后变为「你正在操作」Pages show "Xiaowei is operating"; after takeover, "You are operating"
需要确认时Confirming确认卡标明发起方、应用、动作和关键参数The card names the requester, app, action, and key parameters
事后Afterwards「我 → 设置 → 小微授权管理」列出所有授权,可随时查看与撤销"Me → Settings → Xiaowei permissions" lists every grant for review or revocation

02适用范围与接入级别Scope & Integration Levels

四类页面形态共享同一套身份模型,区别只在于「如何证明页面归属」和「后端如何核验」。 All four surfaces share one identity model. They differ only in how page ownership is proven and how the backend verifies requests.

页面形态Surface 前端接入Frontend 归属证明Ownership proof 后端核验Backend verification
小程序Mini Program基础库 wx.*Base library wx.*代码包签名中的 AppIDAppID in the signed packageWeChat-Agent-Proof → 微信服务端WeChat server
公众号网页Official Account H5JS-SDK 扩展JS-SDK extensionwx.config(同源持久有效)wx.config (persists per origin)WeChat-Agent-Proof → 微信服务端WeChat server
小程序 <web-view>MP <web-view>直接使用 H5 JS-SDKH5 JS-SDK directly页面自身的 wx.configThe page's own wx.config与公众号网页相同Same as Official Account H5
普通网页Regular website无需 SDKNo SDK/.well-known/wx-agent.jsonWeChat-Agent-Token → 本地验签local verification

接入级别见「一分钟读懂」:前端适配与后端识别可以分开接入,未接入的商家始终保持原有行为。兼容模式下微信不添加任何请求头,也不修改 UA、URL 或请求体。 See the integration levels above: frontend awareness and backend verification can be adopted separately, and merchants who opt out keep their existing behavior. In compatible mode WeChat adds no request headers and never modifies the UA, URL, or body.

03身份与会话模型Identity & Session Model

同一个云端页面可以先由 Agent 操作,再交给用户——环境没变,控制权变了。因此协议把四件事分开判断。 The same cloud page can be driven by the Agent, then handed to the user — the environment stays, the controller changes. So the protocol evaluates four things separately.

判断Question 字段Fields 由谁给出Source 用来做什么Used for
在哪里运行Where is it running?env微信运行平台WeChat runtime选择对应的风控策略Choosing a risk policy
谁在操作Who is in control?controller, control_epoch微信控制面WeChat control plane区分 Agent 与用户;每次接管或撤销都会递增 epoch,让旧请求失效Agent vs. user; the epoch increments on every takeover or revoke, invalidating stale requests
代表哪位用户For which user?openid, agent_openid, agent_session_id微信身份服务WeChat identity直接映射到你已有的用户账号,不需要新建账号Maps straight to your existing user account — no new accounts
能做什么What is allowed?scopes, grant_ref, confirm_token用户授权 ∩ 商家策略 ∩ 平台规则User grant ∩ merchant policy ∩ platform rules决定这一次动作能否执行Deciding whether this action may proceed
  • openid:用户在当前 AppID 下的既有身份。openid: the user's existing identity under your AppID.
  • agent_openid:用户创建的某个 Agent 在你这里的不透明标识,仅用于展示和审计,不能跨应用关联,本身不赋予任何权限。agent_openid: an opaque ID for one of the user's Agents as seen by your app — for display and audit only, never linkable across apps, and grants nothing on its own.
  • agent_session_id:本次任务的执行会话,随任务开始与结束。agent_session_id: the execution session of this task, created and ended with it.

保守归因: 后台定时请求、跨越接管时刻的异步请求等无法可靠归因的流量,一律标记为 controller: "unknown"。不可逆操作不能只凭「当前是用户在操作」放行,必须核验用户的显式确认。

Conservative attribution: traffic that can't be reliably attributed — background timers, async requests that cross a takeover — is marked controller: "unknown". Irreversible actions must never be allowed just because "the user seems to be in control"; require explicit user confirmation.

04前端与 JS-SDK 接口Frontend & JS-SDK API

小程序与 H5 使用同一组扁平的 wx.* 接口,命名风格与 wx.login、wx.openAddress 一致,同时支持回调与 Promise。 Mini Programs and H5 share one set of flat wx.* APIs, named like wx.login and wx.openAddress, supporting both callbacks and Promises.

接口一览API overview

接口API H5 是否需要 wx.configH5 needs wx.config? 作用Purpose
wx.getAgentContext不需要No读取运行环境、当前操作方与 epoch,用于界面提示;不返回任何凭证。Reads the environment, current controller, and epoch for UI hints. Returns no credentials.
wx.onAgentControlChange不需要No监听接管、归还、暂停、撤销与结束。Listens for takeover, handback, pause, revoke, and end.
wx.requestUserTakeover不需要No主动暂停 Agent,请用户完成验证码等步骤。Pauses the Agent and asks the user to finish a step such as a captcha.
wx.agentLogin需要(每个 Origin 一次)Yes (once per origin)获取一次性 code,用于建立 Agent 会话。前端不能指定权限范围。Gets a one-time code to establish an Agent session. The frontend cannot request scopes.
wx.getAgentSetting不需要No读取授权票据的状态、有效期与各授权项,形式与 wx.getSetting 一致。Reads the grant ticket's state, duration, and items, shaped like wx.getSetting.
wx.onAgentGrantChange不需要No授权完成、过期或撤销时触发;收到授权后重试 wx.agentLogin。Fires when a grant is given, expires, or is revoked; retry wx.agentLogin once granted.
<wx-open-agent-confirm>需要(openTagList)Yes (openTagList)防伪造的确认按钮,弹出微信原生确认页。A tamper-proof confirm button that opens a native WeChat confirmation sheet.
  • 向后兼容:只读接口不需要 wx.config,前端可以零后端成本接入。Backward compatible: read-only APIs work without wx.config, so the frontend can adopt them with zero backend work.
  • SPA 友好:wx.config 在同一 Origin 内持久有效,前端路由切换无需重新签名。SPA-friendly: wx.config persists within an origin, so client-side route changes need no re-signing.
  • <web-view>:嵌入的 H5 直接使用 JS-SDK,不经过小程序消息通道。<web-view>: embedded H5 pages use the JS-SDK directly, not the Mini Program message channel.
查看 H5 接入示例Show H5 integration example JavaScript
// Read-only awareness: no wx.config required
const ctx = await wx.getAgentContext();
if (ctx.controller === 'agent') showAgentBanner();
wx.onAgentControlChange(e => updateBanner(e.controller));

// Agent login: wx.config once per origin
wx.config({ appId, timestamp, nonceStr, signature,
  jsApiList: ['agentLogin'], openTagList: ['wx-open-agent-confirm'] });

wx.ready(async () => {
  const { code } = await wx.agentLogin({ state: csrfToken });
  await fetch('/api/wx-agent/login', {
    method: 'POST',
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ code, state: csrfToken })
  });
});

wx.agentLogin 失败时When wx.agentLogin fails

所有失败都会返回明确原因,并且不影响页面原有的登录方式。Every failure returns a clear reason and leaves the page's existing login untouched.

errCode原因Reason建议处理Suggested handling
40001not_agent_runtime当前是普通微信,沿用原有登录Regular WeChat client — use your existing login
40002not_agent_controller用户正在操作,不建立 Agent 会话The user is in control — don't create an Agent session
40003grant_required没有有效授权票据(reason:none / expired / revoked)。运行时已向用户发起授权,监听 wx.onAgentGrantChange 后重试No valid grant ticket (reason: none / expired / revoked). The runtime is already asking the user; retry on wx.onAgentGrantChange
40004endpoint_not_registered未在 MP 后台登记换码接口No exchange endpoint registered in MP Admin
40005config_requiredH5 尚未完成 wx.configH5 hasn't completed wx.config

三层人工确认Three levels of human confirmation

从「零代码标记」到「防伪造确认」,按业务风险选择。From zero-code markup to tamper-proof confirmation — choose by business risk.

Level 1

任意层级标记Subtree attribute

可将 data-wxap-hitl 挂在任意 DOM / WXML 层级(整张 <form>、容器、输入框或按钮,沿子树继承)。interaction 标在表单/输入框上自动走 Secure Form(明文不经模型);login 与 submission 走原生确认卡(data-wxap-confirm="once | always")。普通网页同样适用。

Place data-wxap-hitl on any DOM / WXML ancestor (entire <form>, container, input, or button; cascades down the subtree). interaction on forms/inputs uses Secure Form (no plaintext to LLM); login and submission show a native confirmation card (data-wxap-confirm="once | always"). Works on regular websites too.

Level 2

主动接管Imperative takeover

页面在运行时调用 wx.requestUserTakeover(),适合验证码、风控挑战等动态出现的场景。

Call wx.requestUserTakeover() at runtime — ideal for captchas or risk challenges that appear dynamically.

Level 3

防伪造确认Tamper-proof confirm

<wx-open-agent-confirm> 弹出微信原生确认页,页面脚本无法伪造点击,也无法用样式遮挡。确认后得到绑定订单内容的 confirmToken。

<wx-open-agent-confirm> opens a native WeChat sheet that page scripts can't click or visually cover. Confirmation yields a confirmToken bound to the order content.

查看三层确认示例Show confirmation examples HTML
<!-- Level 1: subtree-scoped markup (form-level Secure Form, input, or button) -->
<form data-wxap-hitl="interaction" action="/auth/login" method="post">
  <input name="username" placeholder="Username">
  <input name="password" type="password" placeholder="Password">
  <button type="submit">Sign in</button>
</form>
<input name="sms_code" data-wxap-hitl="interaction">
<button type="submit" data-wxap-hitl="submission" data-wxap-confirm="always">Submit refund</button>

<!-- Level 3: native confirmation -->
<wx-open-agent-confirm
  id="confirm"
  action-id="order_8891"
  summary="Green Tea Gift Box · ¥128.00"
  payload-digest="sha256:9f86d081...">
</wx-open-agent-confirm>

<script>
  // Level 2: imperative takeover
  wx.requestUserTakeover({ mode: 'verification', reason: 'Please finish the captcha' });

  // Level 3: receive the confirmation token
  document.getElementById('confirm').addEventListener('confirm', e => {
    submitOrder(e.detail.confirmToken);
  });
</script>

已有 JS-SDK 接口在云端的行为Existing JS-SDK APIs in the cloud

类别Category接口APIs行为Behavior
按预授权提供Pre-authorizedopenAddress, getLocation在任务授权范围内直接提供,否则询问用户Provided if within the task grant; otherwise asks the user
必须本人User onlychooseWXPay, scanQRCode从不自动执行,转交用户或手机Never automated; handed to the user or phone
安全兼容Safe emulationpreviewImage, closeWindow, getNetworkType正常返回,保证已有页面不报错Return normally so existing pages don't break
Agent 期间禁用Disabled for AgentstartRecord, addCard, 分享类sharing返回 unsupported_in_agent_runtimeReturn unsupported_in_agent_runtime

05认证流程与服务端接口Flows & Server APIs

小程序、公众号网页与 <web-view> 使用完全相同的登录流程:一次取码,一次换码。 Mini Programs, Official Account pages, and <web-view> share one login flow: get a code once, exchange it once.

图 1Figure 1单码登录。微信出站层在请求到达你的接口前附加 WeChat-Agent-Proof,你的后端把它与 code 一并交给微信核验。Single-code login. WeChat's egress attaches WeChat-Agent-Proof before the request reaches you; your backend forwards it with the code for verification.

账号不是按 openid 关联时When accounts aren't keyed by openid

如果站点使用账密、手机号或企业 SSO 等自有账号体系,支持两种方式:① Secure Form(安全表单):在账密/短信登录 <form> 上标 data-wxap-hitl="interaction",用户通过客户端安全表单输入,明文直入会话内存 Vault 并通过一次性 ref 注入云端表单,不经过大模型;② 手机原站绑定:微信请用户在手机上完成一次原站登录(适合企业 SSO / 多因素认证),商家把验证后的账号关联到云端登录事务,云端随后用 Agent code 完成绑定并获得独立受限会话,手机 Cookie 不会被复制到云端。 If your site uses password, phone, or enterprise SSO accounts, two safe options apply: ① Secure Form: mark the login <form data-wxap-hitl="interaction"> so user credentials go from the client form straight into the Session Vault and inject via one-time ref without touching the LLM; ② Phone-bound sign-in (ideal for SSO / MFA): the user signs in once on their phone, you link the account to the cloud transaction, and the cloud gets its own scoped session without copying phone cookies.

高风险操作High-risk actions

下单、退款等操作需要用户在原生确认页核对内容,后端再确认提交内容与用户看到的完全一致。 For purchases and refunds, the user reviews the content on a native sheet, and your backend confirms the submission matches exactly what the user saw.

图 2Figure 2确认与撤销。如果用户在提交途中接管或撤销,epoch 已经变化,在途请求会被拒绝。Confirmation and revocation. If the user takes over or revokes mid-flight, the epoch has changed and the in-flight request is rejected.

服务端接口Server APIs

code2agentSession

登录时调用。核验并消费 code 与证明,返回用户身份与授权范围。不会签发或刷新用户手机上的 session_key。Called at login. Verifies and consumes the code and proof, returning identity and scopes. Never issues or refreshes the user's phone session_key.

字段Field方向Direction说明Description
js_code请求Request前端 wx.agentLogin() 得到的 codeThe code from wx.agentLogin()
proof请求Request请求头 WeChat-Agent-Proof 的值Value of the WeChat-Agent-Proof header
target_uri请求Request收到该请求的接口地址The endpoint URL that received the request
openid返回Response用户在当前 AppID 下的身份The user's identity under your AppID
agent_session_id返回Response本次任务的执行会话This task's execution session
scopes返回Response允许的操作,例如 order:readAllowed actions, e.g. order:read
control_epoch返回Response当前控制代次,后续请求不得低于此值Current control epoch; later requests must not be older
expires_at返回Response会话最长有效期Maximum session lifetime
user_confirmation返回Response登录前是否经用户确认、确认方式(once / always)与时间Whether the user confirmed before login, mode (once / always), and time
grant返回Response授权票据的有效期类型(always / duration / task)与到期时间Grant duration type (always / duration / task) and expiry
查看完整请求与响应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_v1_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_20261120_x9k2",
  "grant_ref": "grant_88219a",
  "scopes": ["catalog:read", "order:read", "order:draft"],
  "env": "cloud_browser",
  "controller": "agent",
  "control_epoch": 1,
  "state": "csrf_9f2a8c",
  "expires_at": 1763612767
}

verify_proof

高风险写操作时调用。确认证明有效、授权仍然有效、epoch 未过期,以及提交内容与用户确认的内容一致。Called for high-risk writes. Confirms the proof is valid, the grant is still active, the epoch is current, and the submission matches what the user confirmed.

字段Field方向Direction说明Description
proof请求Request本次请求附带的 WeChat-Agent-ProofThe WeChat-Agent-Proof on this request
confirm_token请求Request用户在原生确认页确认后得到的票据Token from the user's native confirmation
body_sha256请求Request请求体的 SHA-256,用于防篡改SHA-256 of the request body, to detect tampering
valid, grant_active返回Response证明是否有效、授权是否仍有效Whether the proof and grant are still valid
payload_digest_matched返回Response提交内容是否与用户确认的内容一致Whether the submission matches what the user confirmed
control_epoch返回Response最新控制代次Latest control epoch

撤销事件推送Revocation event push

用户撤销任务或接管时,微信通过现有的 MP 消息推送地址发送 agent_session_revoked 事件(包含 AgentSessionId、ControlEpoch 与原因),收到后立即作废对应会话。When the user revokes or takes over, WeChat sends an agent_session_revoked event (with AgentSessionId, ControlEpoch, and reason) to your existing MP message push URL. Invalidate the session on receipt.

06开发者如何验证How Developers Validate

WeChat-Agent-Proof 与 WeChat-Agent-Token 均由微信云运行时的出站层(Egress Layer,位于执行沙盒之外)在请求离开微信网络边界时自动注入——页面脚本和大模型永远读不到、也改不了。微信生态应用无需写任何加密代码,只需把 Proof 转交给微信服务端;普通网页用标准 JWT 库本地验签。 Both WeChat-Agent-Proof and WeChat-Agent-Token are injected at the network boundary by WeChat's Egress Layer (outside the execution sandbox) — invisible and unmodifiable to page scripts and the LLM. WeChat apps write no cryptography and simply forward the proof to WeChat; regular websites verify locally with any standard JWT library.

WeChat-Agent-ProofWeChat-Agent-Token
适用于Used by小程序、公众号网页、<web-view>(微信生态内)Mini Programs, OA pages, <web-view> (inside WeChat)普通网页(微信生态外,无 AppID、无法调微信服务端)Regular websites (outside WeChat, no AppID)
何时附加Attached when持有有效授权票据且请求命中 MP 后台登记的接口Active grant ticket & request hits an MP-registered endpoint持有有效授权票据且请求命中 wx-agent.json 声明的路径Active grant ticket & request hits a declared wx-agent.json path
出站层如何生成How Egress mints it出站代理拦截出站请求,向微信控制面注册一条 60 秒单次消费的状态记录,强绑定 appid、agent_session_id、grant_ref、control_epoch、method、target_uri、可选 body_sha256 与 user_confirmation,将不透明句柄注入请求头Egress intercepts the outbound request, registers a 60 s single-use state record on WeChat's control plane binding appid, agent_session_id, grant_ref, control_epoch, method, target_uri, optional body_sha256 & user_confirmation, and injects the opaque handle出站签名服务将 iss、aud(网站 Origin)、exp、jti(防重放 ID)、htm(HTTP 方法)、htp(路径)与可选 body_sha256 组装为结构化 JSON,用微信 Ed25519 私钥实时签名为自包含 JWS 注入请求头Egress packs iss, aud (site origin), exp, jti, htm (method), htp (path), and optional body_sha256 into clean JSON and signs it on the fly with WeChat's Ed25519 private key as a self-contained JWS
格式与时效Format & lifetime不透明字符串,60 秒,单次消费即作废Opaque string, 60 s, single useEd25519 签名的 JWS,60 秒,靠 jti 缓存防重放Ed25519-signed JWS, 60 s, replay-checked via jti
如何验证How to verify转交微信服务端接口(code2agentSession / verify_proof),由微信原子核验并消费Forward to WeChat server API (code2agentSession / verify_proof) for atomic verification用缓存的微信公钥(JWKS)本地离线验签,并校验目标路径与 jti 唯一性Verify offline with cached WeChat JWKS, checking target path and jti uniqueness

出站层的三条边界保证: ① 沙盒不可见:证明头在沙盒外部注入,XSS 与大模型既读不到也无法构造;② 按需附加:未登记的普通接口不添加任何请求头,零兼容风险;③ 逐跳防泄漏:遇到 HTTP 3xx 重定向时每跳重新校验目标 Origin,跨域自动剥离证明头;票据过期、撤销或接管后立即停止附加。

Three egress guarantees: ① Invisible to the sandbox — injected outside the sandbox so XSS and the LLM can neither read nor forge it; ② Opt-in only — unregistered endpoints get zero extra headers; ③ Hop-by-hop protection — redirects are re-checked on every hop and proofs are stripped cross-origin, and injection stops immediately on expiry, revocation, or takeover.

务必拒绝而非降级: 任何人都可以伪造同名请求头。在要求验证的接口上,缺少证明、验证失败、重放或 epoch 过期时,必须返回 401 / 403,不能退回为普通用户会话。

Reject, never downgrade: anyone can forge a header with the same name. On endpoints that require verification, a missing proof, failed check, replay, or stale epoch must return 401 / 403 — never fall back to a regular user session.

场景 A:登录时Scenario A: at login

  1. 读取证明Read the proof

    从请求头取出 WeChat-Agent-Proof,从请求体取出 code;任一缺失则拒绝。Take WeChat-Agent-Proof from the header and the code from the body; reject if either is missing.

  2. 交给微信核验Let WeChat verify

    调用 code2agentSession,一次完成 code 与证明的核验。Call code2agentSession; it verifies the code and the proof in one step.

  3. 签发受限会话Issue a scoped session

    用 openid 找到已有用户,签发与普通登录态分开的 HttpOnly Cookie,并记录 scopes 与 epoch。Look up the user by openid, issue an HttpOnly cookie separate from normal sessions, and store scopes and epoch.

查看示例代码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();

  const user = await users.findByOpenId(wx.openid);
  const sid = await sessions.create({
    userId: user.id,
    type: 'agent',
    agentSessionId: wx.agent_session_id,
    scopes: wx.scopes,
    epoch: wx.control_epoch
  });

  res.cookie('wx_agent_sid', sid, { httpOnly: true, secure: true, sameSite: 'lax' });
  res.json({ ok: true });
});

场景 B:高风险写操作Scenario B: high-risk writes

  1. 普通读请求直接放行Plain reads pass through

    浏览、查询只需校验受限会话 Cookie,不需要额外调用微信。Browsing and queries only need the scoped session cookie — no extra WeChat call.

  2. 计算请求体摘要Hash the request body

    对原始请求体计算 SHA-256。Compute SHA-256 over the raw request body.

  3. 调用 verify_proofCall verify_proof

    提交证明、确认票据与摘要;仅当授权有效、epoch 未过期且内容一致时执行,并使用幂等键防止重复提交。Submit the proof, confirmation token, and digest. Proceed only if the grant is active, the epoch is current, and content matches; use an idempotency key against duplicates.

查看示例代码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

  1. 验证签名Verify the signature

    用微信公开的 JWKS 验证 Ed25519 签名、签发方、受众(你的 Origin)与有效期。Verify the Ed25519 signature, issuer, audience (your origin), and expiry against WeChat's public JWKS.

  2. 防止重放Prevent replay

    把 jti 写入缓存(120 秒),已存在则拒绝。Store jti in a cache for 120 s; reject if it already exists.

  3. 核对请求目标Check the target

    确认令牌中的方法、路径(以及可选的请求体摘要)与当前请求一致。Confirm the method, path (and optional body digest) in the token match the current request.

查看示例代码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 标准即可接入。 Sites without an Official Account or Mini Program need no SDK — only web standards.

基础 · 无需改动Baseline · no changes

什么都不做Do nothing

Agent 以普通浏览器身份访问,不加任何请求头。遇到登录或支付时交给用户,任务结束后清除整个浏览环境。

The Agent browses like a normal browser with no extra headers. Logins and payments go to the user, and the whole browser profile is wiped after the task.

声明 · 一个静态文件Declare · one static file

放一个静态文件Host one static file

在 /.well-known/wx-agent.json 声明允许和禁止的页面;在敏感元素上加 data-wxap-hitl。不需要写 JavaScript。

Declare allowed and disallowed pages in /.well-known/wx-agent.json; add data-wxap-hitl to sensitive elements. No JavaScript needed.

识别 · 后端验签Verify · backend check

识别 Agent 请求Recognize Agent requests

为声明的路径接收 WeChat-Agent-Token。签名对象是干净的 JSON,不会因 CDN 或反向代理改写请求头而失效。

Receive WeChat-Agent-Token on declared paths. It signs clean JSON, so it survives CDNs and reverse proxies rewriting headers.

wx-agent.json 字段wx-agent.json fields

字段Field说明Description
policy.allowAgent 可以自动访问的路径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 that receive WeChat-Agent-Token, optionally with a body digest
auth.agent_login_urlAgent 登录入口,用户在此完成登录后签发受限 CookieAgent login entry; after the user signs in here, a scoped cookie is issued
查看完整示例Show full example JSON
{
  "version": "1.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"
  }
}
图 3Figure 3普通网页的发现、验证与登录。用户的密码与验证码只在用户和网站之间传递,不会进入大模型。Discovery, verification, and login for regular websites. Passwords and codes travel only between the user and the site, never through the LLM.

08安全架构与威胁分析Security & Threats

核心原则是委托权限而不交出凭证。大模型和网页脚本都被视为不可信;授权、证明与确认只发生在微信原生界面、控制面和出站层这三个可信位置。 The core principle is delegating authority without surrendering credentials. Both the LLM and page scripts are untrusted; grants, proofs, and confirmations happen only in three trusted places: WeChat's native UI, the control plane, and the egress layer.

图 4Figure 4三方信任边界。橙色虚线区域是不可信的执行沙盒,所有凭证与证明都在它之外产生。Tri-party trust boundaries. The dashed orange area is the untrusted sandbox; every credential and proof is produced outside it.

Agent 如何在用户与开发者之间建立信任How the Agent earns trust between user and developer

  1. 用户划定边界The user sets the boundary

    任务开始前,用户在微信原生卡片上确认商家、数据和动作。授权记录保存在微信服务端,Agent 无法修改。Before the task, the user confirms merchant, data, and actions on a native WeChat card. The grant lives on WeChat's servers; the Agent can't alter it.

  2. 页面证明归属The page proves ownership

    小程序靠代码包签名,H5 靠 wx.config,普通网页靠 wx-agent.json。恶意页面无法冒用其他商家的身份获取 code。Mini Programs via package signing, H5 via wx.config, regular sites via wx-agent.json. A malicious page can't obtain codes under another merchant's identity.

  3. 微信向开发者担保WeChat vouches to the developer

    code 绑定到具体的执行会话,出站层在网络边界附加证明。开发者换码后可以确认:这个请求来自微信托管环境,代表这位用户,在有效授权之内。The code is bound to one execution session, and the egress layer attaches a proof at the network boundary. After exchange, the developer knows: this request comes from WeChat's managed environment, for this user, within a live grant.

  4. 用户确认关键内容The user confirms what matters

    高风险操作的金额、商品与收件人在原生确认页展示,提交时后端核对内容完全一致,杜绝「看到的和提交的不一样」。For high-risk actions, amount, items, and recipient appear on a native sheet, and the backend checks the submission is identical — what the user saw is what gets submitted.

  5. 随时收回权限Authority can be withdrawn instantly

    用户接管或撤销时,epoch 递增、出站层停止附加证明、云端清除 Cookie,并向开发者推送撤销事件,在途请求全部失效。On takeover or revoke, the epoch increments, egress stops attaching proofs, cloud cookies are wiped, and a revocation event is pushed — every in-flight request fails.

威胁与防御Threats and defenses

威胁Threat攻击方式Attack防御Defense
账密/敏感表单泄漏Form secret leakage用户在聊天里输入密码、填入表单后被模型截屏读取,或引用被错填到其他输入框Passwords enter chat/LLM, leak via screenshots, or get filled into a different inputSecure Form(Opaque Ref):原文直入内存 Vault,模型仅拿 [[opaque:...]];引用强绑定页面与目标节点且单次消费;截图事务自动圆点遮罩并隐藏回显Secure Form (Opaque Ref): plaintext stays in memory Vault, LLM gets only [[opaque:...]]; one-time ref bound to page & node; screenshots mask inputs & echoes
code 被盗用Stolen codeXSS 窃取 code 后从外部提交XSS steals the code and submits it from outside外部请求没有出站层附加的证明,换码失败External requests lack the egress proof; exchange fails
脚本或提示注入Script / prompt injection恶意内容诱导 Agent 越权或窃取会话Malicious content tricks the Agent or steals the sessionCookie 为 HttpOnly;前端不能指定权限;写操作需要脚本不可见的证明HttpOnly cookies; frontend can't set scopes; writes need proofs invisible to scripts
撤销竞态Revocation race撤销的瞬间仍有请求在途A request is in flight at the moment of revocationepoch 递增后旧请求被原子拒绝,配合幂等键Once the epoch increments, stale requests are atomically rejected; idempotency keys help
伪造请求头Forged headers外部爬虫伪造证明头External bots forge the proof header证明必须经微信或公钥验证,失败即拒绝Proofs must be verified by WeChat or public key; failures are rejected
重定向泄漏Redirect leakage通过跳转把证明带到其他域名A redirect carries the proof to another domain每一跳都校验目标,跨域时自动移除证明Every hop is checked; proofs are stripped on cross-origin redirects
会话互相影响Session interferenceAgent 登录导致手机端掉线Agent login logs the phone outAgent 会话独立,不刷新 session_keyAgent sessions are separate and never refresh session_key
点击劫持Clickjacking用样式遮挡确认按钮,误导金额CSS overlays mislead the user about the amount确认在微信原生界面完成,页面样式无法覆盖Confirmation happens in native WeChat UI that page CSS can't cover
跨应用追踪Cross-app tracking通过 Agent 标识关联用户Correlating users via an Agent IDagent_openid 按应用隔离,重建后更换agent_openid is per-app and rotates on re-creation

隐私原则Privacy principles

  • Cookie、code、证明与确认票据由底层托管,不进入大模型的输入、页面快照或日志。Cookies, codes, proofs, and confirmation tokens are handled below the model and never enter LLM input, page snapshots, or logs.
  • 预先授权的手机号和地址只用于指定商家和用途;换商家或扩大用途时重新询问用户,即使在完全授权模式下也是如此。Pre-authorized phone numbers and addresses are used only for the stated merchant and purpose; a new merchant or wider purpose asks the user again, even in full-authorization mode.

09灰度与验收Rollout & Verification

建议从只读场景开始,逐步开放写操作。Start with read-only scenarios and open writes gradually.

阶段Phase开放内容Scope上线前必须验证Must verify before launch
1L1 开关即用 + L2 前端适配L1 Switch-on + L2 Frontend-aware开关前后请求完全一致;只读接口无需 wx.config,路由切换后监听仍有效Requests are identical before/after the switch; read-only APIs work without wx.config and survive route changes
2L3 后端识别 + L4 代办登录(只读权限)L3 Backend-verified + L4 Delegated login (read-only)被盗 code 无法从外部换取;手机端不受影响;撤销事件按时生效Stolen codes can't be exchanged externally; the phone is unaffected; revocation takes effect on time
3写操作与人工确认Writes and confirmation篡改请求体被拒;脚本无法触发确认;旧 epoch 请求被拒Tampered bodies are rejected; scripts can't trigger confirmation; stale epochs are rejected
4普通网页Regular websites跨域跳转移除令牌;重放被拒;任务结束后浏览环境被清除Tokens are stripped across origins; replays are rejected; the browser profile is wiped after the task

10常见问题FAQ

默认「总是允许」会不会不安全?Isn't "Always allow" by default risky?

默认放行的是登录与应用已声明的信息,而且每一项都在授权框里清楚可见。付款、敏感个人信息和开发者要求确认的动作始终需要你本人;授权可以随时在「小微授权管理」中撤销,长期不用会自动失效。

What's allowed by default is login plus information the app has declared, and every item is clearly shown on the sheet. Payments, sensitive personal data, and developer-required confirmations always need you; grants can be revoked anytime in Xiaowei settings and expire after long inactivity.

不改任何代码,我的服务会受影响吗?If I change nothing, will my service be affected?

不会。兼容模式下请求格式、UA 与请求头都保持不变,登录和敏感步骤会交给用户完成。

No. In compatible mode the request format, UA, and headers stay the same, and logins and sensitive steps are handed to the user.

为什么不用 RFC 9421 或 JWT?Why not RFC 9421 or JWT?

云运行时由微信第一方托管,微信同时掌握出站与服务端核验,因此可以用一次性证明代替分布式签名。只有无法调用微信服务端的普通网页,才使用 Ed25519 JWS。

WeChat operates the Cloud Runtime and controls both egress and server-side verification, so a one-time proof replaces distributed signatures. Only regular websites, which can't call WeChat's server, use Ed25519 JWS.

Agent 登录会让我手机上的登录失效吗?Will Agent login log out my phone?

不会。code2agentSession 与 code2Session 相互独立,不会签发或刷新 session_key。

No. code2agentSession is independent of code2Session and never issues or refreshes session_key.

小程序 <web-view> 里的网页怎么接入?How do pages inside a Mini Program <web-view> integrate?

与公众号网页相同,直接使用 JS-SDK,无需经过小程序的消息通道。

Exactly like Official Account pages — use the JS-SDK directly, without the Mini Program message channel.

选择了完全授权,为什么有些步骤还要我操作?I chose full authorization — why must I still act on some steps?

完全授权减少的是重复询问。付款、开发者标记为必须本人操作的步骤,以及超出授权范围的动作,仍然需要你确认。

Full authorization reduces repeated prompts. Payments, steps the developer marks as user-only, and anything beyond the granted scope still need you.