uniapp苹果支付

79 阅读1分钟

参考文章uniapp文档

流程

step1|✨manifest.json文件中勾选Apple应用内支付

image.png

step2|✨调用getAppleChannel(productId)函数即可调起苹果支付

// ****苹果支付相关方法-start****
getAppleChannel(productId) {
    let that = this
    uni.showLoading({
        title: '检测支付环境...',
        mask: true
    })
    plus.payment.getChannels((channels) => {
        for (let i in channels) {
            // 1. 判断是否支持苹果支付
            if (channels[i].id === 'appleiap') {
                // 这里的iapChannel需要提前在data中声明
                that.iapChannel = channels[i];
                // 2. 校验产品ID是否上架App Store
                that.compareAppleProduce(productId)
            }
        }
     }, (err) => {
        uni.hideLoading()
        uni.showToast({
            title: "获取支付通道失败:" + err.message,
            icon: 'none'
        })
    })
},
// 校验苹果产品可以支付
compareAppleProduce(productId) {
    let that = this
    that.iapChannel.requestOrder([productId], (event) => {
        uni.hideLoading()
        // 这里使用for循环是为了适配多产品ID情况
        for (let index in event) {
            // 需要产品id和自定义交易id
            that.applePay(productId)
        }
    }, (err) => {
        uni.hideLoading()
        uni.showToast({
            title: "该商品未录入:" + err.message,
            icon: 'none'
        })
    })
},
//苹果支付
applePay(productId) {
    let that = this
    uni.showLoading({
        title: '支付中...',
        mask: true
    })
    uni.requestPayment({
        provider: 'appleiap',
        orderInfo: {
                productid: productId
        },
        async success(res) {
            // 检验苹果支付是否支付成功
            BaseCenterApi.voucher({voucher: res.transactionReceipt}).then(res => {
                if(res.code != 1) {
                    uni.$u.toast('支付失败');
                }else {
                    uni.$u.toast('支付成功');
                    setTimeout(() => {
                        uni.navigateTo({
                            url: '/pages/mine/tool/transactionDetail'
                        })
                    }, 500);
                }
            })
        },
        fail(e) {
            uni.$u.toast('支付已取消');
        },
        complete() {
            uni.hideLoading()
        }
    })
}
// ****苹果支付相关方法-end****