# uni-open-bridge

When developers connect to third-party open platforms such as WeChat, these open platforms have many credentials to manage, such as access_token, session_key, encrypt_key, ticket, etc.

uni-open-bridge is an open source tool for unified management of authentication credentials for third-party platforms such as WeChat.

# background

When calling a third-party open platform such as WeChat, many credentials are involved.

  • WeChat official account h5, applet, app, and web each have certain credentials
  • Some are application-level credentials, some are user-level credentials, some are one-time credentials
  • Some are copied from the WeChat backend web interface, some are obtained by request from the WeChat server, and some need to be initiated on the client side and then requested by the server
  • Some credentials have no validity period, and some are temporary credentials, which will expire after a certain period of time or after a certain operation. The expiration time of different credentials is different.
  • Some credentials cannot be requested to the WeChat server all the time, there are limited times, and you need to cache them yourself

There is a lot of confusion and error here. If credentials are requested from the WeChat server in different business logics, there will inevitably be conflicts.

for example,

  1. The validity period of ticket is 7200 seconds, and it needs to be requested regularly to avoid expiration. And because the number of api calls to obtain ticket is very limited, frequent refresh of ticket will limit api calls and affect their own business. Developers must cache ticket globally in their own services
  2. After calling wx.login() anywhere on the client, the previous session_key will expire immediately
  3. Regarding access_token, the official WeChat document directly recommends that developers of official accounts use the central control server to uniformly obtain and refresh access_token. The WeChat server is refreshed, otherwise it is easy to cause conflicts.

Therefore, these credentials need to be managed uniformly in a central system. Credentials that need to be regularly requested are regularly requested by the central system to the WeChat server and saved to the database.

Then, when each business needs these credentials, it is obtained from the interface of this central system instead of requesting it from the WeChat server.

This central system is uni-open-bridge.

# System composition

