如何在Google Play Billing 5中查询多个产品详情?
在Google Play Billing 5中批量查询产品详情的方法
要批量查询多个产品的详情,核心是在setProductList中传入多个Product实例——虽然单个Product的setProductId仅支持传入一个字符串,但setProductList接受的是产品集合,你可以为每个要查询的产品创建独立的Product对象,再统一放入列表中即可实现批量查询。
修改后的示例代码如下:
QueryProductDetailsParams queryProductDetailsParams = QueryProductDetailsParams.newBuilder() .setProductList( ImmutableList.of( // 第一个产品:订阅类型 Product.newBuilder() .setProductId("sub_product_1") .setProductType(ProductType.SUBS) .build(), // 第二个产品:一次性付费商品类型 Product.newBuilder() .setProductId("inapp_product_1") .setProductType(ProductType.INAPP) .build(), // 可继续添加更多需要查询的产品 Product.newBuilder() .setProductId("sub_product_2") .setProductType(ProductType.SUBS) .build())) .build(); billingClient.queryProductDetailsAsync( queryProductDetailsParams, new ProductDetailsResponseListener() { public void onProductDetailsResponse(BillingResult billingResult, List<ProductDetails> productDetailsList) { // 先校验请求是否成功 if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) { // 遍历返回的产品详情列表,逐个处理 for (ProductDetails details : productDetailsList) { String productId = details.getProductId(); String title = details.getTitle(); // 根据产品类型获取对应价格信息 String formattedPrice = details.getOneTimePurchaseOfferDetails() != null ? details.getOneTimePurchaseOfferDetails().getFormattedPrice() : details.getSubscriptionOfferDetails().get(0).getPricingPhases().getPricingPhaseList().get(0).getFormattedPrice(); // 这里添加你的业务逻辑处理 } } else { // 处理请求失败场景,比如网络异常、产品ID无效等 } } } );
关键说明:
- 每个
Product对象需单独配置productId和productType(ProductType.SUBS对应订阅类产品,ProductType.INAPP对应一次性付费商品)。 - 返回的
productDetailsList会包含所有查询成功的产品详情,顺序与你传入的产品列表一致。 - 必须先判断
billingResult的响应码,确认请求成功后再处理产品列表,避免空指针或无效数据问题。
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

