本文對uniapp框架兼容微信和支付寶小程序一些整改點對比介紹。
一、登錄授權
微信:wx.login 返回 code 換取用戶登錄態信息 openid、unionid、session_key
wx.login({
success (res) {
if (res.code) {
} else {
}
}
})
文檔: https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
支付寶:my.getAuthCode 返回 authCode 換取支付寶會員標識 user_id,換取用戶其他信息需用戶授權
my.getAuthCode({
scopes: 'auth_base', // auth_base(靜默授權)/ auth_user(主動授權)/ auth_zhima (獲取用戶芝麻信息)
success: (res) => {
my.alert({
content: res.authCode,
});
},
});
文檔: https://opendocs.alipay.com/mini/api/openapi-authorize
uni-app: uni.login 兼容全部平台的小程序,統一返回 code 字段
uni.login({
provider: 'weixin',
success: function (loginRes) {
console.log(loginRes.authResult);
}
});
文檔: https://uniapp.dcloud.io/api/plugins/login?id=login
二、獲取用戶信息
微信:wx.getUserProfile 返回 userInfo
wx.getUserProfile({
desc: '用於完善會員資料', // 聲明獲取用戶個人信息后的用途,后續會展示在彈窗中,請謹慎填寫
success: (res) => {
this.setData({
userInfo: res.userInfo
})
}
})
文檔: https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html
支付寶:用 button 組件喚起授權
<!-- .axml -->
<button a:if="{{canIUseAuthButton}}" open-type="getAuthorize" onGetAuthorize="onGetAuthorize" onError="onAuthError" scope='userInfo'> 會員基礎信息授權 </button>
// .js
onGetAuthorize(res) {
my.getOpenUserInfo({
fail: (res) => { },
success: (res) => {
let userInfo = JSON.parse(res.response).response; // 以下方的報文格式解析兩層 response
}
});
},
文檔: https://opendocs.alipay.com/mini/api/ch8chh
uni-app: 需使用 條件編譯 兼容兩個平台不同的寫法
<!-- template -->
<!-- #ifdef MP-WEIXIN -->
<button @tap="getUserProfile"></button>
<!-- #endif -->
<!-- #ifdef MP-ALIPAY -->
<button open-type="getAuthorize" @getAuthorize="getAuthorize" @error="authError" ascope="userInfo"></button>
<!-- #endif -->
// js
// MP-WEIXIN
getUserProfile() {
uni.getUserProfile({
desc: '獲取你的公開信息',
success: res => {
console.log(res.userInfo);
},
fail: err => {}
});
}
// MP-ALIPAY
getAuthorize() {
uni.getUserInfo({
success: res => {
console.log(res.userInfo);
},
fail: err => {}
});
}
文檔: https://uniapp.dcloud.io/api/plugins/login?id=getuserprofile
三、獲取用戶手機號
微信:用 button 組件喚起授權
<!-- wxml -->
<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">授權手機號</button>
// js
getPhoneNumber(res) {
console.log(res);
}
文檔: https://developers.weixin.qq.com/miniprogram/dev/component/button.html
支付寶:用 button 組件喚起授權
<!-- axml -->
<button a:if="{{canIUseAuthButton}}" open-type="getAuthorize" onGetAuthorize="onGetAuthorize" onError="onAuthError" scope="phoneNumber">授權手機號</button>
// js
onGetAuthorize() {
my.getPhoneNumber({
success: (res) => {
let encryptedData = res.response;
my.request({
url: '你的后端服務端',
data: encryptedData,
});
},
fail: (res) => {
console.log(res);
console.log('getPhoneNumber_fail');
},
});
}
文檔: https://opendocs.alipay.com/mini/api/getphonenumber
uni-app: 需使用 條件編譯 兼容兩個平台不同的寫法
<!-- template -->
<!-- #ifdef MP-WEIXIN -->
<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">授權手機號</button>
<!-- #endif -->
<!-- #ifdef MP-ALIPAY -->
<button open-type="getAuthorize" @getAuthorize="getAuthorize" @error="authError" ascope="phoneNumber"></button>
<!-- #endif -->
// js
// MP-WEIXIN
getPhoneNumber(res) {
console.log(res);
}
// MP-ALIPAY
getAuthorize() {
my.getPhoneNumber({
success: (res) => {
let encryptedData = res.response;
my.request({
url: '你的后端服務端',
data: encryptedData,
});
},
fail: (res) => {
console.log(res);
console.log('getPhoneNumber_fail');
},
});
}
文檔: https://uniapp.dcloud.io/component/button?id=button
四、訂閱模板消息
微信:
wx.requestSubscribeMessage({
tmplIds: [''],
success (res) { },
fail (err) {}
})
支付寶:
1、支付寶服務市場 訂購支付寶小程序消息訂閱插件
2、開發者登錄 開放平台控制台 > 找到已創建的小程序 > 點擊進入小程序管理后台 > 在版本管理頁面的 能力列表 部分點擊 添加能力 > 勾選** 模板消息** 能力並點擊 確定 完成能力添加。
3、使用:
// app.json 引入消息模板插件
{
"pages": [
"pages/index/index"
],
"plugins": {
"subscribeMsg": {
"version": "*",
"provider": "2021001155639035"
}
}
}
// index.json
{
"usingComponents": {
"subscribe-msg": "plugin://subscribeMsg/subscribe-msg"
}
}
<!-- index.axml -->
<!-- 引入組件 -->
<subscribe-msg />
// index.js
const { requestSubscribeMessage } = requirePlugin('subscribeMsg');
// 調用方法,喚起訂閱組件
requestSubscribeMessage({
// 模板id列表,最多3個
entityIds: templateList,
// 接收結果的回調方法
callback(res) {
console.log('訂閱回調', res);
if (res.success) {
} else {
}
},
});
文檔:
https://opendocs.alipay.com/mini/introduce/message
https://opendocs.alipay.com/mini/01rqd3
https://opendocs.alipay.com/mini/01rnqx
uni-app: 需使用 條件編譯 兼容兩個平台不同的寫法
// manifest.json 引入消息模板插件
{
"mp-alipay" : {
"usingComponents" : true,
"appid" : "",
"plugins": {
"subscribeMsg": {
"version": "*",
"provider": "2021001155639035"
}
}
},
}
// pages.json 這里是全局引入,可以單獨頁面組件引入
{
"globalStyle": {
"usingComponents": {
// #ifdef MP-ALIPAY
"subscribe-msg": "plugin://subscribeMsg/subscribe-msg"
// #endif
}
},
}
<!-- template -->
<!-- #ifdef MP-WEIXIN-->
<button @tap="requestSubscribeMessage"></button>
<!-- #endif -->
<!-- #ifdef MP-ALIPAY -->
<!-- 引入消息訂閱組件 -->
<subscribe-msg />
<!-- #endif -->
// js
requestSubscribeMessage() {
// #ifdef MP-WEIXIN
uni.requestSubscribeMessage({
tmplIds: [tmplId],
success: res => { },
fail: res => { },
complete: res => {}
});
// #endif
// #ifdef MP-ALIPAY
const { requestSubscribeMessage } = requirePlugin('subscribeMsg');
requestSubscribeMessage({
entityIds: [tmplId],
callback(res) {
console.log('訂閱回調', res);
},
});
// #endif
}
文檔:https://uniapp.dcloud.io/api/other/requestSubscribeMessage?id=requestsubscribemessage
五、獲取用戶收貨地址
微信:
wx.chooseAddress({
success: (res) => {
}
})
文檔: https://developers.weixin.qq.com/miniprogram/dev/api/open-api/address/wx.chooseAddress.html
支付寶:
my.getAddress({
success: (res) => {
}
});
文檔: https://opendocs.alipay.com/mini/api/lymgfk
uni-app: 統一使用 uni.chooseAddress
uni.chooseAddress({
success(res) {
}
})
文檔: https://uniapp.dcloud.io/api/other/choose-address?id=chooseaddress
六、發起支付
微信:
wx.requestPayment({
timeStamp: '',
nonceStr: '',
package: '',
signType: 'MD5',
paySign: '',
success (res) { },
fail (res) { }
})
文檔: https://developers.weixin.qq.com/miniprogram/dev/api/open-api/payment/wx.requestPayment.html
支付寶:
my.tradePay({
// 調用統一收單交易創建接口(alipay.trade.create),獲得返回字段支付寶交易號trade_no
tradeNO: "trade_no",
success: (res) => {
my.alert({
content: JSON.stringify(res),
});
},
fail: (res) => {
my.alert({
content: JSON.stringify(res),
});
}
});
文檔: https://opendocs.alipay.com/mini/api/openapi-pay
uni-app: 統一使用 uni.requestPayment
let payParams = {};
// #ifdef MP-WEIXIN
payParams = {
provider: "wxpay",
timeStamp: timeStamp,
nonceStr: nonceStr,
package: package,
signType: signType,
paySign: paySign,
};
// #endif
// #ifdef MP-ALIPAY
payParams = {
provider: "alipay",
orderInfo: 'tradeNO',
};
// #endif
uni.requestPayment({
...payParams,
success: (res) => {
},
fail: (err) => {
},
complete: () => {
},
});
文檔: https://uniapp.dcloud.io/api/plugins/payment?id=requestpayment
七、樣式和組件兼容
1、在普通 css 寫法里,upx 會被編譯器編譯。但動態綁定時,upx 無法被准確編譯。官方也修改了 uni-app 文檔中關於尺寸單位的介紹,不再推薦 upx 的使用,而推薦 rpx。
文檔: https://ask.dcloud.net.cn/article/36130
2、class 類寫法兼容
// 支付寶內不能使用,運行頁面會報錯
:class="[boolean && 'orange']"
// 可以使用寫法
:class="['orange', className]"
:class="{'orange': boolean}"
:class="[{'orange': boolean}, className]"
3、不能直接在自定義組件上添加 class ,class 不生效,需在引入自定義組件時套一層 view 兼容,class 放在 view 層
// 無效使用
<icon class="iconicon_guanbi" color="#CCCCCC" size="22rpx" icon="iconicon_guanbi" />
// 兼容寫法
<view class="iconicon_guanbi" >
<iconcolor="#CCCCCC" size="22rpx" icon="iconicon_guanbi" />
</view>
4、支付寶小程序內 picker-view 組件不能用 v-show ,顯示隱藏使用 v-if
5、支付寶小程序內 span 、 label、 自定義組件 綁定事件不生效,建議事件綁定使用 div 或者 view
6、控制顯示隱藏組件使用 v-if,支付寶小程序內v-show 不起作用
7、支付寶 uni.showLoading 和 uni.showModal 方法無 mask 屬性,需兼容,不然會有一堆警告
uni.showLoading({
title: "正在加載...",
// #ifdef MP-WEIXIN
mask: true,
// #endif
});
uni.showModal({
title: "提示",
content: "是否刪除",
// #ifdef MP-WEIXIN
mask: true,
// #endif
});
8、支付寶默認全部頁面開啟下拉加載 allowsBounceVertical:true,微信默認是關閉的 enablePullDownRefresh:false ,把支付默認值也設置不開啟
page.json
"globalStyle": {
// #ifdef MP-ALIPAY
"allowsBounceVertical": "NO",
// #endif
}
八、關聯普通二維碼
微信流程:https://developers.weixin.qq.com/miniprogram/introduction/qrcode.html#測試調試
支付寶流程:https://opendocs.alipay.com/mini/operation/vzd5v0
九、支付寶獲取掃碼進入參數
當前頁面的 onLoad 方法獲取不到掃碼的 options
可以使用 my.getLaunchOptionsSync 方法從 onLaunch 獲取
onLoad(options) {
// #ifdef MP-ALIPAY
let launchOptions = my.getLaunchOptionsSync();
console.log('launchOptions:', launchOptions);
// 兼容支付寶掃碼進入小程序只能從onLaunch獲取參數
if(!options && launchOptions.scene == '1011' && launchOptions.query) {
options = launchOptions.query;
}
// #endif
}
文檔: https://opendocs.alipay.com/mini/api/getLaunchOptionsSync
十、支付寶真機開發調試
1、可以打開調試查看打印輸出;
2、打開聯調設置=>聯調掃碼版本,掃線上小程序碼或跳轉時,默認跳轉到當前掃碼開發版本;

