Uni-App 苹果内购的实现

633 阅读1分钟

一、功能配置

配置苹果内购前,需要你的App ID 勾选了苹果支付功能,当然这需要你重新配置下profile文件,而且勾选好mainfest.json里的APP苹果支付。具体官方的配置详情在这

image.png

前往App Store Connect,添加App内购项目

image.png

当然,这里的内购项目是需要审核的,尽量填写规范

二、功能代码

页面的话设置一个支付按钮即可,如果有多个商品也可以加个多选;

data数据

data() {
    return {
            iapChannel: null,
            //这里是选中商品的ID
            productId: 'stylika_NDHY',
            //这里是所有商品的ID
            productIds: ['stylika_FMEM', 'stylika_YDHY', 'stylika_JDHY', 'stylika_NDHY']

      }

 }

初始化

onLoad: function() {

        plus.payment.getChannels((channels) => {
                // console.log("获取到channel" + JSON.stringify(channels))
                for (var i in channels) {
                    var channel = channels[i];

                    if (channel.id === 'appleiap') {
                        this.iapChannel = channel;
                        this.requestOrder();
                    }
                }

                if (!this.iapChannel) {
                    //暂不支持苹果 iap 支付
                }
                
        }, (error) => {
            //暂不支持苹果 iap 支付
        });
}

检测支付环境函数

requestOrder() {

    uni.showLoading({
        title: '检测支付环境',
        mask: true
    })

    //必须调用此方法才能进行 iap 支付
    this.iapChannel.requestOrder(this.productIds, (orderList) => {
        //检测成功
        uni.hideLoading();
    }, (e) => {
        uni.hideLoading();
        //暂不支持苹果 iap 支付
    });

}

订阅函数

iosSubcribed() {
    let that = this

    uni.requestPayment({
        provider: 'appleiap' ,
        orderInfo: {
                   productid: this.productId
        },
        success: (e) => {
            //传给后台交易数据
            that.$iHttp.post('/api/apple_pay/', {receipt: e.transactionReceipt}).then(res => {
                        //购买成功!
            }).catch(err => {
                        //购买失败!
            })
        },
        fail: (e) => {
        //购买失败!
        }
    })
}