跳到主要内容

参考代码 - Uniapp框架支付

示例代码:

<template>
<view class="page">
<web-view
v-if="webviewSrc"
:src="webviewSrc"
:update-title="false"
@message="handleMessage"
/>
</view>
</template>

<script>
function isArray(value) {
return Object.prototype.toString.call(value) === '[object Array]'
}

export default {
name: 'PageVip',
data() {
return {
webviewSrc: null,
}
},
async mounted() {
this.webviewSrc = '用户的付费界面paywallUrl'
},
methods: {
_extractEventData(event) {
let eventData = event.detail.data
if (!isArray(eventData)) {
eventData = [eventData]
}
for (let item of eventData) {
if (item?.type === 'requestPayment') {
return item
}
}
return null
},
_invokeCallback(callback, data) {
let currentWebview = this.$scope.$getAppWebview()
let wvNode = currentWebview.children()[0]
let dataJson = JSON.stringify(data)
wvNode.evalJS(`window.${callback}(${dataJson})`)
},
handleMessage(event) {
console.log('Vip handleMessage', event)
let eventData = this._extractEventData(event)
if (!eventData) {
return
}
const { request, callback } = eventData
uni.requestPayment({
...request,
success: (res) => {
console.log('Payment success', res)
this._invokeCallback(callback, { success: true, data: res })
},
fail: (err) => {
console.log('Payment fail', err)
uni.showToast({ title: '支付未完成', icon: 'none' })
this._invokeCallback(callback, { success: false, data: err })
},
})
},
},
}
</script>

<style></style>

基于 Uniapp Webview 实现,目前支持安卓端支付宝和微信支付(理论上支持所有 uni.requestPayment 支持的支付方式)。