十一、通用管理小程序更新
使用 uni.getUpdateManager 的 onCheckForUpdate 判斷是否有更新
const getUpdateManager = () => {
// 獲取小程序更新機制兼容
if (uni.canIUse("getUpdateManager")) {
const updateManager = uni.getUpdateManager();
updateManager.onCheckForUpdate((res) => {
// 請求完新版本信息的回調
if (res.hasUpdate) {
updateManager.onUpdateReady(() => {
// 新的版本已經下載好,調用 applyUpdate 應用新版本並重啟
updateManager.applyUpdate();
});
updateManager.onUpdateFailed(() => {
// 新的版本下載失敗
uni.showModal({
title: "已經有新版本了喲~",
content: "新版本已經上線啦~,請您刪除當前小程序,重新搜索打開喲~"
});
});
}
});
} else {
// 如果希望用戶在最新版本的客戶端上體驗您的小程序,可以這樣子提示
uni.showModal({
title: "提示",
content:
"當前微信版本過低,無法使用該功能,請升級到最新微信版本后重試。"
});
}
};
文檔: https://uniapp.dcloud.io/api/other/update?id=getupdatemanager
十二、uni-app接入友盟
1.注冊友盟+賬號
2.友盟官網申請小程序appkey
3.配置域名白名單等
4.安裝sdk
npm install umtrack-alipay --save
npm install umtrack-wx --save
5.利用條件編譯集成sdk
main.js
import Vue from 'vue';
import App from './App';
// #ifdef MP-WEIXIN
import uma from 'umtrack-wx';
// #endif
// #ifdef MP-ALIPAY
import uma from 'umtrack-alipay';
// #endif
if(monitorSwitch) { // 監控開關
uma.init({
// #ifdef MP-WEIXIN
appKey:'appKey', // 微信小程序appKey
// #endif
// #ifdef MP-ALIPAY
appKey:'appKey', // 支付寶小程序appKey
// #endif
// #ifdef MP-WEIXIN
useOpenid: true, // 是否使用openid進行統計,此項為false時將使用友盟+隨機ID進行用戶統計。使用openid來統計微信小程序的用戶,會使統計的指標更為准確,對系統准確性要求高的應用推薦使用OpenID。
autoGetOpenid: false, // 是否需要通過友盟后台獲取openid,如若需要,請到友盟后台設置appId及secret
// #endif
debug: false, // 是否打開調試模式
uploadUserInfo: true, // 上傳用戶信息,上傳后可以查看有頭像的用戶分享信息,同時在查看用戶畫像時,公域畫像的准確性會提升。
enableVerify: true // 剪切板功能是用於埋點驗證獲取測試設備信息的;當開啟為true時,用戶側可能會被提示獲取剪切板信息;請確認線上發布版本設置為false;在進行發版前埋點驗證工作時,可以參數設置為true
});
uma.install = function (Vue) {
Vue.prototype.$uma = uma;
};
Vue.use(uma);
}
Vue.config.productionTip = false;
App.mpType = 'app';
const app = new Vue({
...App
});
app.$mount();
6.自定義事件
onLoad(){
this.$uma.trackEvent('eventID',{pa:'fff'});
},