mpapi icon indicating copy to clipboard operation
mpapi copied to clipboard

:baby_chick: 小程序API兼容插件,一次编写,多端运行。支持:微信小程序、支付宝小程序、百度智能小程序、字节跳动小程序

mpapi

mpapi(miniProgram API),小程序 API 兼容插件,一次编写,多端运行。

:alarm_clock: 更新日期: 2019-05-31,小程序功能一直在更新,新版本可能有所差异,请留意。

NPM Language License

此项目解决的问题:寻找不同小程序 API 之间的差异,尽可能地通过一套 API 兼容多个小程序使用

特点

  • 一次编写,多端运行,支持: 微信小程序、支付宝小程序、百度智能小程序、字节跳动小程序
  • 支持 Promise(包含 success 回调的才有)
  • 针对某些 API 使用做了优化,如:api.showToast 可以直接传 stringapi.setStorageSync 无需调用 try catch 等
  • 支持特殊 API 的事件处理,例如:requestdownloadFile详情
  • 支持不同端的判断,api.isWechatapi.isAlipayapi.isSwanapi.isTt

安装

npm install mpapi --save

非 npm 安装方式,直接引入 lib 目录下的 mpapi.js 到项目即可

使用

const api = require('mpapi')

api.alert({...}).then((res) => {})
api.confirm({...}).then((res) => {})
api.getLocation().then((res) => {})
...

快速查看

兼容API列表

所有小程序都可以使用的 API

  • 交互

    • [x] alert
    • [x] confirm
    • [x] showToast
    • [x] showLoading
    • [x] showActionSheet
  • 导航栏

    • [x] setNavigationBarTitle
    • [x] setNavigationBarColor
  • 文件

    • [x] saveFile
    • [x] getFileInfo
    • [x] getSavedFileInfo
    • [x] getSavedFileList
    • [x] removeSavedFile
  • 图片

    • [x] chooseImage
    • [x] previewImage
    • [x] compressImage
    • [x] saveImageToPhotosAlbum
  • 请求

    • [x] request
    • [x] uploadFile
    • [x] downloadFile
  • 数据缓存

    • [x] setStorageSync
    • [x] getStorageSync
    • [x] clearStorageSync
    • [x] getStorageInfoSync
    • [x] removeStorageSync
  • 系统设备

    • [x] getSystemInfoSync
    • [x] setScreenBrightness
    • [x] getScreenBrightness
    • [x] makePhoneCall
    • [x] scanCode
    • [x] setClipboardData
    • [x] getClipboardData

其它包装成Promise的API

只在特定小程序下才会支持

