Google Play Billing v5如何正确获取商品价格
Google Play Billing v5 版本获取商品价格的实现方式
Google Play Billing Library 从v5版本开始重构了商品模型,移除了旧版SkuDetails类上直接暴露的price属性,所有定价信息按商品类型封装在ProductDetails的对应子字段中,取值逻辑和旧版一致,只是字段路径做了拆分:
- 一次性内购商品(inapp类型)
定价信息统一挂载在oneTimePurchaseOfferDetails节点下:- 需要直接展示给用户的带货币符号的本地化价格,取
productDetails.oneTimePurchaseOfferDetails.formattedPrice即可,返回值和旧版SkuDetails.price完全一致 - 如果需要做价格计算,可在同节点取
priceAmountMicros(价格微单位,1000000微单位=1当地货币单位)、priceCurrencyCode(ISO 4217格式货币代码)字段
- 需要直接展示给用户的带货币符号的本地化价格,取
- 订阅商品(subs类型)
订阅支持配置多基础计划、多优惠档位,定价信息挂载在subscriptionOfferDetails列表中,需要先匹配到你要查询的对应offer再取价:- 遍历
productDetails.subscriptionOfferDetails列表,通过basePlanId、offerId匹配到目标档位 - 找到对应档位下的
pricingPhases.pricingPhaseList,这是订阅各计费阶段的定价集合(比如免费试用+首月折扣+原价续费的场景会返回3个阶段对象) - 取对应计费阶段对象的
formattedPrice就是可直接展示的本地化价格,同样支持取priceAmountMicros、priceCurrencyCode做计算
- 遍历
常用取值的Kotlin代码参考:
/** * 获取一次性内购的展示价格 */ fun getOneTimeProductDisplayPrice(productDetails: ProductDetails): String { return productDetails.oneTimePurchaseOfferDetails?.formattedPrice.orEmpty() } /** * 获取订阅指定基础计划、无优惠的常规续费价格 */ fun getSubscriptionRegularPrice( productDetails: ProductDetails, targetBasePlanId: String ): String { // 匹配目标基础计划下无额外优惠的base offer val targetOffer = productDetails.subscriptionOfferDetails ?.firstOrNull { it.basePlanId == targetBasePlanId && it.offerId == null } // 取最后一个计费阶段的价格,即为常规续费价格 return targetOffer ?.pricingPhases ?.pricingPhaseList ?.lastOrNull() ?.formattedPrice .orEmpty() }
注意:所有面向用户展示的价格文本请直接使用接口返回的
formattedPrice字段,不要自行拿价格数值拼接货币符号。该字段已经根据用户Play账号的当前地区做了格式适配,能自动匹配当地的货币符号、小数位规则、价格书写习惯,避免出现格式错误。
内容的提问来源于stack exchange,提问作者Jay N
相关产品推荐
相关产品推荐

