mpapi (miniProgram API), a mini program API compatible plug-in, written once and run on multiple terminals.
⏰ Update date: 2019-05-31, the mini program functions are constantly being updated, the new version may be different, please pay attention.
The problem this project solves : Find the differences between different mini program APIs, and try to use a set of APIs to be compatible with multiple mini programs .
api.showToast
can pass string
directly, api.setStorageSync
does not need to call try catch 等
request
, downloadFile
, detailsapi.isWechat
, api.isAlipay
, api.isSwan
, api.isTt
npm install mpapi --save
Non-npm installation method, just introduce mpapi.js
in the lib
directory directly into the project
const api = require ( 'mpapi' )
api . alert ( { ... } ) . then ( ( res ) => { } )
api . confirm ( { ... } ) . then ( ( res ) => { } )
api . getLocation ( ) . then ( ( res ) => { } )
. . .
request
, downloadFile
, uploadFile
etc.API that can be used by all mini programs
interaction
alert
confirm
showToast
showLoading
showActionSheet
Navigation bar
setNavigationBarTitle
setNavigationBarColor
document
saveFile
getFileInfo
getSavedFileInfo
getSavedFileList
removeSavedFile
picture
chooseImage
previewImage
compressImage
saveImageToPhotosAlbum
ask
request
uploadFile
downloadFile
Data cache
setStorageSync
getStorageSync
clearStorageSync
getStorageInfoSync
removeStorageSync
System equipment
getSystemInfoSync
setScreenBrightness
getScreenBrightness
makePhoneCall
scanCode
setClipboardData
getClipboardData
Only supported under specific mini programs
WeChat applet , Alipay applet , Baidu smart applet , ByteDance applet , if there is an icon, it means only the corresponding applet is supported, if there is no icon, it means all are supported.
interaction
hideToast
hideLoading
showModal
prompt
cache
getStorage
setStorage
removeStorage
getStorageInfo
routing
reLaunch
switchTab
redirectTo
navigateTo
navigateBack
Location
getLocation
openLocation
chooseLocation
File picture
saveImage
getImageInfo
chooseVideo
chooseMessageFile
saveVideoToPhotosAlbum
openDocument
Audio
stopVoice
playVoice
getAvailableAudioSources
stopBackgroundAudio
playBackgroundAudio
seekBackgroundAudio
pauseBackgroundAudio
getBackgroundAudioPlayerState
setInnerAudioOption
startRecord
stopRecord
stopRecord
Navigation bar
getTitleColor
setNavigationBar
showNavigationBarLoading
hideNavigationBarLoading
background
setBackgroundTextStyle
setBackgroundColor
showTabBar
hideTabBar
setTabBarItem
setTabBarStyle
showTabBarRedDot
hideTabBarRedDot
setTabBarBadge
removeTabBarBadge
Pull down to refresh
startPullDownRefresh
stopPullDownRefresh
scroll
pageScrollTo
sendSocketMessage
connectSocket
closeSocket
startLocalServiceDiscovery
stopLocalServiceDiscovery
pin to top
setTopBarText
canvas
canvasGetImageData
canvasPutImageData
canvasToTempFilePath
Share and forward
getShareInfo
updateShareMenu
showShareMenu
hideShareMenu
showFavoriteGuide
openShare
Login, authorization, user information
login
checkSession
getUserInfo
getAuthCode
getAuthUserInfo
getPhoneNumber
authorize
pay
tradePay
requestPayment
requestPolymerPayment
open interface
getSetting
openSetting
reportAnalytics
chooseInvoiceTitle
navigateToMiniProgram
navigateBackMiniProgram
Open interface - WeChat applet
addCard
openCard
chooseInvoice
startSoterAuthentication
checkIsSoterEnrolledInDevice
checkIsSupportSoterAuthentication
getWeRunData
Open interface - Alipay applet
startZMVerify
textRiskIdentification
addCardAuth
getRunScene
chooseCity
datePicker
optionsSelect
multiLevelSelect
rsa
Open interface - Baidu smart applet
getSwanId
navigateToSmartProgram
navigateBackSmartProgram
setPageInfo
setMetaDescription
setMetaKeywords
setDocumentTitle
loadSubPackage
Contact person
chooseAddress
chooseContact
choosePhoneContact
chooseAlipayContact
addPhoneContact
Font loading
loadFontFace
System information
getSystemInfo
getBatteryInfo
getNetworkType
setKeepScreenOn
startAccelerometer
stopAccelerometer
startCompass
stopCompass
startDeviceMotionListening
stopDeviceMotionListening
startGyroscope
stopGyroscope
vibrate
vibrateShort
vibrateLong
watchShake
setEnableDebug
getServerTime
scan
bluetooth wireless
getBeacons
startBeaconDiscovery
stopBeaconDiscovery
startWifi
stopWifi
setWifiList
getWifiList
connectWifi
getConnectedWifi
getBLEDeviceServices
getBLEDeviceCharacteristics
createBLEConnection
closeBLEConnection
writeBLECharacteristicValue
readBLECharacteristicValue
notifyBLECharacteristicValueChange
startBluetoothDevicesDiscovery
stopBluetoothDevicesDiscovery
openBluetoothAdapter
getConnectedBluetoothDevices
getBluetoothDevices
getBluetoothAdapterState
closeBluetoothAdapter
stopHCE
startHCE
getHCEState
sendHCEMessage
Third party platform
getExtConfig
Deep-level API, note: methods are prefixed with $
api.ap
api.ap.$faceVerify
api.ap.$navigateToAlipayPage
...
api.ai
api.ai.$ocrIdCard
api.ai.$ocrBankCard
...
Some new instance of the object above the API
createMapContext
createVideoContext
createAudioContext
createCameraContext
createInnerAudioContext
createLivePusherContext
createLivePlayerContext
getBackgroundAudioManager
getRecorderManager
createSelectorQuery
getFileSystemManager
createARCameraContext
For example: Note: The method is prefixed with $
let ctx = api . createMapContext ( 'maper' )
ctx . $getCenterLocation ( ) . then ( ( res ) => {
console . log ( 'createMapContext:getCenterLocation' )
console . log ( res )
} )
1. Inconsistent parameter transmission
For example: showLoading
method, the loaded display copy, title
parameter in WeChat and Baidu, and the content
parameter in Alipay, as follows
// 微信
wx . showLoading ( {
title : '加载中'
} )
// 百度
swan . showLoading ( {
title : '加载中'
} )
// 支付宝
my . showLoading ( {
content : '加载中'
} )
// 使用 mpapi 之后,多端兼容
api . showLoading ( '加载中' )
api . showLoading ( {
title : '提示内容'
} )
2. Return parameters are inconsistent
For example: showActionSheet
method, after execution, obtain the selected index. In WeChat and Baidu, it is res.tapIndex
, in Alipay, it is res.index
, as follows
// 微信
wx . showActionSheet ( {
itemList : [ '台球' , '羽毛球' , '篮球' ] ,
success : ( res ) => {
// res.tapIndex
}
} )
// 支付宝
my . showActionSheet ( {
items : [ '台球' , '羽毛球' , '篮球' ] ,
success : ( res ) => {
// res.index
}
} )
// 使用 mpapi,多端兼容
api . showActionSheet ( {
itemList : [ '台球' , '羽毛球' , '篮球' ] ,
success : ( res ) => {
// res.tapIndex
}
} )
3. Not supported, but compatible
For example: Alipay has my.alert
, but WeChat and Baidu do not have this method. However, you can encapsulate an alert
method through WeChat’s wx.showModal
or Baidu’s swan.showModal
, as follows
api . alert ( '提示内容' )
api . alert ( {
content : '提示内容'
} )
// 请求数据,兼容多端
api . request ( { ... } ) . then ( ( res ) => { } )
4. Not supported and incompatible
Some APIs are only valid in specific terminals and cannot be processed in compatibility, as follows:
// 只在支付宝里面有效,微信和百度小程序里面会报错
api . startZMVerify ( { ... } )
// 建议这样处理
if ( api . isAlipay ) {
api . startZMVerify ( { ... } )
}
// 只在微信里面有效,支付宝或百度小程序里面会报错
api . setTopBarText ( { ... } )
// 建议这样处理
if ( api . isWechat ) {
api . setTopBarText ( { ... } )
}
// 百度智能小程序的特殊 API 一样的道理
if ( api . isSwan ) {
api . getSwanId ( ) . then ( ( res ) => { } )
}
1. Support Promise
style
All mini program APIs, as long as they include success
callbacks, have been encapsulated with Promise
and can be used directly. Both writing methods are supported, for example
// 使用回调
api . showActionSheet ( {
itemList : [ '台球' , '羽毛球' , '篮球' ] ,
success : ( res ) => {
// res.tapIndex
}
} )
// 或者
api . showActionSheet ( {
itemList : [ '台球' , '羽毛球' , '篮球' ]
} ) . then ( ( res ) => {
// res.tapIndex
} )
// 其它
api . setStorage ( { ... } ) . then ( ( res ) => { } )
api . chooseImage ( { ... } ) . then ( ( res ) => { } )
. . .
2. The parameters passed and returned in the compatible method are subject to the WeChat applet call . Parameters that are incompatible with other terminals are not processed (some parameters cannot be processed and are not supported by specific mini programs). Developers need to pay attention, such as
api . chooseImage ( {
count : 1 ,
sizeType : [ 'original' , 'compressed' ] , // 只在微信可用
sourceType : [ 'album' , 'camera' ] ,
} ) . then ( ( res ) => {
// res.tempFilePaths 在微信和支付宝都可用
// res.tempFiles 只在微信可用
} )
Some APIs need to support Promise and call its events, so the following methods can be used:
before:
const downloadTask = wx . downloadFile ( {
url : 'https://example.com/audio/123' , // 仅为示例,并非真实的资源
success ( res ) {
console . log ( res )
}
} )
downloadTask . onProgressUpdate ( ( res ) => {
console . log ( res )
} )
downloadTask . abort ( ) // 取消下载任务
After using mpapi
:
const api = require ( 'mpapi' )
const downloadTask = api . downloadFile ( {
url : 'https://example.com/audio/123' // 仅为示例,并非真实的资源
} ) . then ( ( res ) => {
console . log ( 'success' )
console . log ( res )
} )
downloadTask . $event ( 'onProgressUpdate' , ( res ) => {
console . log ( res )
} )
// downloadTask.$event('abort') // 取消下载任务
Other APIs can be handled similarly, such as: request
, uploadFile
, connectSocket
If you find bugs during use or have good suggestions, please feel free to report them.
Change log