微信小程序wx、支付宝小程序my、百度智能小程序swan、字节跳动小程序tt,有图标表示只支持对应小程序,没有图标表示都支持。

  • 交互

    • [x] hideToast
    • [x] hideLoading
    • [x] showModal %= lbl %> %= lbl %> %= lbl %>
    • [x] prompt %= lbl %>
  • 缓存

    • [x] getStorage
    • [x] setStorage
    • [x] removeStorage
    • [x] getStorageInfo
  • 路由

    • [x] reLaunch
    • [x] switchTab
    • [x] redirectTo
    • [x] navigateTo
    • [x] navigateBack
  • 位置

    • [x] getLocation
    • [x] openLocation
    • [x] chooseLocation %= lbl %> %= lbl %> %= lbl %>
  • 文件图片

    • [x] saveImage %= lbl %>
    • [x] getImageInfo
    • [x] chooseVideo %= lbl %> %= lbl %> %= lbl %>
    • [x] chooseMessageFile %= lbl %>
    • [x] saveVideoToPhotosAlbum %= lbl %> %= lbl %> %= lbl %>
    • [x] openDocument %= lbl %> %= lbl %>
  • 音频

    • [x] stopVoice %= lbl %>
    • [x] playVoice %= lbl %>
    • [x] getAvailableAudioSources %= lbl %>
    • [x] stopBackgroundAudio %= lbl %>
    • [x] playBackgroundAudio %= lbl %>
    • [x] seekBackgroundAudio %= lbl %>
    • [x] pauseBackgroundAudio %= lbl %>
    • [x] getBackgroundAudioPlayerState %= lbl %>
    • [x] setInnerAudioOption %= lbl %> %= lbl %>
    • [x] startRecord %= lbl %>
    • [x] stopRecord %= lbl %>
    • [x] stopRecord %= lbl %>
  • 导航栏

    • [x] getTitleColor %= lbl %>
    • [x] setNavigationBar %= lbl %>
    • [x] showNavigationBarLoading %= lbl %> %= lbl %> %= lbl %>
    • [x] hideNavigationBarLoading %= lbl %> %= lbl %> %= lbl %>
  • 背景

    • [x] setBackgroundTextStyle %= lbl %> %= lbl %> %= lbl %>
    • [x] setBackgroundColor %= lbl %> %= lbl %> %= lbl %>
    • [x] showTabBar %= lbl %> %= lbl %> %= lbl %>
    • [x] hideTabBar %= lbl %> %= lbl %> %= lbl %>
    • [x] setTabBarItem %= lbl %> %= lbl %> %= lbl %>
    • [x] setTabBarStyle %= lbl %> %= lbl %> %= lbl %>
    • [x] showTabBarRedDot %= lbl %> %= lbl %> %= lbl %>
    • [x] hideTabBarRedDot %= lbl %> %= lbl %> %= lbl %>
    • [x] setTabBarBadge %= lbl %> %= lbl %> %= lbl %>
    • [x] removeTabBarBadge %= lbl %> %= lbl %> %= lbl %>
  • 下拉刷新

    • [x] startPullDownRefresh
    • [x] stopPullDownRefresh
  • 滚动

    • [x] pageScrollTo
    • [x] sendSocketMessage %= lbl %> %= lbl %> %= lbl %>
    • [x] connectSocket
    • [x] closeSocket %= lbl %> %= lbl %> %= lbl %>
    • [x] startLocalServiceDiscovery %= lbl %>
    • [x] stopLocalServiceDiscovery %= lbl %>
  • 置顶

    • [x] setTopBarText %= lbl %>
  • 画布

    • [x] canvasGetImageData %= lbl %> %= lbl %> %= lbl %>
    • [x] canvasPutImageData %= lbl %> %= lbl %> %= lbl %>
    • [x] canvasToTempFilePath %= lbl %> %= lbl %> %= lbl %>
  • 分享转发

    • [x] getShareInfo %= lbl %>
    • [x] updateShareMenu %= lbl %>
    • [x] showShareMenu %= lbl %> %= lbl %>
    • [x] hideShareMenu %= lbl %> %= lbl %> %= lbl %>
    • [x] showFavoriteGuide %= lbl %>
    • [x] openShare %= lbl %>
  • 登录、授权、用户信息

    • [x] login %= lbl %> %= lbl %> %= lbl %>
    • [x] checkSession %= lbl %> %= lbl %> %= lbl %>
    • [x] getUserInfo %= lbl %> %= lbl %> %= lbl %>
    • [x] getAuthCode %= lbl %>
    • [x] getAuthUserInfo %= lbl %>
    • [x] getPhoneNumber %= lbl %>
    • [x] authorize %= lbl %> %= lbl %>
  • 支付

    • [x] tradePay %= lbl %>
    • [x] requestPayment %= lbl %> %= lbl %>
    • [x] requestPolymerPayment %= lbl %>
  • 开放接口

    • [x] getSetting
    • [x] openSetting
    • [x] reportAnalytics
    • [x] chooseInvoiceTitle %= lbl %> %= lbl %>
    • [x] navigateToMiniProgram %= lbl %> %= lbl %>
    • [x] navigateBackMiniProgram %= lbl %> %= lbl %>
  • 开放接口 - 微信小程序

    • [x] addCard %= lbl %>
    • [x] openCard %= lbl %>
    • [x] chooseInvoice %= lbl %>
    • [x] startSoterAuthentication %= lbl %>
    • [x] checkIsSoterEnrolledInDevice %= lbl %>
    • [x] checkIsSupportSoterAuthentication %= lbl %>
    • [x] getWeRunData %= lbl %>
  • 开放接口 - 支付宝小程序

    • [x] startZMVerify %= lbl %>
    • [x] textRiskIdentification %= lbl %>
    • [x] addCardAuth %= lbl %>
    • [x] getRunScene %= lbl %>
    • [x] chooseCity %= lbl %>
    • [x] datePicker %= lbl %>
    • [x] optionsSelect %= lbl %>
    • [x] multiLevelSelect %= lbl %>
    • [x] rsa %= lbl %>
  • 开放接口 - 百度智能小程序

    • [x] getSwanId %= lbl %>
    • [x] navigateToSmartProgram %= lbl %>
    • [x] navigateBackSmartProgram %= lbl %>
    • [x] setPageInfo %= lbl %>
    • [x] setMetaDescription %= lbl %>
    • [x] setMetaKeywords %= lbl %>
    • [x] setDocumentTitle %= lbl %>
    • [x] loadSubPackage %= lbl %>
  • 联系人

    • [x] chooseAddress %= lbl %> %= lbl %> %= lbl %>
    • [x] chooseContact %= lbl %>
    • [x] choosePhoneContact %= lbl %>
    • [x] chooseAlipayContact %= lbl %>
    • [x] addPhoneContact %= lbl %> %= lbl %> %= lbl %>
  • 字体加载

    • [x] loadFontFace %= lbl %> %= lbl %>
  • 系统信息

    • [x] getSystemInfo
    • [x] getBatteryInfo %= lbl %> %= lbl %> %= lbl %>
    • [x] getNetworkType
    • [x] setKeepScreenOn %= lbl %> %= lbl %> %= lbl %>
    • [x] startAccelerometer %= lbl %> %= lbl %> %= lbl %>
    • [x] stopAccelerometer %= lbl %> %= lbl %> %= lbl %>
    • [x] startCompass %= lbl %> %= lbl %> %= lbl %>
    • [x] stopCompass %= lbl %> %= lbl %> %= lbl %>
    • [x] startDeviceMotionListening %= lbl %> %= lbl %>
    • [x] stopDeviceMotionListening %= lbl %> %= lbl %>
    • [x] startGyroscope %= lbl %> %= lbl %>
    • [x] stopGyroscope %= lbl %> %= lbl %>
    • [x] vibrate %= lbl %>
    • [x] vibrateShort
    • [x] vibrateLong
    • [x] watchShake %= lbl %>
    • [x] setEnableDebug %= lbl %> %= lbl %>
    • [x] getServerTime %= lbl %>
    • [x] scan %= lbl %>
  • 蓝牙无线

    • [x] getBeacons %= lbl %> %= lbl %>
    • [x] startBeaconDiscovery %= lbl %> %= lbl %>
    • [x] stopBeaconDiscovery %= lbl %> %= lbl %>
    • [x] startWifi %= lbl %>
    • [x] stopWifi %= lbl %>
    • [x] setWifiList %= lbl %>
    • [x] getWifiList %= lbl %>
    • [x] connectWifi %= lbl %>
    • [x] getConnectedWifi %= lbl %>
    • [x] getBLEDeviceServices %= lbl %> %= lbl %>
    • [x] getBLEDeviceCharacteristics %= lbl %> %= lbl %>
    • [x] createBLEConnection %= lbl %> %= lbl %>
    • [x] closeBLEConnection %= lbl %> %= lbl %>
    • [x] writeBLECharacteristicValue %= lbl %> %= lbl %>
    • [x] readBLECharacteristicValue %= lbl %> %= lbl %>
    • [x] notifyBLECharacteristicValueChange %= lbl %> %= lbl %>
    • [x] startBluetoothDevicesDiscovery %= lbl %> %= lbl %>
    • [x] stopBluetoothDevicesDiscovery %= lbl %> %= lbl %>
    • [x] openBluetoothAdapter %= lbl %> %= lbl %>
    • [x] getConnectedBluetoothDevices %= lbl %> %= lbl %>
    • [x] getBluetoothDevices %= lbl %> %= lbl %>
    • [x] getBluetoothAdapterState %= lbl %> %= lbl %>
    • [x] closeBluetoothAdapter %= lbl %> %= lbl %>
    • [x] stopHCE %= lbl %>
    • [x] startHCE %= lbl %>
    • [x] getHCEState %= lbl %>
    • [x] sendHCEMessage %= lbl %>
  • 第三方平台

    • [x] getExtConfig %= lbl %> %= lbl %>
  • 深层级的 API,注意:方法加了 $ 前缀

    • api.ap my
      • [x] api.ap.$faceVerify
      • [x] api.ap.$navigateToAlipayPage
      • [x] ...
    • api.ai swan
      • [x] api.ai.$ocrIdCard
      • [x] api.ai.$ocrBankCard
      • [x] ...
  • 某些新实例的对象上面的 API

    • [x] createMapContext %= lbl %> %= lbl %> %= lbl %>
    • [x] createVideoContext %= lbl %> %= lbl %>
    • [x] createAudioContext %= lbl %>
    • [x] createCameraContext %= lbl %> %= lbl %>
    • [x] createInnerAudioContext %= lbl %> %= lbl %> %= lbl %>
    • [x] createLivePusherContext %= lbl %>
    • [x] createLivePlayerContext %= lbl %>
    • [x] getBackgroundAudioManager %= lbl %> %= lbl %>
    • [x] getRecorderManager %= lbl %> %= lbl %> %= lbl %>
    • [x] createSelectorQuery
    • [x] getFileSystemManager %= lbl %>
    • [x] createARCameraContext %= lbl %>

