openid is the unique identifier of the user's operation of the applet. The same user will have the same openid in different applets and different operations of the same applet. Therefore, openid is generally used to uniquely identify a user. The importance of openid in applets It is still very high. If you need to use data interaction, you need to use openid.
There are two or three ways to obtain openid. Here I will talk about the simplest way to obtain it by using cloud functions, just copy it directly.
First of all, I usually get it in onload to facilitate the display of data
To add the useropenid field in the data of js, it can be called any name, but the setdata must be modified accordingly
wx.cloud.callFunction({
name:'hellocloud',
data:{
message:'hellocloud',
}
}).then(res=>{
console.log(res)//res就将appid和openid返回了
//做一些后续操作,不用考虑代码的异步执行问题。
that.setData({
useropenid:res.result.openid
})
Among them, that.setdata needs to be var this=that at the very beginning, which is not written in the code segment, because I intercepted it from the actual project, and there are many other things in the whole onload, just add var
The consol.log prints the data, and you can see whether the acquisition is successful in the background
Then, on the cloud function side, create a new node.js cloud function named hellocloud, and the js in it
as follows
const cloud = require('wx-server-sdk')
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
let{ APPID,OPENID}=cloud.getWXContext()
return {
APPID,
OPENID
}}
After uploading and deploying the cloud function, it can be used
After execution, see if it is displayed as follows
This is what is printed out, which means the acquisition is successful.