Skip to main content

API

Basics#

mpService.canIUse(schema)#

Determines whether the APIs, callbacks, parameters, and components of the Mini Program are available in the current version.

Parameters#

string schema

The API is called using the ${API}.${method}.${param}.${options} or ${component}.${attribute}.${option} method.

  • ${API}: API name
  • ${method}: Call method. Available values: return, success, object, and callback.
  • ${param}: Parameter or return value
  • ${options}: Available values for the parameter
  • ${component}: Component name
  • ${attribute}: Component attribute
  • ${options}: Available values for the component attribute

Return Values#

Boolean Indicates whether the API is supported in the current version.

Sample code#

mpService.canIUse('openBluetoothAdapter')mpService.canIUse('getSystemInfoSync.return.screenWidth')mpService.canIUse('getSystemInfo.success.screenWidth')mpService.canIUse('showToast.object.image')mpService.canIUse('onCompassChange.callback.direction')mpService.canIUse('request.object.method.GET')
mpService.canIUse('live-player')mpService.canIUse('text.selectable')mpService.canIUse('button.open-type.contact')

mpService.getSystemInfo#

Return Values#

Object res

PropertyTypeExampleDescription
brandstring"Apple" "Xiaomi"Device brand
modelstringDevice model
pixelRationumberDevice's pixel ratio
screenWidthnumberScreen width in px
screenHeightnumberScreen height in px
windowWidthnumberAvailable window width in px
windowHeightnumberAvailable window height in px
statusBarHeightnumberStatus bar height in px
languagestringLanguage set in App
versionstringApp version
SDKVersionstringBase library version for the App version
systemstringOperating system and version
platformstring"ios" "android"Client platform
safeAreaObjectSafe area when the screen is in vertical orientation platform

res.safeArea

PropertyTypeDescription
leftnumberThe x-coordinate of the top-left corner of the safe area
rightnumberThe x-coordinate of the bottom-right corner of the safe area
topnumberThe y-coordinate of the top-left corner of the safe area
bottomnumberThe y-coordinate of the bottom-right corner of the safe area
widthnumberSafe area width in logical pixels
heightnumberSafe area height in logical pixels

mpService.getUpdateManager#

Get the singleton update manager for managing mini program updates.

Return Values#

UpdateManager

The update manager object.

mpService.getLaunchOptionsSync#

Obtains the parameters upon Mini Program startup. The callback parameters are consistent with those of onLaunch.

Return Values#

Object res Startup parameters

PropertyTypeDefault ValueRequiredDescription
pathstring--The path for Mini Program startup
scenenumber--The scene value for Mini Program startup
queryObject--The query parameter for Mini Program startup
referrerInfoObject--The source information. This is returned when a user enters the Mini Program from another Mini Program, Official Account, or app. Otherwise, {} is returned. (see the Note below for details.)

referrerInfo is composed as follows

PropertyTypeDefault ValueRequiredDescription
appIdstring--The appId of the source Mini Program, Official Account, or app.
extraDataObject--

mpService.getEnterOptionsSync#

Gets the parameters when the applet starts. If the current startup is cold, the return value is the same as the callback parameter for onLaunch; If the current is a hot start, the return value is the same as onShow.

Return Values#

Object res Startup parameters

PropertyTypeDefault ValueRequiredDescription
pathstring--The path for Mini Program startup
scenenumber--The scene value for Mini Program startup
queryObject--The query parameter for Mini Program startup
referrerInfoObject--The source information. This is returned when a user enters the Mini Program from another Mini Program, Official Account, or app. Otherwise, {} is returned. (see the Note below for details.)

referrerInfo is composed as follows

PropertyTypeDefault ValueRequiredDescription
appIdstring--The appId of the source Mini Program, Official Account, or app.
extraDataObject--

mpService.onUnhandledRejection#

Listen for unhandled Promise rejection events.

Parameters#

function callback#

Callback function for unhandled Promise rejection event.

function parameters#

Object res

PropertyTypeDefault ValueRequiredDescription
reasonstring-Reason for rejection, usually an Error object
promisePromise.<any>-scene code

Notes#

All unhandledRejection can be captured by this monitor, but only the Error type will trigger an alarm in the background of the applet.

mpService.onThemeChange#

Monitor system theme change events.

Parameters#

function callback#

Callback function for system theme change event.

function parameters#

