# Access to open data on the server

Weixin Mini Program can access open data provided by WeChat through various front-end interfaces.Considering that developers' servers also need access to this open data, WeChat offers two ways to access it:

  • Method 1 : Developer background checks and decrypts open data
  • Option 2: : Cloud calls Getting open data directly ( [Cloud development]]](../../wxcloud/basis/getting-started.md) )

# Way 1: Developer background validation and decryption of open data

WeChat will sign and encrypt this open data.After the open data is obtained by the developer background, the data can be verified, signed and decrypted to ensure that the data is not tampered with.

Signature verification and data encryption and decryption involve the user's session key session_key. Developers should obtain the session key session_key in advance through the wx.login login process and save it in the server.In order to prevent data from being tampered with, developers should not pass the session_key to an environment outside the Weixin Mini Program server.

# Data signature validation

To ensure the security of the user data returned by the open interface, WeChat signs the clear data.Developers can perform signature validation of data packets according to business needs to ensure the integrity of the data.

  1. When fetching data by calling an interface such as wx.getUserInfo , the interface returns both rawData and signature, where signature = sha1 (rawData + session_key)
  2. The developer sends the signature and rawData to the developer server for verification. The server uses the user's session_key to calculate the signature Signature2 using the same algorithm, and then compares the signature with the signature to verify the integrity of the data.

Such as wx.getUserInfo's data validation:

The rawData returned by the interface:

{
  "nickName": "Band",
  "gender": 1,
  "language": "zh_CN",
  "city": "Guangzhou",
  "province": "Guangdong",
  "country": "CN",
  "avatarUrl": "http://wx.qlogo.cn/mmopen/vi_32/1vZvI39NWFQ9XM4LtQpFrQJ1xlgZxx3w7bQxKARol6503Iuswjjn6nIGBiaycAjAtpujxyzYsrztuuICqIM5ibXQ/0"
}

User's session-key:

HyVFkGl5F5OQWJZZaNzBBg==

The character string used for signing is:

{"nickName":"Band","gender":1,"language":"zh_CN","city":"Guangzhou","province":"Guangdong","country":"CN","avatarUrl":"http://wx.qlogo.cn/mmopen/vi_32/1vZvI39NWFQ9XM4LtQpFrQJ1xlgZxx3w7bQxKARol6503Iuswjjn6nIGBiaycAjAtpujxyzYsrztuuICqIM5ibXQ/0"}HyVFkGl5F5OQWJZZaNzBBg==

The result using sha1 is

75e81ceda165f4ffa64f4068af58c64b8f54b88c

# Encryption Data Decryption Algorithm

If an interface involves sensitive data (such as openId and unionId in wx.getUserInfo ), the plaintext content of the interface will not contain that sensitive data.If developers need to get sensitive data, they need to decrypt symmetrically the encrypted data (encryptedData)** returned by the interface. The decryption algorithm is as follows:

  1. The symmetric decryption algorithm used is AES-128-CBC, and the data is filled with PKCS # 7.
  2. The target ciphertext for symmetric decryption is Base64_Decode (encryptedData).
  3. Symmetric decryption key aeskey = Base64_Decode (session_key), aeskey is 16 bytes.
  4. The symmetric decryption algorithm starts with Base64_Decode (iv), where iv is returned by the data interface.

WeChat Sample code is available in several programming languages ( Click to download ).Interface names are consistent for each language type. Calls can be called by reference to examples.

In addition, in order to verify the validity of the data, data watermark is added to sensitive data.

Watermark Parameter Dxplaination:

parameter type Introductions
appid String Sensitive data belongs to appId, and developers can verify that this parameter is consistent with their own appId
timestamp Int Time stamps for sensitive data acquisition that developers can use for data timeliness validation

Such as interface wx.getUserInfo watermark in sensitive data:

{
    "openId": "OPENID",
    "nickName": "NICKNAME",
    "gender": GENDER,
    "city": "CITY",
    "province": "PROVINCE",
    "country": "COUNTRY",
    "avatarUrl": "AVATARURL",
    "unionId": "UNIONID",
    "watermark":
    {
        "appid":"APPID",
        "timestamp":TIMESTAMP
    }
}

Note:

  1. The json data obtained after decryption may add new fields according to needs, and the old fields will not be changed and deleted.

# Session key session_key validity

Developers who encounter signature verification failure or decryption failure due to incorrect session_key should pay attention to the following notes related to session_key.

  1. Wx.login When called, the user's session_key may be updated, causing the old session_key to expire (the refresh mechanism has a minimum cycle if the same user is called multiple times in a short period of time]] wx.login , not every call results in a session_key refresh).Developers should only call wx.login when they explicitly need to log in again,Update the session_key stored by the server in time through the code2Session interface.
  2. WeChat does not inform developers of the validity of session_key. The session_key is renewed based on the user's behavior with Weixin Mini Program. The more frequently the user uses the Mini Program, the longer the session_key is valid.
  3. When the session_key fails, the developer can obtain a valid session_key by re-executing the login process.Use the interface wx.checkSession to verify that the session_key is valid, thereby avoiding the Weixin Mini Program repeated login process.
  4. When developers implement self-defined login mode, they can consider session_key validity as their login mode validity, or implement self-defined temporal validity strategy.

# Option 2: Cloud calls directly obtain open data

Interface if sensitive data is involved (e.g. wx.getWeRunData ),The plaintext content of the interface does not contain these sensitive data, but instead contains thecloudIDfield for the corresponding sensitive data in the returned interface, and the data can be obtained through the cloud function.The full process is as follows:

1. Get cloudID

With the base library version 2.7.0 or above, if Weixin Mini Program has opened cloud development, in the return value of the open data interface, you can use thecloudIDfield acquisition (similar toencryptedData), andcloud IDis valid for five minutes.

2. Call a cloud function

When calling a cloud function, the incomingdataparameter, if there is a top-level field with a value ofwx.cloud.CloudIDis constructed`` CloudID,Then when the cloud function is called, the values of these fields are replaced with open data corresponding tocloudID, and up to 5 can be replaced in one call.CloudID

Examples:

A call is made after Weixin Mini Program getscloudID:

wx.cloud.callFunction({
  name: 'myFunction',
  data: {
    weRunData: wx.cloud.CloudID('xxx'), // 这个 CloudID 值到云函数端会被替换
    obj: {
      shareInfo: wx.cloud.CloudID('yyy'), // 非顶层字段的 CloudID 不会被替换,会原样字符串展示
    }
  }
})

Example of aeventreceived in a cloud function:

// event
{
  // weRunData 的值已被替换为开放数据
  "weRunData": {
    "cloudID": "xxx",
    "data": {
      "stepInfoList": [
        {
          "step": 5000,
          "timestamp": 1554814312,
        }
      ],
      "watermark": {
        "appid": "wx1111111111",
        "timestamp": 1554815786
      }
    }
  },
  "obj": {
    // 非顶层字段维持原样
    "shareInfo": "yyy",
  }
}

IfcloudIDIllegal or out of date, the object obtained ineventis an object containing the error code, error message, and the originalcloudID.ExpirationcloudIDExample of results exchanged for:

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