mpapi

0.2.2 • Public • Published

mpapi

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

⏰ 更新日期: 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

  • 交互

    • alert
    • confirm
    • showToast
    • showLoading
    • showActionSheet
  • 导航栏

    • setNavigationBarTitle
    • setNavigationBarColor
  • 文件

    • saveFile
    • getFileInfo
    • getSavedFileInfo
    • getSavedFileList
    • removeSavedFile
  • 图片

    • chooseImage
    • previewImage
    • compressImage
    • saveImageToPhotosAlbum
  • 请求

    • request
    • uploadFile
    • downloadFile
  • 数据缓存

    • setStorageSync
    • getStorageSync
    • clearStorageSync
    • getStorageInfoSync
    • removeStorageSync
  • 系统设备

    • getSystemInfoSync
    • setScreenBrightness
    • getScreenBrightness
    • makePhoneCall
    • scanCode
    • setClipboardData
    • getClipboardData

其它包装成Promise的API

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

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

  • 交互

    • hideToast
    • hideLoading
    • showModal %= lbl %> %= lbl %> %= lbl %>
    • prompt %= lbl %>
  • 缓存

    • getStorage
    • setStorage
    • removeStorage
    • getStorageInfo
  • 路由

    • reLaunch
    • switchTab
    • redirectTo
    • navigateTo
    • navigateBack
  • 位置

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

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

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

    • getTitleColor %= lbl %>
    • setNavigationBar %= lbl %>
    • showNavigationBarLoading %= lbl %> %= lbl %> %= lbl %>
    • hideNavigationBarLoading %= lbl %> %= lbl %> %= lbl %>
  • 背景

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

    • startPullDownRefresh
    • stopPullDownRefresh
  • 滚动

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

    • setTopBarText %= lbl %>
  • 画布

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

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

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

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

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

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

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

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

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

    • loadFontFace %= lbl %> %= lbl %>
  • 系统信息

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

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

    • getExtConfig %= lbl %> %= lbl %>
  • 深层级的 API

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

    • createMapContext %= lbl %> %= lbl %> %= lbl %>
    • createVideoContext %= lbl %> %= lbl %>
    • createAudioContext %= lbl %>
    • createCameraContext %= lbl %> %= lbl %>
    • createInnerAudioContext %= lbl %> %= lbl %> %= lbl %>
    • createLivePusherContext %= lbl %>
    • createLivePlayerContext %= lbl %>
    • getBackgroundAudioManager %= lbl %> %= lbl %>
    • getRecorderManager %= lbl %> %= lbl %> %= lbl %>
    • createSelectorQuery
    • getFileSystemManager %= lbl %>
    • 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

Package Sidebar

Install

npm i mpapi

Weekly Downloads

0

Version

0.2.2

License

MIT

Unpacked Size

53.7 kB

Total Files

5

Last publish

Collaborators

  • chanceyu