Object res

PropertyTypeDefault ValueRequiredDescription
themestring-The current theme of the system, the value is light or dark

The legal value of the

PropertyTypeDefault ValueRequiredDescription
dark-The current theme of the system, the value is light or dark
light-The current theme of the system, the value is light or dark

Notes#

This event will only be triggered when the global configuration "darkmode": true

mpService.onError#

Listens on the Mini Program error event. This event is triggered as a result of script error or failed API call. The callback timing and parameters of this event are consistent with those of App.onError

Parameters#

function callback#

The callback function for the Mini Program error event.

Parameters#

string error Error message, including stacks.

mpService.onAppShow#

Listens on the event that Mini Program is switched to foreground. The callback timing for this event is consistent with that of App.onShow.

Parameters#

function callback#

The callback function for the event that Mini Program is switched to foreground.

Parameters#

Object res

PropertyTypeDefault ValueRequiredDescription
pathstring--The path for Mini Program startup
scenenumber--The scene value for Mini Program startup
queryObject--The query parameter for Mini Program startup
referrerInfoObject--The source information. This is returned when a user enters the Mini Program from another Mini Program, Official Account, or app. Otherwise, {} is returned. (see the Note below for details.)

referrerInfo is composed as follows

PropertyTypeDefault ValueRequiredDescription
appIdstring--The appId of the source Mini Program, Official Account, or app.
extraDataObject--

Notes#

In some versions, when there is no referrerInfo, the value undefined is returned. You can use options.referrerInfo && options.referrerInfo.appId to make a judgment.

mpService.onAppHide#

Listens on the event that Mini Program is switched to background. The callback timing for this event is consistent with that of App.onHide.

Parameters#

function callback#

The callback function for the event that Mini Program is switched to background.

mpService.offUnhandledRejection#

Cancel listening for unhandled Promise rejection events.

Parameters#

function callback#

Callback function for unhandled Promise rejection event.

mpService.offThemeChange#

Cancel listening for system theme change events.

Parameters#

function callback#

The callback function for the Mini Program theme change.

mpService.offError#

Un-listens on Mini Program error event.

Parameters#

function callback#

The callback function for the Mini Program error event.

mpService.offAppShow#

Un-listens on the event that Mini Program is switched to foreground.

Parameters#

function callback#

The callback function for the event that Mini Program is switched to foreground.

mpService.offAppHide#

Un-listens on the event that Mini Program is switched to background.

Parameters#

function callback#

The callback function for the event that Mini Program is switched to background.

UpdateManager#

UpdateManager object, used to manage updates, the instance can be obtained through the mpService.getUpdateManager() interface.

Methods#

UpdateManager.applyUpdate#

Force the mini program to restart and use the new version. Called after the new version of the mini program has been downloaded (that is, the onUpdateReady callback is received).

UpdateManager.onCheckForUpdate(function callback)#

Listen to the Binance App background request to check the update result event. The Binance App automatically checks for updates when the mini program is cold-started, and does not need to be triggered by the developer.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“The callback function. ({ hasUpdate: boolean }) => void
UpdateManager.onUpdateReady(function callback)#

Monitor the version update event of the mini program. The client actively triggers the download (no need for the developer to trigger), and the callback will be called after the download is successful.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“The callback function. () => void
UpdateManager.onUpdateFailed(function callback)#