uni-open-bridge includes:

  1. A cloud object with the same name uni-open-bridge, the plugin download address: [https://ext.dcloud.net.cn/plugin?id=9002](https://ext.dcloud.net.cn/ plugin?id=9002). (which depends on the public module below, but is not a plugin)
  2. A public module uni-open-bridge-common, plugin download address: [https://ext.dcloud.net.cn/plugin?id=9177](https://ext.dcloud.net.cn /plugin?id=9177). It is an independent plug-in for the convenience of reference by other business modules. In fact, uni-id refers to this common plugin.
  3. The supporting database, save these credentials, the table name is opendb-open-data. The key format in redis is uni-id:[dcloudAppid]:[platform]:[openid]:[access-token|user-access-token|session-key|encrypt-key-version|ticket]

The cloud object uni-open-bridge runs regularly by default, and is configured to run every hour in package.json (it will take effect after it is deployed to the online service space).

The cloud object has the right to periodically send requests to the WeChat server according to the configuration fixed credentials in uni-config-center, and save the obtained access_token or ticket to Database opendb-open-data table.

When redis is activated in the service space where it is located, the key of redis will also be cached. This will make the system perform better.

The cloud object uni-open-bridge also provides URLization capabilities to facilitate reading and writing of these credentials by external systems.

uni-open-bridge-common provides the underlying interface for operating WeChat and other third-party platform credentials, including the ability to access WeChat servers and multi-layer read and write Redis and databases.

The cloud object uni-open-bridge actually relies on the uni-open-bridge-common public module when accessing the WeChat server and reading and writing credentials. Dependency plugins are automatically installed when installing the uni-open-bridge cloud object plugin uni-open-bridge-common

After obtaining various credentials from WeChat, when each business code needs these credentials, obtain them in the following way.

  • To obtain these temporary credentials from cloud functions/cloud objects, you can refer to the public module uni-open-bridge-common and obtain them through the module's API, such as getAccessToken. see below
  • For non-uniCloud systems, such as traditional cloud, to obtain these credentials, you need to URLize the cloud object uni-open-bridge and request credentials through Http. see below

The flow chart is as follows:

# Credential introduction

# Credentials Summary

WeChat has 4 platforms including official account h5, mini program, app, and web, and each platform has several credentials.

WeChat provides two systems, the public platform and the open platform.

  • The public platform, https://mp.weixin.qq.com/, is responsible for the capability opening in WeChat, namely WeChat official account H5 and mini programs, which Both run inside WeChat.
  • Open platform, https://open.weixin.qq.com/, responsible for the use of WeChat capabilities by systems other than WeChat, namely external apps and external web sites , these external applications call WeChat login, WeChat payment and other capabilities.
Credentials WeChat Mini Programs WeChat Official Account H5 Websites outside WeChat Non-WeChat Apps
access_token Regular refresh Regular refresh Developer operation Developer operation
user_access_token - Developer action - -
session_key uni-id maintenance or developer operation - - -
encrypt_key uni Cloud Integrated Security Network or developer operation - - -
ticket - Regular refresh - -
  • Timed refresh: refers to the timed task triggered by the cloud object uni-open-bridge, automatically obtains credentials from the WeChat server, and writes to Redis or database by calling uni-open-bridge-common

  • Developer operation: refers to the introduction of the public module uni-open-bridge-common by the developer, calling the relevant read and write methods

  • session_key: If a uni-id is used, the uni-id user will automatically read and write the credentials when they log in. Usually no developer maintenance is required.

  • encrypt_key depends on access_token, session_key, if the dependent value already exists, you can directly read encrypt_key, if it does not exist, it will be automatically obtained from the WeChat server, the developer should only read the value, if using uni cloud integrated security network is maintained by it, if there is a case that does not use uni-open-bridge hosting, there are external system operations

  • ticket depends on access_token, directly obtaining ticket will check access_token, if it does not exist by default, first request the WeChat server to obtain and save it, and continue to request ticket

There are also some less commonly used credentials that are not listed, for example: access_token for non-WeChat App platforms.

# Platform tag Platform

In uni-open-bridge, the different platforms are named in the following table, and the following table is used to mark the API and store data. Note that it is different from the uniPlatform used by the front-end conditional compilation.

value description
weixin-mp WeChat Mini Program
weixin-h5 WeChat Official Account H5
weixin-web Web site outside WeChat
weixin-app Non-WeChat App
qq-mp QQ applet
qq-app Apps outside QQ

Tip: Auto refresh of fixed app-level credentials currently only supports weixin-mp, weixin-h5. Additional platforms will be added later

# Common Credential Uses

  • WeChat applet
  1. Client login needs to save session_key
  2. access_token, session_key are required to decrypt user sensitive data, for example: obtain user authorized mobile phone number, user sensitive information
  3. access_token, session_key, encrypt_key are required to decrypt the encrypted data used by the uni cloud integrated security network channel
  • WeChat public account
  1. user_access_token, ticket are required for user login on H5 page of WeChat Official Account

WeChat credentials are divided into application-level, user-level, one-time and other credentials. If you have not contacted WeChat credentials before, please be sure to read the following detailed introduction of each credential

# access_token (application level)

  • Wechat applet access_token is the globally unique backend interface calling credential of the Wechat applet, and it needs to be used when calling most backend interfaces. Details

  • WeChat Official Account H5 access_token is the globally unique API call credential of the Official Account. The Official Account must use access_token when calling each API. Developers need to keep it properly. The storage of access_token must reserve at least 512 characters of space. The access_token is currently valid for 2 hours and needs to be refreshed regularly. Repeated acquisition will cause the last acquired access_token to be invalid.

Note: The acquisition of the WeChat official account H5 access_token requires a fixed IP, and the IP whitelist needs to be filled in the WeChat public platform. There is no fixed IP by default in uniCloud. To obtain a fixed IP, please refer to the document Fixed IP

Instructions on the use and generation of access_token required for API calls on the public platform:

1、 It is recommended that developers of official accounts use the central control server to obtain and refresh the access_token uniformly. The access_token used by other business logic servers all come from the central control server. They should not go to the WeChat server to refresh each other, otherwise it is easy to cause conflicts. Cause access_token to be overwritten and affect the business;

2、 The current validity period of access_token is conveyed by the returned expires_in, which is currently the value within 7200 seconds. The central control server needs to refresh the new access_token in advance according to this valid time. During the refresh process, the central control server can continue to output the old access_token. At this time, the backend of the public platform will ensure that both the new and old access_token are available within 5 minutes, which ensures a smooth transition of third-party services;

3、 The valid time of access_token may be adjusted in the future, so the central control server not only needs to actively refresh the access_token internally, but also needs to provide an interface for passively refreshing the access_token, which is convenient for the business server to know that the access_token has timed out in the API call In the case of access_token, the refresh process of access_token can be triggered.

4、 For calls that may have risks, when the developer makes a call to obtain access_token, it enters the risk call confirmation process, and the user administrator can confirm it before it can be successfully obtained. The specific process is:

The developer initiates a call through an IP -> the platform returns an error code [89503] and at the same time sends a template message to the official account administrator -> the official account administrator confirms that the IP can be called -> the developer uses the IP to initiate a call again -> The call succeeded.

If the official account administrator rejects the IP call for the first time, the user will not be able to use the IP to call again within 1 hour. If the official account administrator rejects the IP call for many times, the IP may not be able to initiate the call for a long time. The platform recommends that developers actively communicate with the administrator to confirm the invocation requirements before initiating the call, or request the administrator to enable the IP whitelist function and add the IP to the IP whitelist.

# user_access_token (user level)

The WeChat official account H5 platform has two access_token with the same name, which are used for

1、 Application level: The globally unique interface calling credentials of the official account, and the access_token is required when the official account calls each interface. 2、 User level: The web page authorization interface calls the credentials, and the scope of user authorization is access_token.

Many credentials are named access_token, which cannot be effectively distinguished. For user-level access_token, renamed user_access_token in uni-open-bridge. It corresponds to the user authorization access_token of the WeChat public platform webpage

Platform Value Description
WeChat Official Account H5 access_token WeChat Official Account H5 User Session Key. Details

# code(temporary credentials)

WeChat applet user login credential verification

The client obtains the temporary login credential code by calling uni.login() and then transmits it to the developer server to request the WeChat server to obtain the session_key, openid, unionid

code can only be used once on the server, and the client-side call frequency is limited to 100 per minute per user.

So there is no persistent storage code in uni-open-bridge.

# openid (user level)

WeChat Mini Program User Unique ID

It needs to be obtained by requesting the WeChat server on the developer server, depending on the parameter code, details

There is no persistent storage of openid in uni-open-bridge, and the related read, write and save are handled by another plugin uni-id.

可通过 uni-id-co 获取,详情

# session_key (user level)

The value corresponding to the platform

Platform Value Description
WeChat applet session_key WeChat applet session key. Details

Session key session_key validity

If the developer encounters that the signature verification fails or the decryption fails because the session_key is incorrect, please pay attention to the following notes related to session_key.

When uni.login is called, the user's session_key may be updated, causing the old session_key to become invalid (the refresh mechanism has a shortest period, if the same user calls uni.login multiple times in a short period of time, not every time calls result in a session_key refresh).

Developers should only call uni.login when they clearly need to log in again, and update the session_key stored by the server through the code2Session interface in time.

WeChat will not inform the developer of the validity period of the session_key, and will renew the session_key according to the user's behavior of using the applet. The more frequently the user uses the applet, the longer the session_key is valid.

When the session_key is invalid, the developer can obtain a valid session_key by re-executing the login process. Use the interface uni.checkSession to check whether the session_key is valid, so as to avoid the applet from repeatedly performing the login process.

When developers implement a custom login state, they can consider using the session_key validity period as the validity period of their own login state, or they can implement a custom timeliness strategy.

# encrypt_key (user level)

In order to avoid data interception and tampering when the WeChat applet communicates with the developer in the background, the WeChat side maintains a user-dimensional reliable key, which is used for encryption and signature when the applet communicates with the background. Details

Developers can obtain the user's encryption key through the interfaces provided by the front-end of the applet and the back-end of WeChat respectively.

# ticket (user level)

ticket is a temporary ticket used by WeChat official account to call WeChat JS interface. Under normal circumstances, the validity period of ticket is 7200 seconds, which is obtained through access_token.

Since the number of api calls to obtain ticket is very limited, frequent refresh of ticket will limit api calls and affect their own business. Developers must cache ticket globally in their own services. Details

While in uni-open-bridge the credentials are already cached.

# The usage process of uni-open-bridge

# 1. **Download the plugin uni-open-bridge into the project.

# 2. Configure fixed credentials under uni-id of uni-config-center

If you do not have appid and secret, you need to apply to WeChat first

  • WeChat Mini Program or WeChat Official Account, apply for appid and secret fixed credentials from WeChat's public platform.
  • WeChat App or PC webpage, apply for appid and secret fixed credentials from WeChat's Open Platform.

Then configure in the project's uniCloud/cloudfunctions/common/uni-config-center/uni-id/config.json file

If you do not need to refresh access_token, ticket regularly, or access credentials through an external system, you can introduce uni-open-bridge-common separately, and then use the cloud function or Directly call related methods in cloud objects

Uni-id example code in uni-id-config

// uniCloud/cloudfunctions/common/uni-config-center/uni-id/config.json
{
  "dcloudAppid": "__UNI__xxxxxx", // 在项目的 manifest.json 中
  "mp-weixin": { // 微信小程序
    "tokenExpiresIn": 259200,
    "oauth": {
      "weixin": {
        "appid": "", // 微信公众平台申请的小程序 appid
        "appsecret": "" // 微信公众平台申请的小程序 secret
      }
    }
  },
  "web": {
    "oauth": {
      "weixin-h5": { //微信公众号h5
        "appid": "", // 微信公众平台申请的网页授权 appid
        "appsecret": "" // 微信公众平台申请的网页授权 secret
      }
    }
  }
}
  • On the weixin-mp and weixin-h5 platforms, the access_token, encrypt_key, ticket need to use appid, appsecret in the configuration file
  • weixin-web, weixin-app, qq-mp, qq-app do not need to be configured for the time being. When these platforms are supported in the future, the configuration needs to be supplemented again, but it can still be configured by calling uni-open-bridge -common method to pass in the setting value

Note: The comments need to be removed when copying the contents of this file. Standard json does not support annotations. In HBuilderX, you can use multiple selection // to remove comments in batches.

# 3. Configure uni-open-bridge under uni-config-center

Create a new subdirectory uni-open-bridge under the uni-config-center directory, add config.json, configure dcloudAppid , see the sample code below for details

Uni-open-bridge example code in uni-id-config

// uniCloud/cloudfunctions/common/uni-config-center/uni-open-bridge/config.json
{
  "schedule": {
    "__UNI__xxxxxx": { // dcloudAppid, 需要和 `uni-config-center` uni-id中的配置一致
      "enable": true, // 任务全局开关,优先级最高
      "weixin-mp": { // 平台,目前仅支持 微信小程序、微信 H5,详情参见 https://uniapp.dcloud.net.cn/uniCloud/uni-open-bridge#platform
        "enable": true, // 当前平台任务开关
        "tasks": ["accessToken"] // 要执行的任务,微信小程序支持 accessToken
      },
      "weixin-h5": {
        "enable": false,
        "tasks": ["ticket"] // 支持微信 H5 ticket,因 ticker 依赖微信 H5 accessToken,内部自动先获取 accessToken。此处的 accessToken 和微信小程序的 accessToken 不是一个值
      }
    }
  },
  "ipWhiteList": ["0.0.0.0"] // 用于 URL化后 http 调用的服务器IP白名单,即指定ip的服务器才可以访问URL化后的`uni-open-bridge云对象
}

Note: The comments need to be removed when copying the contents of this file. Standard json does not support annotations. In HBuilderX, you can use multiple selection // to remove comments in batches.

# 4. Upload the plugin to the service space

After the cloud object uni-open-bridge is uploaded to the service space, it will automatically run every hour to obtain the relevant credentials from the WeChat server and save it to the database.

The data will be seen in the database opendb-open-data. If redis is activated, check it in the uni-id group of redis (it is recommended to activate redis for better performance).

If abnormal, please find the cloud function/cloud object uni-open-bridge in the uniCloud Web Console to check the running log. It is very likely that the configuration of the first or second step is wrong.

Of course, if you do not need scheduled tasks, you can modify the scheduled task configuration in the cloud object package.json and upload it again. Or modify the scheduled task in the uniCloud web console. It is generally not recommended to modify the scheduled task settings.

Notice

If you want to obtain the access_token of the WeChat official account H5 platform, you need to deal with the fixed export IP of the service space. Because the IP whitelist needs to be filled in the WeChat public platform, and then the credentials can be obtained from the WeChat server. There is no fixed IP by default in uniCloud. To obtain a fixed IP, please refer to the document Fixed IP

# How the business system obtains the relevant credentials

After the uni-open-bridge cloud object obtains the relevant credentials, when the business system (such as login payment or other business) needs to use these credentials, it is obtained in the following ways.

# Cloud function public module method

When your business is on uniCloud, reference the common module uni-open-bridge-common in your business cloud function/cloud object, then call the API below.

Cloud function common module is a way for different cloud functions to share code. If you don't know what cloud function common module is, please read the document public module

uni-open-bridge-common public module, provides access_token, user_access_token, session_key, encrypt_key, ticket read, write, delete operations.

uni-open-bridge-common supports multi-layer read/write mechanism, redis -> database -> fallback, the priority is as follows:

If the user does not activate redis or the operation fails, it will be transparently transmitted to database. After database fails, if the user configures fallback, continue to call the fallback method, otherwise throw Error, database corresponds to The table is: opendb-open-data

In common cases, it is enough to call several get methods of uni-open-bridge-common in your cloud function/cloud object.

let uobc = require('uni-open-bridge-common')

// application level credentials
const key = {
  dcloudAppid: '__UNI__xxx', // DCloud Appid
  platform: 'weixin-mp' // 指定凭据所属平台,解释见上
}
uobc.getAccessToken(key)
uobc.getTicket(key)


// User-level credentials, you need to pass in openid at the same time to get
const userKey = {
  dcloudAppid: '__UNI__xxx', // DCloud Appid
  platform: 'weixin-mp', // 指定凭据所属平台,解释见上
  openid: '' // 用户唯一标识,解释见上
}
uobc.getUserAccessToken(userKey)
uobc.getSessionKey(userKey)
uobc.getEncryptKey(userKey)

In addition to the common methods above, the get, set, and remove methods for all credentials are listed below.

# getAccessToken(key: Object, fallback: Function)

read access_token

# setAccessToken(key: Object, value: Object, expiresIn: Number)

Write access_token. Developers generally only need to use the get class method, and do not use the set and remove class methods. Same below

# removeAccessToken(key: Object)

Remove access_token. Developers generally only need to use the get class method, and do not use the set and remove class methods. Same below

key attribute

Parameters Type Required Description
dcloudAppid String Yes DCloud application appid. Details
platform String Yes Details

value attribute

parameter type description
access_token String Details

expiresIn

Effective time (seconds)

Sample code

'use strict';

const {
  getAccessToken,
  setAccessToken,
  removeAccessToken
} = require('uni-open-bridge-common')

exports.main = async (event, context) => {
  const key = {
    dcloudAppid: '__UNI__xxx',
    platform: 'weixin-mp'
  }
  const value = {
    access_token: ''
  }
  const expiresIn = 7200

  // write (redis / database)
  await setAccessToken(key, value, expiresIn)

  // read (redis / database)
  let result1 = await getAccessToken(key)

  // delete
  await removeAccessToken(key)

  // read after deletion, return null
  let result2 = await getAccessToken(key)
  console.log(result2) // null

  return null
};

# getUserAccessToken(key: Object, fallback: Function)

read user_access_token

# setUserAccessToken(key: Object, value: Object, expiresIn: Number)

write user_access_token

# removeUserAccessToken(key: Object)

remove user_access_token

Corresponding to WeChat official platform webpage user authorization access_token, see the description below for details

key attribute

Parameters Type Required Description
dcloudAppid String Yes DCloud application appid. Details
platform String Yes Details
openid String Yes Details

value attribute

parameter type description
access_token String WeChat public platform user session key, Details

expiresIn

Effective time (seconds)

Sample code

'use strict';

const {
  getUserAccessToken,
  setUserAccessToken,
  removeUserAccessToken
} = require('uni-open-bridge-common')

exports.main = async (event, context) => {
  const key = {
    dcloudAppid: '__UNI__xxx',
    platform: 'weixin-h5',
    openid: ''
  }
  const value = {
    'access_token': ''
  }
  const expiresIn = 7200

  // write (redis / database)
  await setUserAccessToken(key, value, expiresIn)

  // read (redis / database)
  let result1 = await getUserAccessToken(key)

  // delete
  await removeUserAccessToken(key)


  // read after deletion, return null
  let result2 = await getUserAccessToken(key)
  console.log(result2) // null

  return null
};

# getSessionKey(key: Object, fallback: Function)

read session_key

# setSessionKey(key: Object, value: Object, expiresIn: Number)

write session_key

# removeSessionKey(key: Object)

delete session_key

key attribute

Parameters Type Required Description
dcloudAppid String Yes DCloud application appid. Details
platform String Yes Details
openid String Yes Details

value attribute

parameter type description
session_key String WeChat applet session key, details

expiresIn

Effective time (seconds)

Sample code

'use strict';

const {
  getSessionKey,
  setSessionKey,
  removeSessionKey
} = require('uni-open-bridge-common')

exports.main = async (event, context) => {
  const key = {
    dcloudAppid: '__UNI__xxx',
    platform: 'weixin-mp',
    openid: ''
  }
  const value = {
    'session_key': ''
  }
  const expiresIn = 7200

  // write (redis / database)
  await setSessionKey(key, value, expiresIn)

  // read (redis / database)
  let result1 = await getSessionKey(key)

  // delete
  await removeSessionKey(key)


  // read after deletion, return null
  let result2 = await getSessionKey(key)
  console.log(result2) // null

  return null
};

# getEncryptKey(key: Object, fallback: Function)

read encrypt_key

# setEncryptKey(key: Object, value: Object, expiresIn: Number)

write encrypt_key

# removeEncryptKey(key: Object)

delete encrypt_key

key attribute

Parameters Type Required Description
dcloudAppid String Yes DCloud application appid. Details
platform String Yes Details
openid String Yes Details
version Number Yes Version

value attribute

parameter type description
encrypt_key String Encryption key, details
iv String encrypted iv

expiresIn

Effective time (seconds)

Sample code

'use strict';

const {
  getEncryptKey,
  setEncryptKey,
  removeEncryptKey
} = require('uni-open-bridge-common')

exports.main = async (event, context) => {
  const key = {
    dcloudAppid: '__UNI__xxx',
    platform: 'weixin-mp',
    openid: '',
    version: 1
  }
  const value = {
    encrypt_key: '',
    iv: ''
  }
  const expiresIn = 7200

  // write (redis / database)
  await setEncryptKey(key, value, expiresIn)

  // read (redis / database)
  let result1 = await getEncryptKey(key)

  // delete
  await removeEncryptKey(key)

  // read after deletion, return null
  let result2 = await getEncryptKey(key)
  console.log(result2) // null

  return null
};

# getTicket(key: Object, fallback: Function)

read ticket

# setTicket(key: Object, value: Object, expiresIn: Number)

write ticket

# removeTicket(key: Object)

delete ticket

key attribute

Parameters Type Required Description
dcloudAppid String Yes DCloud application appid. Details
platform String Yes Details

value attribute

parameter type description
ticket String Details

expiresIn

Effective time (seconds)

Sample code

'use strict';

const {
  getTicket,
  setTicket,
  removeTicket
} = require('uni-open-bridge-common')

exports.main = async (event, context) => {
  const key = {
    dcloudAppid: '__UNI__xxx',
    platform: 'weixin-h5'
  }
  const value = {
    ticket: ''
  }
  const expiresIn = 7200

  // write (redis / database)
  await setTicket(key, value, expiresIn)

  // read (redis / database)
  let result1 = await getTicket(key)

  // delete
  await removeTicket(key)


  // read after deletion, return null
  let result2 = await getTicket(key)
  console.log(result2) // null

  return null
};

# fallback

Optional async function fallback(), when reids -> database cannot find the corresponding key, this method is called, and the returned data format is as follows

{
  value: null,
  duration: 1
}

In order to simplify calling getAccessToken(), getTicket() to the WeChat server with built-in fallback, you need to configure appid appsecret in config-center, Details

# Precautions

  • All methods are of type async and need to use await
  • All methods check whether the key property is valid, if invalid, throw new Error(), for value only check whether it is Object

# Cloud object URLization method

After the cloud object uni-open-bridge is URLized, non-uniCloud systems can access the credentials through http.

URLization is a way to expose cloud functions or cloud objects as Http interfaces, see details. It can be operated in uniCloud Web Console.

通过以下2种方式验证外部服务器与uniCloud安全通讯

  1. uni-cloud-s2s模块
  2. 配置外部服务器IP白名单字段 ipWhiteList,参见 config.json

After configuring URLization, other systems can read, write and delete various open platform credentials through the following http interface.

请求类型 POST

# getAccessToken

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/getAccessToken

parameter

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-mp"
}

The parameter platform value range see details. The same below, and will not be repeated.

# setAccessToken

If various open platform credentials are hosted by uni-open-bridge, you only need to call various get methods instead of set and other methods. But in some cases, the relevant credentials are not obtained from the WeChat server by uni-open-bridge, and these set methods are needed. See details

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/setAccessToken

parameter

The relevant credentials are obtained from WeChat by the external system, and then written. See details

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-mp",
  "value": {
    "access_token": ""
  },
  "expiresIn": 7200
}

