在做苹果支付之前首先要有苹果开发者账号,在测试的时候需要在开发者中心设置沙盒账号,app未上架之前正式环境测试有问题,一般沙盒环境测试正常,就没有问题。
苹果支付需要苹果产品id,在苹果开发者官网设置
页面样式根据项目原型需求自己定义就好,这里就不做展示了
1.首先根据plus.payment.getChannels()验证是否有苹果支付功能,同时获取支付通道当中的产品列表,拿到里面平台申请拿到的内购产品i的id,后续的支付需要苹果产品id才能走下去。
created() {
this.iphonepay()
},
methods: {
// 验证是否有苹果支付功能
iphonepay() {
let that = this
plus.payment.getChannels((res) => {
let channel = res.find(i => i.id === 'appleiap')
that.iapChannel = channel ? channel : null
that.requestOrder()
})
},
//获取支付通道 使用所有的产品列表去检测 that.productIds 这个自己定义获取
requestOrder() {
let that = this
// this.productIds 是平台申请拿到的内购商品的id
that.iapChannel.requestOrder(that.productIds, function(event) {
console.log(event)
if(!that.list[0].productid){
event.forEach((v,i)=>{
that.list.map((x,y)=>{
if(v.price==x.price){
return x.productid = v.productid
}
})
})
}
}, function(erroemsg) {
uni.hideLoading()
uni.showToast({
title: "获取支付通道失败:" + errormsg.message,
icon: 'none'
})
})
},
},
2.第二部就和普通的支付差不多了,都是根据后端的提供接口,来获取订单ID,但是不同的是这里需要上传商品id是我们之前从支付通道当中取到的苹果商品id
Recharge() {
uni.showLoading({
title: '支付加载中',
mask: true
});
if (this.value == "appleiap") {
// 生成订单接口
this.$req(api.Recharge, {
payType: 6,//支付类型 后端定义
salePointTypeId: this.list[this.tabIndex].salePointTypeId //苹果商品id
}, 'POST', ).then(res => {
if (res.code == 200) {
this.orderid = res.data //订单id
// 苹果支付
this.topays(this.list[this.tabIndex].productid)
} else {
uni.hideLoading();
uni.showToast({
title: res.msg,
duration: 1000,
icon: 'none'
});
}
})
}
}
然后就是通过plus.payment.request()方法根据苹果产品id吊起苹果手机的支付功能,支付完成后需要调用向苹果中心验证支付成功的接口,有后端提供
//苹果支付
topays(id) {
const that = this
uni.showLoading({
title: '充值中请勿离开',
mask: true
})
plus.payment.request(that.iapChannel, {
productid: id,//苹果产品id 必填
username: '购买上架点',//支付功能名称,不必填
optimize: true // 支付时设置 optimize: true
}, function(res) {
// 支付信息
const receipt = res.transactionReceipt
// 后端向苹果中心验证支付成功的接口
that.$req(api.setIapCertificate, {
receipt,
chooseEnv: false,
orderNo: that.orderid, // 这里就算第二步里获取的订单ID
totalAmount: that.list[that.tabIndex].price
}, 'GET').then(ress => {
uni.hideLoading()
if (ress.code == 200) {
uni.showToast({
title: '充值成功'
})
} else {
uni.showToast({
title: ress.msg,
duration: 1000,
icon: 'none'
});
}
})
}, function(err) {
console.log(err)
uni.hideLoading()
uni.showModal({
content: "支付失败",
showCancel: false
})
})
},