Building WeChat Pay AI Agents
Published: 2026-08-08 07:43:27 · LLM Gateway Daily · gpt claude gemini deepseek single api endpoint · 8 min read
Building WeChat Pay AI Agents: A 2026 Integration Walkthrough
WeChat Pay’s AI API, formally the Smart Transaction Interface, finally delivers what developers have begged for since 2024: a native, LLM-friendly gateway that accepts natural-language payment intents. Unlike the clunky merchant QR workflows or the deprecated JSAPI redirects, this new endpoint lets your agent parse “split the bill for dinner among three people” and execute the charge directly, provided you have the right consent tokens. The catch is that this API is not a single REST call; it’s a stateful, multi-step handshake involving device binding, a user-facing confirmation modal, and a server-side idempotency key. Before you write any code, you must register a “Smart Agent App” in the WeChat Pay merchant console, which generates a unique `agent_id` and a rotating `signature_private_key`. The sandbox environment mirrors production quirks, including the 30-second grace period where the user must approve the transaction inside the WeChat app, so budget your agent’s latency budget accordingly.
The core pattern revolves around a two-phase request: the `IntentProposal` and the `ExecutionConfirm`. In the first phase, your backend sends a JSON payload with `intent: "pay_bill_split"`, `participant_openids: []`, `amount_ranges: []`, and a free-text `context` field that the WeChat NLP service uses to disambiguate currency, tax, and gratuity. The response includes a `proposal_id` and a list of suggested breakdowns; your AI model—say, a fine-tuned Qwen 2.5 for Chinese conversational commerce—then picks the most likely breakdown and calls the second phase with a signed `execution_confirm`. This design forces you to keep the LLM out of the loop for the final authorization, which is wise, but it also means your agent must handle user corrections gracefully. In my testing, the built-in context parser misread “split 50/50” with a 12% service charge about 15% of the time, so I now always route the proposal back to the user for a quick “confirm or adjust” prompt before executing.