Monitor the update failure event of the mini program. There is a new version of the mini program, the client actively triggers the download (no need for the developer to trigger), and the download fails (maybe due to network reasons, etc.) and callback

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“The callback function. () => void
Example#
const updateManager = mpService.getUpdateManager()
updateManager.onCheckForUpdate(function (res) {  // Callback after requesting new version information  console.log(res.hasUpdate)})
updateManager.onUpdateReady(function () {  mpService.showModal({    title: 'Update reminder',    content: 'The new version is ready, do you want to restart the mini-program? ',    success: function (res) {      if (res.confirm) {        // The new version has been downloaded, call applyUpdate to apply the new version and restart        updateManager.applyUpdate()      }    }  })})
updateManager.onUpdateFailed(function () {  // Failed to download the new version})

Routing#

mpService.redirectTo#

Closes the current page and redirects to a page (except for the tabbar page) in the app.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlstringβœ“Path to a non-tabBar page to be navigated to in the app. Parameters can be appended after the path. You can use ? to separate the path from parameters, = to connect a parameter key with a parameter value, and & to separate different parameters. For example, 'path?key=value&key2=value2'.

mpService.reLaunch#

Closes all pages and opens a page in the app.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlstringβœ“Path to a non-tabBar page to be navigated to in the app. Parameters can be appended after the path. You can use ? to separate the path from parameters, = to connect a parameter key with a parameter value, and & to separate different parameters. For example, 'path?key=value&key2=value2'.

mpService.navigateTo#

Keeps the current page open and redirects to a page (except for the tabbar page) in the app. You can return to the original page using mpService.navigateBack.

Parameters#

Object payload

PropertyTypeDefault ValueRequiredDescription
urlstringβœ“url to navigate
eventsObjectregister callbacks to listen EventChannel

Return Values#

Object res

PropertyTypeDescription
eventChannelEventChannelcommunication channel between opener page and opened page

mpService.switchTab#

Redirects to the tabBar page and closes all non-tabBar pages.

payload

PropertyTypeDefault ValueRequiredDescription
urlstringβœ“Path to the tabBar page (a page to be defined in the tabBar field of app.json) to be navigated to. Parameters cannot be appended after the path.

Parameters#

mpService.navigateBack#

Closes the current page and returns to the previous page or multi-level page.

Parameters#

PropertyTypeDefault ValueRequiredDescription
deltanumber1The position in the history to which you want to move, relative to the current page. For example, pop(2) moves back two pages. If no value is passed then the default delta is 1.

mpService.navigateToMiniProgram#

Opens another Mini Program.

payload

PropertyTypeDefault ValueRequiredDescription
appIdstringβœ“The appId of the Mini Program to be opened.
pathstringThe path of the page to be opened. If it is empty, the homepage is opened. Content following the question mark (?) in the path becomes a query.
extraDataobjectThe data that needs to be passed to the target Mini Program. The target Mini Program can obtain this data from App.onLaunch and App.onShow.
envVersion'preview', 'experience', 'published'publishedThe channel of the Mini Program to be opened. It is valid when target="miniProgram".
type'app', 'web', 'webview'appThe type of the Mini Program to be opened. It is valid when target="miniProgram".
revStringThe rev of the Mini Program to be opened. It is valid when target="miniProgram".
mpService.navigateToMiniProgram({  appId: '',  path: 'page/1',  extraData: {    foo: 'bar',  },  envVersion: 'published',  type: 'app',  rev: '006a05ebf14db3e4a8e69cb6bc8b2589',})

mpService.navigateBackMiniProgram#

Returns to the previous Mini Program. It can be called only when the current Mini Program is opened from another Mini Program.

payload

PropertyTypeDefault ValueRequiredDescription
extraDataobjectThe data that needs to be returned to the previous Mini Program. The previous Mini Program can get this data from App.onShow.
mpService.navigateBackMiniProgram({  extraData: {    foo: 'bar',  },})

mpService.exitMiniProgram#

Exit the miniprogram. There must be a click behavior to call successfully.

Framework#

mpService.getApp#

Gets the globally unique App instance of the Mini Program.

Interface#

;() => App

mpService.getCurrentPages#

Gets the current page stack. In the array, the first element is the homepage and the last element is the current page.

Interface#

() => Page[]

Interface#

mpService.showToast#

Displays the message prompt box.

Parameters#

PropertyTypeDefault ValueRequiredDescription
titlestring-βœ“Prompt content
iconstringsuccessIcon. Available values: success,loading, none, error
durationnumber1500The delay time for a prompt

mpService.hideToast#

Hides the message prompt box.

mpService.showLoading#

Displays the loading prompt box. mpService.hideLoading must be called to close the prompt box.

mpService.hideLoading#

Hides the loading prompt box.

mpService.showModal#

Displays the modal dialog box.

Parameters#

PropertyTypeDefault ValueRequiredDescription
titlestring-βœ“Prompt title
contentstring-βœ“Prompt content
confirmTextstring-The text of the "OK "button, not more than 4 characters
showCancelbooleansuccessIndicates whether to display the "Cancel" button
cancelTextstring-The text of the "Cancel" button, not more than 4 characters

Return Values#

Object res

PropertyTypeDescription
statusbooleanWhen the value is "true", it indicates that the user tapped the "OK" button.

mpService.showActionSheet#

Displays the action sheet.

Parameters#

PropertyTypeDefault ValueRequiredDescription
alertTextstring-Alert text
itemListstring[]-βœ“The text array of the button, with a length limited to 6
itemColorstring#000000The text color of the button

Return Values#

Object res

PropertyTypeDescription
tapIndexnumberThe sequence number of the button tapped by the user, from top to bottom and starting from 0

mpService.setNavigationBarTitle#

Dynamically sets the title of the current page.

Parameters#

PropertyTypeDefault ValueRequiredDescription
titlestringβœ“title of the navigation bar

mpService.setTabBarItem#

Dynamically sets the content of a tabBarn item.

Parameters#

PropertyTypeDefault ValueRequiredDescription
indexnumberβœ“Specifies which item of tabBar, starting from the left.
textstringThe text of a button on tab.
iconPathstringThe path to the icon. The icon size is limited to 40 KB. Recommended size is 81 px * 81 px, This parameter does not take effect when position is top.
selectedIconPathstringThe path to the selected icon. The icon size is limited to 40 KB. Recommended size is 81 px * 81 px, This parameter does not take effect when position is top.

mpService.showTabBar#

Display tabBar.

Parameters#

PropertyTypeDefault ValueRequiredDescription
animationbooleanfalseShow animation effect

mpService.hideTabBar#

Hide tabBar.

Parameters#

PropertyTypeDefault ValueRequiredDescription
animationbooleanfalseShow animation effect

mpService.pageScrollTo#

Scrolls the screen to the target location

Parameters#

PropertyTypeDefault ValueRequiredDescription
scrollTopnumberNoScrolls the screen to the target location (in px)
durationnumber300NoScrolls the screen to the target location (in px)
selectorstringNoselector
selector syntax#

selector is similar to CSS selector, but only supports the following syntax.

  • ID selector: #the-id
  • class selector: .a-class.another-class
  • child selector: .the-parent > .the-child
  • descendant selector: .the-ancestor .the-descendant
  • Descendant selector across custom components: .the-ancestor >>> .the-descendant
  • Union of multiple selectors: #a-node, .some-other-nodes

mpService.hideHomeButton#

Hide Back HomeButton.When the bottom page of the mini program opened by the user is not the homepage, the "Back to Homepage" button is displayed by default. Developers can use hideHomeButton in the onShow/componentDidShow page to hide HomeButton.

Media#

mpService.chooseImage#

Selects an image from the local album or takes a photo with the camera.

Parameters#

PropertyTypeDefault ValueRequiredDescription
countnumber9noThe maximum number of images allowed
sizeTypeArray.<string>['original', 'compressed']noThe size of the select image
sourceTypeArray.<string>['album', 'camera']noThe source of the image
Valid values of object.sizeType#
ValueDescription
originalOriginal image
compressedCompressed image
Valid values of object.sourceType#
ValueDescription
albumSelects an image from the album
cameraTakes a photo with the camera

Return Values#

PropertyTypeDescription
tempFilePathsArray.<string>The list of local temporary file paths to images
tempFilesArray.<Object>The local temporary file list for images
res.tempFiles is composed as follows#
PropertyTypeDescription
pathstringThe path to the local temporary file
sizenumberThe size of a local temporary file, in bytes

mpService.createVideoContext(id)#

Creates the VideoContext object for the video.

Parameters#

PropertyTypeDefault ValueRequiredDescription
idstringβœ“The video component's ID

Return Values#

VideoContext

videoContext.play#

Plays the video.

videoContext.pause#

Pauses the video.

videoContext.stop#

Stops the video.

videoContext.seek(position)#

Jumps to the specific position.

PropertyTypeDefault ValueRequiredDescription
positionnumberβœ“The position to be jumped to (in sec)
videoContext.playbackRate(rate)#

Sets multi-speed playback.

PropertyTypeDefault ValueRequiredDescription
ratenumberβœ“Indicates the playback speed (0.5x/0.8x/1x/1.25x/1.5x).
videoContext.requestFullScreen#

Enters the full screen.

videoContext.exitFullScreen#

Exits the full screen.

videoContext.exitPictureInPicture#

Exits the picture in picture mode.

Custom Component#

Defers some operations until the next time slice. (similar to setTimeout)

mpService.nextTick(function callback)#

Parameters#

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“the callback function

Keyboard#

mpService.onKeyboardHeightChange(callback function)#

Listens on the keyboard height changes

Parameters#

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“the callback function

mpService.offKeyboardHeightChange(callback function)#

Remove the listener on the keyboard height changes

Parameters#

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“the callback function

Sample code#

function callback(res) {  console.log(res.height)}
mpService.onKeyboardHeightChange(callback)mpService.offKeyboardHeightChange(callback)

mpService.hideKeyboard#

Hide keyboard

Sample code#

mpService  .hideKeyboard()  .then(res => {    console.log('hideKeyboard res', res)  })  .catch(error => {    console.log('hideKeyboard error', error)  })

mpService.getSelectedTextRange#

Obtains the cursor position of the input box after the focus of input, textarea, etc. Note: This API works only when it is called during the focus process.

Sample code#

mpService  .getSelectedTextRange()  .then(res => {    console.log('getSelectedTextRange res', res.start, res.end)  })  .catch(error => {    console.log('hideKeyboard error', error)  })

Network#

mpService.request#

Initiates an HTTPS request.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlstring-βœ“request url
datastring-request params
headerobject-set request header, can't set Referer. default value of content-type is application/json
timeoutnumber10000timeout of request, unit is millisecond
methodstring'GET'HTTP request method
dataTypestring'json'Returned data format
responseTypestring'text'Response data type
successfunctionCallback function for successful interface call
failfunctionCallback function for successful interface call
completefunctionThe callback function for the end of the interface call
Available values of object.dataType#
ValueDescription
'json'The returned data is JSON. After returning, JSON.parse will be performed on the returned data.
othersDo not perform JSON.parse on the returned content
Available values of object.responseType#
ValueDescription
'text'The response data is text
'arraybuffer'The response data is ArrayBuffer
Parameters of object.success callback#

Object res

PropertyTypeDescription
datastring/Object/ArraybufferData returned by the developer server
statusCodenumberThe status code of the response. (This will be 200 for a success).
headerObjectThe Headers object associated with the response.
statusTextstringThe status message corresponding to the status code. (e.g., OK for 200).
Description of data parameter#

The final data sent to the server is of type String. If the data passed in is not of type String, it will be converted to String. The conversion rules are as follows:

  • For the data of the GET method, the data will be converted into query string:
encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...
  • For data with POST method and header['content-type'] is application/json, the data will be serialized in JSON

  • For POST method and header['content-type'] is application/x-www-form-urlencoded data, the data will be converted into query string

encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...

Return Values#

RequestTask

Request task

requestTask.abort#

Interrupt request task

requestTask.onHeadersReceived(callback)#

Listen to the HTTP Response Header event. Will be earlier than the requested completion event

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“The callback function. ({ headers: Object }) => void
requestTask.offHeadersReceived(callback)#

Cancel listening for HTTP Response Header event

mpService.downloadFile#

Downloads local resources to the local device. The client initiates an HTTPS GET request. The local temporary path to the file is returned.

Note: Specify a reasonable Content-Type field in the server response header to ensure that the client handles the file type properly.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlstring-βœ“URL to download resources
headersobject-Set request header, can't set Referer. default value of content-type is application/json
timeoutnumber60000timeout of request, unit is millisecond
filePathstringSpecify the path where the file is stored after downloading (local path)
successfunctionCallback function for successful interface call
failfunctionCallback function for successful interface call
completefunctionThe callback function for the end of the interface call
Parameters of object.success callback#

Object res

PropertyTypeDescription
tempFilePathstringTemporary file path. It is returned when the filePath to save files is not specified. The downloaded files will be stored in a temporary file path.
filePathstringUser file path (local path). It will be returned when filePath is passed in, which is consistent with the filePath passed in
statusCodenumberHTTP status code returned by the developer server

Return Values#

DownloadTask

An object that can monitor the download progress change event and cancel the download

downloadTask.abort#

Interrupt download task

downloadTask.onHeadersReceived(callback)#

Listen to the HTTP Response Header event. Will be earlier than the requested completion event

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“The callback function. ({ headers: Object }) => void
downloadTask.offHeadersReceived(callback)#

Cancel listening for HTTP Response Header event

downloadTask.onProgressUpdate(callback)#

Monitor download progress change events.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“The callback function. (progress) => void
Parameters object of callback function#
PropertyTypeDescription
progressnumberDownload progress percentage
totalBytesWrittennumberThe length of the downloaded data, in Bytes
totalBytesExpectedToWritenumberThe total length of data expected to be downloaded, in Bytes
downloadTask.offProgressUpdate(callback)#

Cancel listening to download progress change event

mpService.uploadFile#

Upload local resources to the server. The client initiates an HTTPS POST request, where the content-type is multipart/form-data.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlstringβœ“The HTTPS API URL of developer server
filePathstringβœ“The path of the file resource to be uploaded (local path)
namestringβœ“The key corresponding to the file, the server can get the file content through this key
headerObjectHeader of HTTP request, Referer cannot be set in Header
formDataObjectOther additional form data in the HTTP request
timeoutnumber60000timeout of request, unit is millisecond
successfunctionCallback function for successful interface call
failfunctionCallback function for successful interface call
completefunctionThe callback function for the end of the interface call
Parameters of object.success callback#

Object res

PropertyTypeDescription
datastringData returned by the developer server
statusCodenumberHTTP status code returned by the developer server

Return Values#

UploadTask

An object that can monitor upload progress change events and cancel upload tasks

uploadTask.abort#

Interrupt upload task

uploadTask.onHeadersReceived(callback)#

Listen to the HTTP Response Header event. Will be earlier than the requested completion event

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“The callback function. ({ headers: Object }) => void
uploadTask.offHeadersReceived(callback)#

Cancel listening for HTTP Response Header event

uploadTask.onProgressUpdate(callback)#

Monitor upload progress change events.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“The callback function. (progress) => void
Parameters object of callback function#
PropertyTypeDescription
progressnumberThe percentage of upload progress
totalBytesSentnumberThe length of the uploaded data, in Bytes
totalBytesExpectedToSendnumberThe total length of data expected to be uploaded, in Bytes
uploadTask.offProgressUpdate(callback)#

Cancel listening to upload progress change event

mpService.connectSocket#

Creates a WebSocket connection.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlstring-βœ“The wss API URL of developer server
headersobject-set request header, can't set Referer. default value of content-type is application/json
protocolsstring[]-Sub-protocol array.
<!--successfunction-
failfunction-The callback function for a failed API call.
completefunction-The callback function used when the API call completed (always executed whether the call succeeds or fails).

Return Values#

SocketTask

WebSocket task

socketTask.send#

Sends data over a WebSocket connection.

PropertyTypeDefault ValueRequiredDescription
datastring/ArrayBuffer-βœ“The data to be sent.
socketTask.close#

Disables the WebSocket connection.

PropertyTypeDefault ValueRequiredDescription
codenumber1000 (indicating that the connection is disabled normally)A numeric value indicates the status code explaining why the connection has been disabled.
reasonstring-A readable string explaining why the connection has been disabled. This string must be a UTF-8-encoded text (not characters) with not more than 123 bytes.
socketTask.onOpen(callback)#

Listens on the event of enabling the WebSocket connection.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“The callback function. ({ headers: Object }) => void
socketTask.onClose(callback)#

Listens on the event of disabling the WebSocket connection.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“The callback function. () => void
socketTask.onError(callback)#

Listens on the WebSocket error event.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“The callback function. ({ errMsg: string }) => void
socketTask.onMessage(callback)#

Listens on the event of receiving server messages by WebSocket

PropertyTypeDefault ValueRequiredDescription
callbackfunction-βœ“The callback function. ({ data: string/ArrayBuffer }) => void

Number of Concurrent Connections#

  • Up to 5 WebSocket connections can exist at the same time.

Data Caching#

mpService.getStorageInfo#

Gets the information related to the current storage.

Return Values#

Object res

PropertyTypeDescription
keysstring[]All keys in the current storage
currentSizenumberCurrent space occupied (in KB)
limitSizenumberSpace size limit (in KB)

mpService.getStorage#

Gets the content of the specified key from the local cache

Parameters#

PropertyTypeDefault ValueRequiredDescription
keystringβœ“The specified key in the local cache

Return Values#

Object res

PropertyTypeDescription
dataanyContent of the key

mpService.setStorage#

Stores data in the specified key in the local cache. This operation will overwrite the original content of the key. The data storage lifecycle is consistent with the Mini Program, that is, data is always available unless manually deleted by the user or automatically deleted after a certain period of time.

Parameters#

PropertyTypeDefault ValueRequiredDescription
keystringβœ“The specified key in the local cache
dataanyβœ“Contents to be stored can only be native types, dates, and objects that can be serialized via JSON.stringify.

mpService.removeStorage#

Removes the specified key from the local cache.

Parameters#

PropertyTypeDefault ValueRequiredDescription
keystringβœ“The specified key in the local cache

mpService.clearStorage#

Clears the data cached locally.

Location#

mpService.openLocation#

Views location using the built-in map.

Parameters#

PropertyTypeDefault ValueRequiredDescription
latitudenumber-βœ“Latitude. The value ranges from -90 to +90, and the negative number means south latitude. The GCJ-02 coordinate system of the State Bureau of Surveying and Mapping is used. title
longitudenumber-βœ“Longitude. The value ranges from -180 to +180, and the negative number means west longitude. The GCJ-02 coordinate system of the State Bureau of Surveying and Mapping is used. content
scalenumber18Scale, ranging from 5 to 18
namestringLocation name
addressstringDetailed address

mpService.getLocation#

Gets current geographic location and speed. The API cannot be called when the user exits the Mini Program.

Parameters#

PropertyTypeDefault ValueRequiredDescription
typestringwgs84GPS coordinates are returned for WGS84, and coordinates used for mpService.openLocation are returned for GCJ-02.
altitudestringfalseAltitude information is returned if true is passed. The API will take a longer time to respond since a higher accuracy is required to obtain the altitude.

Return Values#

Object res

PropertyTypeDescription
latitudenumberLatitude. The value ranges from -90 to +90, and the negative number means south latitude.
longitudenumberLongitude. The value ranges from -180 to +180, and the negative number means west longitude.
speednumberspeed(unit: m/s)
accuracynumber
altitudenumberaltitude(unit: m)
verticalAccuracynumberVertical accuracy(unit: m)
horizontalAccuracynumberHorizontal accuracy(unit: m)

mpService.chooseLocation#

Opens the map to select a location.

Parameters#

PropertyTypeDefault ValueRequiredDescription
latitudenumber-Latitude of the target.
longitudenumber-Longitude of the target.

Return Values#

Object res

PropertyTypeDescription
namestringLocation name brand
addressstringDetailed address platform
latitudestringLatitude, which is expressed by a floating point number ranging from -90 to +90, and the negative number means south latitude. The GCJ-02 coordinate system of the State Bureau of Surveying and Mapping is used.
longitudestringLongitude, which is expressed by a floating point number ranging from -180 to +180, and the negative number means west longitude. The GCJ-02 coordinate system of the State Bureau of Surveying and Mapping is used.

mpService.startLocationUpdate#

Start monitoring real-time position changes in the foreground

mpService.stopLocationUpdate#

Stop monitoring real-time location changes

mpService.onLocationChange#

Subscribe the event of real-time location changes,used with mpService.startLocationUpdate.

mpService.offLocationChange#

Unsubscribe the event of real-time location changes.

Open APIS#

mpService.login#

Gets the login credential (code), which is then used to exchange for the user login status information, including the unique identifier (openid) of the user and the session key (session_key) of the current login.

Return Values#

Object res

PropertyTypeDescription
codestringThe authorization code.

mpService.getUserInfo#

Gets user information.

Parameters#

PropertyTypeDefault ValueRequiredDescription
withCredentialsbooleanIndicates whether to include login status information. When withCredentials is true, mpService.login must be called previously and the login status must be effective. In this case, sensitive information such as encryptedData and iv is returned. When withCredentials is false, the login status is not required, and sensitive information such as encryptedData and iv is not returned.
langstringenThe language of the displayed user information

Return Values#

Object res

PropertyTypeDescription
userInfoObjectUser information object, excluding openid and other sensitive information.

res.userInfo

{}

mpService.requestPayment#

Initiates a request for payment via Binance Pay.

Parameters#

Object payload

PropertyTypeDefault ValueRequiredDescription
certSnstring-βœ“API identity key issued by Binance payment system
merchantIdstring-βœ“The merchant account id, issued when merchant been created at Binance.
timeStampstring-βœ“timestamp of the sign
noncestrstring-βœ“nonceStr for the sign
prepayIdstring-βœ“The value of the prepay_id parameter returned by the unified order placement API
paySignstring-βœ“Signature. For specific signature schemes, see Binance Pay API Documentation

Return Values#

Object res

PropertyTypeDescription
statusstring0 : pay success
others : pay failed

Notes the response is a string, not a number.

example:

mpService  .requestPayment({    certSn: '',    merchantId: '',    timeStamp: '',    noncestr: '',    prepayId: '',    paySign: '', // signature of the parameters  })  .then(res => {    if (res.status === '0') {      // success    }  })

mpService.getPerformance#

Gets the performance information

Return Values#

Performance

performance.getEntries#

Get all current performance information.

Return Entry[]

Entry property

PropertyTypeDescription
entryTypenavigation, render, scripttype of entry
namestringname of entry
startTimenumberstart time of entry
durationnumbertotal time of entry
pathstringpath
navigationStartnumberthe real time of navigation
navigationTypestringtype of navigation
entryTypeDescription
navigationappLaunch: time of app launch. route: performance of routing
renderfirstRender: first render time
scriptevaluateScript: inject script time

Example

const performance = mpService.getPerformance()const entries = performance.getEntries()
[  {    entryType: 'navigation',    name: 'appLaunch',    navigationType: 'appLaunch',    startTime: 1618467220999,    duration: 434,  },
  // 1. entryPage  {    entryType: 'script',    name: 'evaluateScript',    path: 'pages/component/index',    startTime: 1618467221374,    duration: 5,  },  {    entryType: 'render',    name: 'firstRender',    path: 'pages/component/index',    startTime: 1618467221379,    duration: 73,  },
  // 2. navigateTo to "pages/component/pages/view/view"  {    entryType: 'navigation',    name: 'route',    navigationType: 'navigateTo',    navigationStart: 1618467224916,    path: 'pages/component/pages/view/view',    startTime: 1618467224906,    duration: 312,  },  {    entryType: 'script',    name: 'evaluateScript',    path: 'pages/component/pages/view/view',    startTime: 1618467225218,    duration: 5,  },  {    entryType: 'render',    name: 'firstRender',    path: 'pages/component/pages/view/view',    startTime: 1618467225223,    duration: 16,  },
  // 3. switchTab to "pages/API/index"  {    entryType: 'navigation',    name: 'route',    navigationType: 'switchTab',    navigationStart: 1618467227064,    path: 'pages/API/index',    startTime: 1618467227062,    duration: 303,  },  {    entryType: 'script',    name: 'evaluateScript',    path: 'pages/API/index',    startTime: 1618467227365,    duration: 7,  },  {    entryType: 'render',    name: 'firstRender',    path: 'pages/API/index',    startTime: 1618467227372,    duration: 16,  },]

Device#

mpService.setClipboardData#

Set the contents of the system clipboard.

Parameters#

PropertyTypeDefault ValueRequiredDescription
datastringβœ“Clipboard content

Return Values#

mpService.getClipboardData#

Get the contents of the system clipboard.

Parameters#

Return Values#

Object res

PropertyTypeDescription
datastringClipboard content

mpService.onNetworkStatusChange#

Listens on the network status change event.

Parameters#

function callback#

The callback function for the network status change event.

Parameters#

Object res | Property | Type | Description | | -------- | --------- | ----------- | | isConnected | boolean | Indicates whether it is connected to the network | | networkType | string | Network type |

Valid values of networkType | Value | Description | Minimum Version | | -------- | --------- | ----------- | | wifi | Wi-Fi network | | 2g | 2G network | | 3g | 3G network | | 4g | 4G network | | 5g | 5G network | | unknown| Uncommon network types for Android | | none| No network |

Return Values#

mpService.offNetworkStatusChange#

Un-listens on Mini Program network status change event.

Parameters#

function callback#

Cancel the callback function for the network status change event.

mpService.getNetworkType#

Gets the network type.

Parameters#

Return Values#

Object res

PropertyTypeDescription
networkTypestringNetwork type
signalStrengthnumberSignal strength, dbm
errMsgstringerror info

mpService.scanCode#

Tun up the client scan code interface for scanning code.

Parameters#

PropertyTypeDefault ValueRequiredDescription
scanTypeArray.<string>['qrCode']-Scan code type

Return Values#

PropertyTypeDefault ValueRequiredDescription
resultstring-the content of scanned code
scanTypestring-the type of scanned code

Object scanType

ValueDescriptionVersion
QR_CODEQR Code-