WeChat Mini Program
In WeChat Mini Programs, you can access cloud hosting services via the built-in wx.cloud.callContainer
method. Before using this method, ensure that your Tencent Cloud account and Mini Program have completed the association operation.
// Make sure that wx.cloud.init has been called in onLaunch to initialize the environment (any environment ID is acceptable, and an empty string can be passed)
const res = await wx.cloud.callContainer({
config: {
env: "Fill in the cloud environment ID", // The environment ID for WeChat Cloud Run
},
path: "/xxx", // Enter the custom business path and parameters. The root directory is /
method: "POST", // Choose the corresponding method based on your business development
header: {
"X-WX-SERVICE": "xxx", // Enter the service name (WeChat Cloud Run - Service Management - Service List - Service Name)
// Other header parameters
},
// dataType:'text', // By default, the response is parsed as JSON. Use 'text' if you do not want the SDK to parse it automatically.
// Other parameters are the same as wx.request
});
console.log(res);
Before using as described above, you need to execute wx.init
in the app.js file of the Mini Program, as shown in the following code:
App({
async onLaunch() {
// Before using callContainer, ensure that init has been executed; this only needs to be done once globally.
wx.cloud.init();
// The following request can be used anywhere on the page
const result = await wx.cloud.callContainer({
config: {
env: "prod-01", // The environment ID for WeChat Cloud Run
},
path: "/", // Enter the custom business path and parameters. The root directory is /
method: "GET", // Choose the corresponding method based on your business development
header: {
"X-WX-SERVICE": "xxx", // Enter the service name (WeChat Cloud Run - Service Management - Service List - Service Name)
},
// dataType:'text', // By default, the response is parsed as JSON. Use 'text' if you do not want the SDK to parse it automatically.
});
console.log(result);
},
});
For more information on using callContainer to access Cloud Run in Mini Programs, see:
Advantages of Using wx.cloud.callContainer VS. wx.request
- Consumes no public network traffic; frontend-backend communication occurs via the internal network.
- Natively immune to DDoS attacks. Only authorized Mini Programs/Official Accounts can access the backend; others cannot access it even with the environment id and service name.
- Accelerated via WeChat's nearby access nodes, unaffected by backend service regions, eliminating cross-region latency without requiring multi-region backend deployment.
- Not required to configure "server domain" in the Mini Program backend;
- The backend can directly obtain user information, including opneid, without invoking interfaces.
- Therefore, if the cloud hosting service will only be called by WeChat Mini Programs/Official Accounts, it is recommended to disable public network access in the service settings.