# removeAccessToken

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/removeAccessToken

parameter

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-mp"
}

# getUserAccessToken

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/getUserAccessToken

parameter

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-h5",
  "openid": ""
}

The parameter openid value range see details. The same below, and will not be repeated.

# setUserAccessToken

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/setUserAccessToken

parameter

The relevant credentials are obtained from WeChat by the external system, and then written. See details

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-h5",
  "openid": "",
  "value": {
    "access_token": ""
  },
  "expiresIn": 7200
}

# removeUserAccessToken

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/removeUserAccessToken

parameter

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-h5",
  "openid": ""
}

# getSessionKey

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/getSessionKey

parameter

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-mp",
  "openid": ""
}

# setSessionKey

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/setSessionKey

parameter

The relevant credentials are obtained from WeChat by the external system, and then written. See details

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-mp",
  "openid": "",
  "value": {
    "session_key": ""
  },
  "expiresIn": -1
}

默认值 "expiresIn": -1 为永不过期

由于微信的设计并没有告知开发者最短有效期,且只能通过客户的 uni.checkSession() 检查是否过期,过期后通知服务器同步到 uni-open-bridge

# removeSessionKey

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/removeSessionKey

parameter

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-mp",
  "openid": ""
}

# getEncryptKey

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/getEncryptKey

