The applet uses cloud functions to call third-party APIs to avoid domain name registration
In the development of small programs, if you need to call a third-party API, but cannot directly use it in the small program due to domain name registration restrictions, we can use cloud functions to solve this problem.
1. Open cloud development
- Use the WeChat developer tool to open the Mini Program project, click Cloud Development, and activate it if it is not activated
- Enter the cloud development name, select the payment method, and click Create
2. Create a new cloud function
- To use cloud functions, you need to create a
cloudfunctions
cloud function folder named Cloud Functions. After creation, your cloud development name will be automatically displayed on the right side
- Associate the cloud development environment in app.js, and configure the environment id of the newly created cloud development
- Then right-click on the cloudfunctions folder to create a new cloud function
- Write the cloud function code in the newly created cloud function entry file index.js, where we can write the logic for requesting third-party interfaces
code show as below:
//index.js
// 云函数入口文件
const cloud = require('wx-server-sdk')
const rp = require("request-promise")
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
// 云函数入口函数
exports.main = async (event, context) => {
console.log(event)
const config = {
url: "https://xxx.com/api/test",
qs: {
message: event.message
},
json: true,
}
const res = await rp(config)
return res
}
- After saving the code, right-click the cloudfunctions folder, click Synchronize cloud function list, and synchronize our newly created cloud function to the cloud development environment
- Then right-click the cloud function just written, click upload and deploy, and the cloud will automatically install the dependencies
3. Use cloud functions
- After the cloud function is uploaded, you can call the cloud function on the page for debugging, where the name value is the function name of the cloud function
testFn() {
wx.cloud.callFunction({
name: "test", // 此处是云函数的名称
data:{
message: "hello world"
}
}).then(res => {
console.log("云函数返回",res);
})
},
4. Configure cloud functions
- Click the cloud function in cloud development to enter the list of cloud functions, and click the version and configuration of the corresponding cloud function
- Continue to configure
- Click Advanced Configuration, where you can configure cloud function memory, time and environment variables, etc., and you can perform different configurations according to our business needs