Get Mini Program code
This tutorial mainly introduces how to obtain Mini Program code through cloud invocation in WeDa obtain Mini Program code, official cloud invocation method sample:
Since the Mini Program code API returns images as buffers, it is necessary to convert the buffer to base64 in advance for frontend display.
Implementation Steps
In the cloud development platform, create a cloud function named getQRCode to obtain the Mini Program code.
1.1. Cloud Function Code Sample
Cloud Function Code:
const cloud = require("wx-server-sdk");
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
});
exports.main = async (event, context) => {
try {
const result = await cloud.openapi.wxacode.get({
path: "/pages/ulmp2pyqxok/index",
width: 430,
});
return result;
} catch (err) {
return err;
}
};tippath is the Mini Program page path, which needs to be replaced with the actual Mini Program page path in the business scenario and can be in the form of a variable.
1.2. Install cloud function dependencies. Click the "Save and Install Dependencies" button below and copy the dependency json.
1.3. Create a
package.json
file with the content being the json value from the previous step, and add the wx-server-sdk dependency."dependencies": {
"@cloudbase/node-sdk": "latest",
"wx-server-sdk": "~2.4.0"
}Build the application scenario in the editor
2.1. Create a variable named base64 to store the Mini Program code image address, and use the image component to display the Mini Program code.
2.2. The button component calls the cloud function to obtain the Mini Program code, and converts the buffer type returned by the cloud function to the base64 image type.
() => {
$w.cloud
.callFunction({
name: "getQRCode", // Cloud function name
//data: { a: 1 }, // Parameters received by the cloud function, depending on the input parameters of the cloud function you created.
})
.then((res) => {
const buffer_base64 = wx.arrayBufferToBase64(res.result.buffer);
$w.page.dataset.state.base64 =
"data:image/png;base64," + buffer_base64;
console.log("result", res);
});
};Notewx.arrayBufferToBase64: Converts an ArrayBuffer object to a Base64 string
Real-device effect demonstration: Click the button to trigger the event of obtaining the Mini Program code.
3.1. Response parameters display:
result {
"errMsg": "cloud.callFunction:ok",
"result": {
"contentType": "image/jpeg",
"buffer": "<ArrayBuffer: byteLength=104208>",
"errMsg": "openapi.wxacode.get:ok",
"errCode": 0
},
"requestID": "abed807a-0f4f-4026-a75e-xxxxxxxxx"
}