例如:注意:方法加了 $ 前缀

let ctx = api.createMapContext('maper')

ctx.$getCenterLocation().then((res) => {
  console.log('createMapContext:getCenterLocation')
  console.log(res)
})

小程序之间的API差异

1、传参不一致

例如:showLoading 方法,加载的显示文案,微信和百度里面是 title 参数,支付宝里面是 content 参数,如下

// 微信
wx.showLoading({
  title: '加载中'
})

// 百度
swan.showLoading({
  title: '加载中'
})

// 支付宝
my.showLoading({
  content: '加载中'
})

// 使用 mpapi 之后,多端兼容
api.showLoading('加载中')
api.showLoading({
  title: '提示内容'
})

2、返回参不一致

例如:showActionSheet 方法,执行完之后获取选择的索引,微信和百度里面是 res.tapIndex,支付宝里面是 res.index,如下

// 微信
wx.showActionSheet({
  itemList: ['台球', '羽毛球', '篮球'],
  success: (res) => {
    // res.tapIndex
  }
})

// 支付宝
my.showActionSheet({
  items: ['台球', '羽毛球', '篮球'],
  success: (res) => {
    // res.index
  }
})

// 使用 mpapi,多端兼容
api.showActionSheet({
  itemList: ['台球', '羽毛球', '篮球'],
  success: (res) => {
    // res.tapIndex
  }
})

