uniapp 苹果支付内购示例代码

2024-03-28 22:52

本文主要是介绍uniapp 苹果支付内购示例代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

// #ifdef APPasync init() {uni.showLoading({title: '检测支付环境...'});try {// 初始化,获取iap支付通道await this._iap.init();// 从苹果服务器获取产品列表this.productList = await this._iap.getProduct();this.productList[0].checked = true;this.productId = this.productList[0].productid;console.log('this.productId',this.productId);console.log('this.productList',this.productList);} catch (e) {uni.showModal({title: "init",content: e.message,showCancel: false});} finally {uni.hideLoading();}if (this._iap.ready) {this.restore();}},async restore() {// 检查上次用户已支付且未关闭的订单,可能出现原因:首次绑卡,网络中断等异常// 在此处检查用户是否登陆uni.showLoading({title: '正在检测已支付且未关闭的订单...'});try {// 从苹果服务器检查未关闭的订单,可选根据 username 过滤,和调用支付时透传的值一致const transactions = await this._iap.restoreCompletedTransactions({username: this.userInfo.user_name});if (!transactions.length) {return;}// 开发者业务逻辑,从服务器获取当前用户未完成的订单列表,和本地的比较// 此处省略switch (transaction.transactionState) {case IapTransactionState.purchased:// 用户已付款,在此处请求开发者服务器,在服务器端请求苹果服务器验证票据//let result = await this.validatePaymentResult();// 验证通过,交易结束,关闭订单// if (result) {//   await this._iap.finishTransaction(transaction);// }break;case IapTransactionState.failed:// 关闭未支付的订单await this._iap.finishTransaction(transaction);break;default:break;}} catch (e) {uni.showModal({content: e.message,showCancel: false});} finally {uni.hideLoading();}},async payment() {if (this.loading == true) {return;}this.loading = true;uni.showLoading({title: '支付处理中...'});try {// 请求苹果支付const transaction = await this._iap.requestPayment({productid: this.productId,manualFinishTransaction: true,username: this.userInfo.user_name});console.log(transaction,'transaction');const res = await this.$service.getApplePaySign({receipt: transaction.transactionReceipt,id: this.detail.data[this.activeId].id,time: this.active})console.log(res,'借口返回');uni.showToast({icon:'none',title: res.msg})//支付成功} catch (e) {console.log(e,'e');uni.showModal({content: e.message,showCancel: false});} finally {this.loading = false;uni.hideLoading();}},

使用前先创建并引入以下文件:

// uni iapconst ProviderType = {IAP: 'iap'
}const IapTransactionState = {purchasing: "0", // A transaction that is being processed by the App Store.purchased: "1", // A successfully processed transaction.failed: "2", // A failed transaction.restored: "3", // A transaction that restores content previously purchased by the user.deferred: "4" // A transaction that is in the queue, but its final status is pending external action such as Ask to Buy.
};class Iap {_channel = null;_channelError = null;_productIds = [];_ready = false;constructor({products}) {this._productIds = products;}init() {return new Promise((resolve, reject) => {this.getChannels((channel) => {this._ready = true;resolve(channel);}, (err) => {reject(err);})})}getProduct(productIds) {return new Promise((resolve, reject) => {this._channel.requestProduct(productIds || this._productIds, (res) => {resolve(res);}, (err) => {reject(err);})});}requestPayment(orderInfo) {return new Promise((resolve, reject) => {uni.requestPayment({provider: 'appleiap',orderInfo: orderInfo,success: (res) => {resolve(res);},fail: (err) => {reject(err);}});});}restoreCompletedTransactions(username) {return new Promise((resolve, reject) => {this._channel.restoreCompletedTransactions({manualFinishTransaction: true,username}, (res) => {resolve(res);}, (err) => {reject(err);})});}finishTransaction(transaction) {return new Promise((resolve, reject) => {this._channel.finishTransaction(transaction, (res) => {resolve(res);}, (err) => {reject(err);});});}getChannels(success, fail) {if (this._channel !== null) {success(this._channel)return}if (this._channelError !== null) {fail(this._channelError)return}uni.getProvider({service: 'payment',success: (res) => {this._channel = res.providers.find((channel) => {return (channel.id === 'appleiap')})if (this._channel) {success(this._channel)} else {this._channelError = {errMsg: 'paymentContext:fail iap service not found'}fail(this._channelError)}}});}get channel() {return this._channel;}
}export {Iap,IapTransactionState
}

效果图:

 需要注意的是,这里是沙盒环境,只能使用虚拟账号进行支付:

可以在下面这个页面进行添加账号:

Apple 内购申请流程: 苹果支付内购申请-CSDN博客

参考:uniapp开发对接IOS应用内支付

其他解决方案:

uni-pay:uni-pay - DCloud 插件市场

这篇关于uniapp 苹果支付内购示例代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/856914

相关文章

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

Python中logging模块用法示例总结

《Python中logging模块用法示例总结》在Python中logging模块是一个强大的日志记录工具,它允许用户将程序运行期间产生的日志信息输出到控制台或者写入到文件中,:本文主要介绍Pyt... 目录前言一. 基本使用1. 五种日志等级2.  设置报告等级3. 自定义格式4. C语言风格的格式化方法

Spring 中的切面与事务结合使用完整示例

《Spring中的切面与事务结合使用完整示例》本文给大家介绍Spring中的切面与事务结合使用完整示例,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录 一、前置知识:Spring AOP 与 事务的关系 事务本质上就是一个“切面”二、核心组件三、完

sky-take-out项目中Redis的使用示例详解

《sky-take-out项目中Redis的使用示例详解》SpringCache是Spring的缓存抽象层,通过注解简化缓存管理,支持Redis等提供者,适用于方法结果缓存、更新和删除操作,但无法实现... 目录Spring Cache主要特性核心注解1.@Cacheable2.@CachePut3.@Ca

QT Creator配置Kit的实现示例

《QTCreator配置Kit的实现示例》本文主要介绍了使用Qt5.12.12与VS2022时,因MSVC编译器版本不匹配及WindowsSDK缺失导致配置错误的问题解决,感兴趣的可以了解一下... 目录0、背景:qt5.12.12+vs2022一、症状:二、原因:(可以跳过,直奔后面的解决方法)三、解决方

MySQL中On duplicate key update的实现示例

《MySQL中Onduplicatekeyupdate的实现示例》ONDUPLICATEKEYUPDATE是一种MySQL的语法,它在插入新数据时,如果遇到唯一键冲突,则会执行更新操作,而不是抛... 目录1/ ON DUPLICATE KEY UPDATE的简介2/ ON DUPLICATE KEY UP

Python中Json和其他类型相互转换的实现示例

《Python中Json和其他类型相互转换的实现示例》本文介绍了在Python中使用json模块实现json数据与dict、object之间的高效转换,包括loads(),load(),dumps()... 项目中经常会用到json格式转为object对象、dict字典格式等。在此做个记录,方便后续用到该方

MySQL分库分表的实践示例

《MySQL分库分表的实践示例》MySQL分库分表适用于数据量大或并发压力高的场景,核心技术包括水平/垂直分片和分库,需应对分布式事务、跨库查询等挑战,通过中间件和解决方案实现,最佳实践为合理策略、备... 目录一、分库分表的触发条件1.1 数据量阈值1.2 并发压力二、分库分表的核心技术模块2.1 水平分