HarmonyOS掌上记账APP开发实践第63篇:鸿蒙 IAP 商品配置与管理 — 从订阅商品到权益验证

📅 2026/7/22 1:44:43
HarmonyOS掌上记账APP开发实践第63篇:鸿蒙 IAP 商品配置与管理 — 从订阅商品到权益验证
鸿蒙 IAP 商品配置与管理 — 从订阅商品到权益验证文章简介HarmonyOS 应用内支付IAPIn-App Purchases是鸿蒙生态中实现应用商业化的核心能力。MoneyTrack 作为一款记账应用提供了会员订阅功能允许用户购买自动续费订阅商品以解锁高级特性。本文从 IAP 商品配置的角度出发详细介绍商品从 AGC 配置到客户端查询、本地缓存的完整链路帮助开发者理解鸿蒙 IAP 商品管理的全流程。核心知识点1. IAP 商品配置完整流程IAP 商品配置涉及三个关键环节AppGallery Connect 后台配置、客户端 SDK 查询、本地缓存管理。以下流程图展示了完整链路是否AGC 控制台配置商品配置商品 ID/价格/描述发布应用版本客户端 iap.create 初始化调用 getProducts 查询商品查询成功?解析 iap.Product 列表读取本地缓存商品缓存商品信息到本地渲染会员商品列表用户点击购买发起 createPurchase2. iap.Product 的完整字段说明鸿蒙 IAP 的iap.Product接口定义了商品的完整信息开发者可通过这些字段向用户展示统一的商品信息界面字段类型说明productIdstring商品唯一标识需与 AGC 后台一致pricestring格式化后的价格字符串如 “¥6.00”microPricenumber价格微单位单位为分1 元 100descriptionstring商品描述文本支持多语言titlestring商品名称标题typeProductType商品类型CONSUMABLE / NONCONSUMABLE / AUTORENEWABLEstatusProductStatus商品状态ACTIVE / INACTIVEsubPeriodstring订阅周期描述仅 AUTORENEWABLE 类型有效在 MoneyTrack 中ProductInfo类封装了 IAP 商品与本地权益模型的映射关系确保商品信息在 UI 层以统一格式展示export class ProductInfo { type: iap.ProductType iap?.ProductType.AUTORENEWABLE; productId: string ; privileges: MemberShipPrivilege[] []; privacyName?: string ; privacyContent?: string ; }3. 商品价格格式化不同地区的用户看到的货币符号不同鸿蒙 IAP SDK 已自动处理本地化格式。iap.Product.price返回的字符串已包含正确的货币符号和格式开发者可直接用于 UI 展示。如果需要在本地自行格式化可参照以下逻辑function formatPrice(microPrice: number, currency: string): string { const price (microPrice / 100).toFixed(2); // 根据 currency 添加对应货币符号 const symbolMap: Recordstring, string { CNY: ¥, USD: $, JPY: ¥, EUR: €, }; return ${symbolMap[currency] || }${price}; }4. 商品缓存策略为了避免频繁调用 IAP SDK 查询商品列表网络请求耗时且可能失败MoneyTrack 采用「先缓存、兜底读」的策略。首次查询成功后将商品信息序列化后写入本地首选项Preferences后续启动时先读缓存展示再异步刷新// 商品缓存管理 async function cacheProducts(products: iap.Product[]): Promisevoid { const prefs await preferences.getPreferences(getContext(), iap_cache); const json JSON.stringify(products.map(p ({ productId: p.productId, price: p.price, title: p.title, description: p.description, }))); await prefs.put(products, json); await prefs.flush(); } async function getCachedProducts(): Promiseiap.Product[] | null { const prefs await preferences.getPreferences(getContext(), iap_cache); const json await prefs.get(products, ); return json ? JSON.parse(json) : null; }项目代码案例MemberShipVM 的完整商品管理代码MemberShipVM 是会员模块的核心 ViewModel管理商品列表的查询、缓存和购买入口。其productInfoList: iap.Product[]属性存储 IAP SDK 查询返回的商品信息视图层据此渲染会员卡片ObservedV2 export class MemberShipVM { Trace productInfoList: iap.Product[] []; Trace isMember: boolean false; Trace expiresTime: number 0; // 查询 IAP 商品并缓存 async queryProducts(): Promisevoid { try { const products await iap.getProducts([membership_monthly, membership_yearly]); this.productInfoList products; await cacheProducts(products); } catch (err) { hilog.error(0xFF00, MemberShipVM, queryProducts err: ${JSON.stringify(err)}); // 兜底读取本地缓存 const cached await getCachedProducts(); if (cached) this.productInfoList cached; } } // 发起购买 buyProduct(productId: string, type: iap.ProductType): void { // 购买前可加入安全环境检测 iap.createPurchase({ productId, type, subscribeCallBack: (params: iap.PurchaseParams) { if (params.finishStatus iap.FinishStatus.FINISHED) { // 支付成功进行服务端验证 this.handlePurchaseSuccess(params); } }, }); } private async handlePurchaseSuccess(params: iap.PurchaseParams): Promisevoid { // 将收据解码后发送至服务端验证 const payload JWSUtil.decodeJwsObj(params.receipt); await UserApis.subscribeMembership({ receipt: payload }); } }最佳实践商品 ID 命名规范建议采用功能_类型_周期格式如membership_autorenewable_monthly便于后期扩展多商品。缓存兜底策略网络异常时从本地缓存读取商品信息保证页面不白屏。同时设置缓存过期时间如 24 小时。价格展示一致性直接使用 IAP SDK 返回的price字段不做额外格式化避免汇率和本地化问题。商品状态校验每次展示商品前检查status字段避免显示已下架商品。推荐参考文档HarmonyOS IAP Kit 开发指南AppGallery Connect IAP 商品配置文档kit.IAPKit API 参考鸿蒙首选项Preferences数据存储指南