uniapp框架相容微信和支付寶小程式
本文對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-->
<!--#ifdefMP-WEIXIN-->
<button @tap="getUserProfile"></button>
<!--#endif-->
<!--#ifdefMP-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-->
<!--#ifdefMP-WEIXIN-->
<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">授權手機號</button>
<!--#endif-->
<!--#ifdefMP-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#%E6%B5%8B%E8%AF%95%E8%B0%83%E8%AF%95
支付寶流程: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'});
},
8. sdk整合位置儘量靠前
文件:https://github.com/umeng/mp-demos/tree/master/uniapp