Skip to main content

Fetch and Transfer WeChat Open Data

Overview

WeChat provides a series of front-end interfaces for accessing WeChat's open data. Considering that the developer server-side also needs to access this open data, WeChat offers two methods of access:

  1. Traditional solution: The developer backend verifies and decrypts open data.
  2. Cloud Development: Directly access open data via cloud invocation

This article will introduce the second approach.

See: Server-Side Access to Open Data.

Solution Comparison: Traditional Solution vs Cloud Development

Code Sample

APIs for accessing open data, if involving sensitive data (such as wx.getWeRunData()), will not include such sensitive data in plaintext within the response. Instead, the returned data contains a cloudID field corresponding to the sensitive data, which can be obtained via cloud functions. The complete process is as follows:

Step 1: Get cloudID

Using base library version 2.7.0 or above, if cloud development is enabled for the Mini Program, the cloudID field can be obtained in the return value of the open data interface (at the same level as encryptedData). The cloudID is valid for five minutes.

Take Get User's WeChat Workout Step Count as an example:

wx.getWeRunData({
success(res) {
const cloudID = res.cloudID;
// ...
},
});

Step 2: Invoke the cloud function

When invoking a cloud function, for the data parameter passed in, if any top-level field value is a cloudID constructed via wx.cloud.CloudID, these field values will be replaced with the open data corresponding to the cloudID during the invocation. A single call can replace up to 5 cloudIDs.

Example:

After the Mini Program obtains the cloudID, it initiates the call:

wx.getWeRunData({
success(res) {
const id = res.cloudID;
wx.cloud.callFunction({
name: "myFunction",
data: {
weRunData: wx.cloud.CloudID(id), // This CloudID value will be replaced on the cloud function side
obj: {
shareInfo: wx.cloud.CloudID("yyy"), // Non-top-level CloudID, will not be replaced
},
},
});
},
});

An example of the event received by the cloud function:

// event
{
// The value of weRunData has been replaced with open data
"weRunData": {
"cloudID": "xxx",
"data": {
"stepInfoList": [
{
"step": 5000,
"timestamp": 1554814312
}
],
"watermark": {
"appid": "wx1111111111",
"timestamp": 1554815786
}
}
},
"obj": {
// Non-top-level fields remain unchanged
"shareInfo": "yyy"
}
}

If the cloudID is invalid or expired, what will be obtained in event is an object containing the error code, error message, and the original cloudID. A sample result for an expired cloudID:

// event
{
"weRunData": {
"cloudID": "xxx",
"errCode": -601006,
"errMsg": "cloudID expired."
}
// ...
}