parameter

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-mp",
  "openid": "",
  "version": 1 // 此版本号应根据客户端传递的版本号
}

# setEncryptKey

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/setEncryptKey

parameter

The relevant credentials are obtained from WeChat by the external system, and then written. See details

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-mp",
  "openid": "",
  "version": 1,
  "value": {
    "encrypt_key": "",
    "iv": ""
  }
}

# removeEncryptKey

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/removeEncryptKey

parameter

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-mp",
  "openid": "",
  "version": 1
}

# getTicket

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/getTicket

parameter

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-h5"
}

# setTicket

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/setTicket

parameter

The relevant credentials are obtained from WeChat by the external system, and then written. See details

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-h5",
  "value": {
    "ticket": ""
  }
}

# removeTicket

Url

https://xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx.bspapp.com/uni-open-bridge/removeTicket

parameter

{
  "dcloudAppid": "__UNI__xxx",
  "platform": "weixin-h5"
}

提示:上面 Url 中的 uni-open-bridge 指云函数 uni-open-bridge 开启 Url 化时配置的 path 名称

# Hosting without uni-open-bridge

For example, the developer's old business has already obtained credentials such as WeChat's access_token, and it is difficult to migrate to uni-open-bridge to host WeChat-related credentials.

Then uni-open-bridge also exposes an interface that allows third-party systems to write WeChat-related credentials to uni-open-bridge.

Because other plugins will depend on uni-open-bridge, for example:

  1. uni-ad WeChat applet rewarded video ad server callback
  2. uni cloud integrated security network

If there are no relevant credentials in uni-open-bridge, the above plugins or functions will not work.

Therefore, developers do not want to change to uni-open-bridge to host WeChat credentials, but also need to use the above functions or plug-ins that rely on uni-open-bridge, they can only write the relevant credentials obtained by the old system into writing into uni-open-bridge.

At this point, the developer needs to deal with it in the following ways:

  1. Cancel the scheduled task of the uni-open-bridge cloud object, and no longer request credentials from the WeChat server regularly

Find the timer node triggers in the package.json of the uni-open-bridge cloud object and delete this node. After modifying the package.json locally, it needs to be re-uploaded to the service space for it to take effect.

Refer to Scheduled Task Configuration).

  1. After the old system obtains the relevant credentials from the WeChat server, it calls the set method of uni-open-bridge to write the credentials

First URLize the cloud object uni-open-bridge to expose the http interface. Then the old system calls interfaces such as setAccessToken, setUserAccessToken, setSessionKey, setEncryptKey, and setTicket. Reference

On This Page