# Getting Mini Program User Information

The unique advantage of Cloud Base cloud functions is their seamless integration with WeChat login authentication. When a cloud function is called by the Mini Program, the incoming parameters of the cloud function are injected with the openid of the Mini Program user. The developer is not required to verify the openid because it has been authenticated via WeChat and can be used directly. The appid of a Mini Program is injected into the cloud function along with the openid.

When calling a cloud function via a Mini Program, developers can use the getWXContext method provided by the wx-server-sdk in the cloud function to obtain the context (appid, openid, etc.) of each call and get the natural and reliable user login status (openid) without having to maintain a complex authentication system. You can test this by writing the following cloud function:

// index.js
const cloud = require('wx-server-sdk')
exports.main = (event, context) => {
  // The openId, appId, and unionId obtained here are reliable. Note that a unionId is returned only when it can be obtained.
  let { OPENID, APPID, UNIONID } = cloud.getWXContext()

  return {
    OPENID,
    APPID,
    UNIONID,
  }
}

Assuming the cloud function is named test, after the cloud function is uploaded and deployed, calling can be tested from the Mini Program:

wx.cloud.callFunction({
  name: 'test',
  complete: res => {
    console.log('callFunction test result: ', res)
  }
})

As we can see in the debugger, the output res is an object with the following structure:

{
  "APPID": "xxx",
  "OPENID": "yyy",
  "UNIONID": "zzz", // Returned only when unionId can be obtained.
}

In the next chapter, we will learn how to return the result after performing an async operation in the cloud function.

点击咨询小助手