3、不支持,但可兼容

例如:支付宝里面有 my.alert,而微信和百度里面没有此方法,但是可以通过微信的 wx.showModal 或百度的 swan.showModal 封装一个 alert 方法,如下

api.alert('提示内容')

api.alert({
  content: '提示内容'
})

// 请求数据,兼容多端
api.request({...}).then((res) => {})

4、不支持,无法兼容

有的 API 只在特定端里面有效,无法兼容处理,如下

// 只在支付宝里面有效,微信和百度小程序里面会报错
api.startZMVerify({...})

// 建议这样处理
if(api.isAlipay){
  api.startZMVerify({...})
}

// 只在微信里面有效,支付宝或百度小程序里面会报错
api.setTopBarText({...})

// 建议这样处理
if(api.isWechat){
  api.setTopBarText({...})
}

// 百度智能小程序的特殊 API 一样的道理
if(api.isSwan){
  api.getSwanId().then((res) => {})
}

使用说明

1、支持 Promise 风格

所有小程序的 API 只要包含 success 回调,都已经用 Promise 封装过,可以直接使用,两种写法都支持,例如

// 使用回调
api.showActionSheet({
  itemList: ['台球', '羽毛球', '篮球'],
  success: (res) => {
    // res.tapIndex
  }
})

// 或者
api.showActionSheet({
  itemList: ['台球', '羽毛球', '篮球']
}).then((res) => {
    // res.tapIndex
})

// 其它
api.setStorage({...}).then((res) => {})
api.chooseImage({...}).then((res) => {})
...

2、兼容方法里的传参和返回参,以微信小程序调用为准。其它端不兼容的参数不处理(某些参数也无法处理,特定小程序不支持)开发者需要留意,例如

api.chooseImage({
  count: 1,
  sizeType: ['original', 'compressed'], // 只在微信可用
  sourceType: ['album', 'camera'],
}).then((res) => {
  // res.tempFilePaths 在微信和支付宝都可用
  // res.tempFiles 只在微信可用
})

特殊API的事件处理

某些 API 既要支持 Promise,又要调用它的事件,那么可以采用如下方式:

以前:

const downloadTask = wx.downloadFile({
  url: 'https://example.com/audio/123', // 仅为示例,并非真实的资源
  success(res){
    console.log(res)
  }
})

downloadTask.onProgressUpdate((res) => {
  console.log(res)
})

downloadTask.abort() // 取消下载任务

使用 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') // 取消下载任务

其它 API 可以类似处理,例如:requestuploadFileconnectSocket

Issues

如果您在使用过程中发现 Bug,或者有好的建议,欢迎报告问题

Changelog

更新日志

License

license