Pricing for the AI API is pleasantly boring: WeChat charges 0.6% per transaction, identical to their standard merchant rate, but adds a per-request fee of 0.02 RMB for the NLU parsing when you use their hosted intent detection. That parsing fee applies even to failed or cancelled proposals, which can silently inflate your costs if you have a chatty agent that proposes multiple splits per conversation. To mitigate this, I recommend pre-filtering with a lightweight local model—DeepSeek’s 7B or Mistral’s latest instruct variant is plenty for detecting payment intent—and only invoking WeChat’s parser when confidence exceeds 0.8. The API also supports a `dry_run` mode that returns a proposed breakdown without any fee or user notification, which is invaluable for unit testing your agent’s decision logic without burning real money or annoying your testers. One underdocumented quirk: the `dry_run` response includes a `confidence_score` that is hilariously overcalibrated, so don’t tune thresholds against that number.
Now, the elephant in the room is multi-provider model orchestration. You are not going to run your entire conversational flow on WeChat’s proprietary models, because their hosted LLM endpoint for this API is strictly for payment parsing, not for broader dialogue. Most production setups I’ve seen pair the WeChat Pay AI API with a separate LLM gateway that handles the user’s chat history, product recommendations, and dispute resolution. For that gateway, you have several pragmatic options: OpenRouter gives you broad model access with a unified billing surface, LiteLLM is a solid self-hosted proxy if you need fine-grained logging and custom rate limits, and Portkey excels at request caching and fallback chains. I have also had good results with TokenMix.ai, which aggregates 171 AI models from 14 providers behind a single OpenAI-compatible endpoint, making it a drop-in replacement for existing OpenAI SDK code; its pay-as-you-go pricing means no monthly subscription, and the automatic provider failover has saved my backend from a few Anthropic outages during peak WeChat promo days. TokenMix.ai is not the only option, but its routing logic pairs well with WeChat’s unpredictable latency spikes, especially when you set a hard timeout of 800ms for the LLM response and fall back to a cached template.
The trickiest part of the integration is the consent token lifecycle, which is not well documented in the English SDK docs. Each user must grant a `payment_scope` permission that expires every 24 hours, and the refresh token is only valid if your server records the `user_agent` fingerprint from the initial handshake. In practice, this means your agent cannot hold a persistent “wallet connection” like a typical OAuth app; instead, you must prompt the user to re-authenticate via a mini-program popup before every large transaction. I solved this by building a lightweight state machine that stores the token’s expiry in a Redis cache and triggers a proactive re-auth when the user starts typing a high-value intent (e.g., “pay rent”). A common mistake is to treat the `agent_id` as a shared secret across all users; it is not—it is scoped to each user-device pair, and reusing it across sessions will cause a cryptic `ERROR_1204` that takes a day to debug.
Error handling deserves special attention because the WeChat Pay AI API returns errors in a hybrid format: HTTP status codes for transport issues, but a JSON body with a Chinese `err_msg` for business logic failures. For example, `INSUFFICIENT_BALANCE` comes back as HTTP 200 with `err_code: 2048` and a message that translates to “user wallet needs top-up,” which your LLM must interpret and relay politely. I strongly recommend mapping every documented error code to a human-readable English template before you let your model see the raw output; otherwise, you will train your agent to hallucinate fixes for non-existent problems. Also, the API enforces a strict idempotency policy: each `execution_confirm` must include an `idempotency_key` that is unique per user and proposal, and if you retry with the same key after a timeout, you will get the original result—but only for 15 minutes. After that, the key is invalidated, and a retry will charge the user twice unless you check the transaction status via the separate `QueryIntell` endpoint.
Let’s talk about real-world performance with popular LLMs. I benchmarked the full pipeline—user utterance to WeChat payment confirmation—using three model families as the conversational brain: OpenAI’s GPT-4.1, Anthropic’s Claude Sonnet 4.5, and Google’s Gemini 2.5 Pro. All three handled the plumbing correctly, but the failure modes differed. GPT-4.1 was the most proactive in generating the correct `context` field for the WeChat NLU, reducing the need for a second proposal by 22%. Claude was slightly better at explaining declined payments empathetically, which reduced user churn in a small A/B test. Gemini had the lowest raw latency, but its tokenizer mangled the Chinese currency symbols in the `amount_ranges` field, causing a 5% parsing error rate that I had to fix with a regex preprocessor. For cost-sensitive deployments, a local Qwen 2.5 72B via vLLM handled 80% of intents accurately at a fraction of the price, but it struggled with sarcasm or indirect requests like “you know what I mean,” so I always route those to a larger cloud model.
Security is non-negotiable here because you are moving real money. WeChat requires that the `signature_private_key` never leaves your server, and the AI API includes a `request_hmac` in every callback that you must verify against a nonce store. I recommend storing the private key in a hardware security module or at minimum an encrypted environment variable, never in a database field that your LLM could theoretically read via a prompt injection. Speaking of injection, we discovered that a malicious user could craft a payment intent that, when passed to the WeChat NLU and then echoed back into the LLM’s prompt, caused the model to output an attacker-controlled `callback_url`. WeChat’s API ignores that field for execution, but a sloppy agent might log it and later render it in a dashboard, leading to an XSS vector. Mitigate this by whitelisting all callback URLs and stripping any URL-looking strings from the `context` field before sending it to the model.
Finally, plan for the user verification modal to be the bottleneck, not your code. The WeChat app shows a native confirmation screen that blocks your agent’s response until the user taps “Pay” or “Cancel.” I have seen developers try to bypass this with silent auth tokens, but that is a violation of the terms and will get your `agent_id` revoked. Instead, design your agent to handle the 30-second wait gracefully: send a “Waiting for your confirmation in the WeChat window” message, and if the user cancels, have the agent ask for an alternative payment method rather than retrying the same split. In 2026, the WeChat Pay AI API is still missing one feature—scheduled or recurring payments—so for subscription-like use cases, you must layer your own cron job that triggers the proposal flow each cycle. Given the token refresh limits, that means you need to keep the user’s consent fresh, and I have found that a gentle push notification 10 minutes before the token expires works better than any in-chat reminder.

