A Real Problem
Many indie developers hit the same pitfall the first time they integrate a large language model into a mini-program: hardcoding the API Key directly in the mini-program's frontend code.
This is like taping your house key to your front door. Anyone can decompile a mini-program's code package; once the key leaks, others burn through your quota while the bill lands on you. The proper approach is to build your own backend proxy layer: buy a server, write authentication, configure an HTTPS domain, set up rate limiting, handle key rotation... Once an indie developer runs the numbers, it becomes clear how heavy this is:
| Item | Self-built Proxy | Via AI Gateway Relay |
|---|---|---|
| Server procurement & setup | Half a day to a full day | 0, no server |
| Domain ICP filing + HTTPS certificate | 1–7 days (depending on filing) | 0, gateway domain ready to use |
| Auth/rate-limiting/key rotation code | 2–3 days | Platform-managed |
| Mini-program backend domain whitelist | Must be configured | Configure once and done |
By conservative estimates, a self-built solution takes at least 5–10 working days from kickoff to launch for a single developer; with a gateway relay, integration and joint debugging are usually done within an afternoon. Converted to an indie developer's time cost, this isn't about saving a few hundred bucks on servers—it's the difference between compressing a two-week schedule into half a day. That week-plus you save is enough to polish the mini-program's experience through two more rounds.
The Approach: Never Ship Keys Down, Let the Proxy Relay
The core of the solution in one sentence: The mini-program never holds the key. All requests are forwarded through an AI gateway, and the key exists only in your single server-side configuration (or is hosted by the gateway).
The architecture is just three steps:
- The mini-program sends a
wx.requestto the gateway address; - The gateway validates your configured access policies and forwards the request to the model provider;
- The response returns along the same path, and the mini-program renders the result.
You don't need to write any proxy code—the gateway itself is that proxy layer. All you have to do is: register an account, get a Key, put the Key in the single server-side location (e.g., your cloud function or a Next.js route handler—the key lives only in this one place), and then have the mini-program call your own endpoint.
Hands-On: Get Your First Code Running in Ten Minutes
Step one: register a ThisToken.AI account, go to the API Keys page in the console, create a Key, and store it securely. No assumptions about pricing—refer to the official pricing page.
Step two: write the forwarding logic on your server side (cloud function / Next.js Route Handler, etc.). Using Python as an example:
# server/proxy.py —— 部署在你的云函数或服务器上
# 这是全项目唯一持有 API Key 的地方
import os
from flask import Flask, request, jsonify, Response
from openai import OpenAI
app = Flask(__name__)
client = OpenAI(
api_key=os.environ["THISTOKEN_API_KEY"],
base_url="https://api.thistoken.ai/v1",
)
@app.post("/api/chat")
def chat():
body = request.get_json(force=True)
# 这里可以加上你自己的用户鉴权逻辑,防止接口被白嫖
messages = body.get("messages", [])
try:
resp = client.chat.completions.create(
model="gpt-4o-mini", # 按你在网关控制台开通的模型填写
messages=messages,
stream=False,
)
return jsonify({
"reply": resp.choices[0].message.content
})
except Exception as e:
return jsonify({"error": str(e)}), 502
if __name__ == "__main__":
app.run(port=8787)Step three: call it from the mini-program. Note that the domain must be added to the mini-program backend's list of valid request domains:
// miniprogram/utils/ai.js
function askAI(messages) {
return new Promise((resolve, reject) => {
wx.request({
url: "https://你的域名/api/chat",
method: "POST",
data: { messages },
header: { "content-type": "application/json" },
success: (res) => resolve(res.data.reply),
fail: reject,
});
});
}
module.exports = { askAI };Call askAI([{ role: "user", content: "你好" }]) in a page, and you'll receive the first model reply within seconds. At this point, the integration is up and running.
A Few Easily Overlooked Points
- Keep the key in exactly one place: It should exist only in the
THISTOKEN_API_KEYenvironment variable mentioned above. Never commit it to the code repository, and never ship it to the mini-program side. - Add a layer of authentication for yourself: The proxy endpoint is public. It's recommended to require the mini-program's login state (e.g., validating the code obtained via
wx.login); otherwise anyone can burn through your quota. - Streaming output: If you want a typewriter effect, turn on
stream=Trueand forward SSE, then receive chunks on the mini-program side usingwx.requestwithenableChunked. - Graceful failure handling: When the gateway returns an error, show users a friendly message and allow a retry. Don't let a blank page waste all the time you saved earlier.
Doing the Math
Self-built proxy: long-term server costs + 5–10 working days of setup and maintenance + full responsibility for key leak risks. Gateway proxy: from registration to a working integration in under half a day, with authentication, forwarding, and key management handed off to the platform—so your time goes into the product itself.
For indie developers and small teams, this choice isn't a hard one. Register now at https://api.thistoken.ai/register and get your first mini-program AI feature up and running.
---
Ready to try it yourself? Sign up at https://api.thistoken.ai/register to get your API key and start building.
Хотите попробовать Token.AI?
Создайте API Key уровня проекта, включите каналы в консоли и настройте маршрутизацию, бюджеты и журналы аудита.
注册 ThisToken.AI 并获取 API Key