1、app.vue
``` vue
<template>
</template>
<script>
export default {
globalData: {
PrivacyProtocol: {
needAuthorization: true,
title: ''
}
},
methods: {
checkUserPrivacyProtocol() {
if (wx.getPrivacySetting) {
wx.getPrivacySetting({
success: res => {
console.log(res)
this.globalData.PrivacyProtocol.needAuthorization = res.needAuthorization
if (res.needAuthorization) {
// 需要弹出隐私协议
this.globalData.PrivacyProtocol.title = res.privacyContractName
}
}
})
}
}
}
async onLaunch(option) {
// 检测用户是否需要提示隐私协议
await this.checkUserPrivacyProtocol()
},
}
</script>
2、使用mixin封装
export default {
data() {
return {
showPrivacyPopup: false, // 是否需要弹出协议
PrivacyPopupTitle: '', // 小程序协议名称
resolvePrivacyAuthorization: null // wx.onNeedPrivacyAuthorization的回调
};
},
created() {},
methods: {
// 打开弹窗
openPrivacyPopup() {
const app = getApp()
this.PrivacyPopupTitle = app.globalData.PrivacyProtocol.title
this.showPrivacyPopup = true
},
// 关闭弹窗
closePrivacyPopup() {
this.showPrivacyPopup = false
},
// 用户点击同意
handleAgreePrivacyAuthorization() {
console.log('点击了同意');
this.resolvePrivacyAuthorization({
buttonId: 'agree-btn',
event: 'agree'
})
this.showPrivacyPopup = false
},
// 用户点击拒绝
handleRefusePrivacyAuthorization() {
uni.showModal({
content: '如果拒绝,我们将无法获取您的信息, 包括手机号、位置信息、相册等该小程序十分重要的功能,您确定要拒绝吗?',
success: (res) => {
if (res.confirm) {
const app = getApp()
console.log('点击了拒绝', this.resolvePrivacyAuthorization);
this.resolvePrivacyAuthorization({
event: 'disagree'
})
this.closePrivacyPopup()
this.$log.warn(`用户${app.globalData.userInfo?.Name || ''}拒绝了隐私请求,无法使用相关微信的Api`)
}
}
})
},
// 打开隐私协议
onClickPrivacyPopupTitle() {
wx.openPrivacyContract({})
},
// 监听调用微信api的函数
saveWXCallBack() {
if (wx.onNeedPrivacyAuthorization) {
wx.onNeedPrivacyAuthorization(resolve => {
this.resolvePrivacyAuthorization = resolve
this.openPrivacyPopup()
})
}
}
}
};
3、main.js引入
import PrivacyProtocol from "./utils/PrivacyProtocol.js"
Vue.mixin(PrivacyProtocol)
4、页面使用
<template>
<view class="box">
xxxxx
<u-popup :show="showPrivacyPopup" :closeOnClickOverlay="false" :round="10" mode="bottom"
@close="closePrivacyPopup()">
<view style="padding: 40rpx">
<p style="text-align: center;margin-bottom: 40rpx;font-size: 20px;font-weight: 700;">提示</p>
<text> 在你使用服务之前,请仔细阅读<text @click="onClickPrivacyPopupTitle()"
style="color: #29B7A3;">{{PrivacyPopupTitle}}</text>。如果你同意{{PrivacyPopupTitle}},请点击“同意”开始使用。
</text>
<view class="display-style" style="margin-top: 40rpx;">
<u-button text="拒绝" @click="handleRefusePrivacyAuthorization()"></u-button>
<button id="agree-btn" class="btn-agree" open-type="agreePrivacyAuthorization"
@agreeprivacyauthorization="handleAgreePrivacyAuthorization()">同意</button>
</view>
</view>
</u-popup>
</view>
</template>
<script>
export default {
onLoad(option) {
this.saveWXCallBack()
},
}
</script>