Android集成goole内购

1.配置依赖项,在app下的build.gradle (此步骤后即可将app发布到测试轨道了)

dependencies {
    def billing_version = "5.0.0"
    implementation "com.android.billingclient:billing:$billing_version"
}

2.获取支付类实例,并传入支付结果监听器

    /**
     * 支付结果监听
     */
    private PurchasesUpdatedListener purchasesUpdatedListener = new PurchasesUpdatedListener() {
        @Override
        public void onPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases) {
            int responseCode = billingResult.getResponseCode();//支付结果状态码
            if (responseCode == BillingClient.BillingResponseCode.OK){
                if (purchases != null){
                    for (Purchase purchase : purchases) {
                        //处理购买结果
                        handlePurchase(purchase);
                    }
                }
            }
        }
    };

    /**
     * 获取支付类实例
     */
    private BillingClient billingClient = BillingClient.newBuilder(this)
            .setListener(purchasesUpdatedListener)
            .enablePendingPurchases()
            .build();

3.点击支付按钮

    /**
     * 点击支付,需要传入商品id,改商品id为google后台配置的商品唯一id
     * @param productId
     */
    private void payClick(String productId){
        if (isGoogleInAppPayConnect){
            //进行支付前的查询
            queryProductDetail("hogg.sgzjjp.money.60000");
        }else{
            startConnection("hogg.sgzjjp.money.60000");
        }
    }
    private boolean isGoogleInAppPayConnect = false;//是否和google内购服务建立连接
    /**
     * 建立支付服务连接
     * @param productId 为null则只是建立连接,比如断线重连,不为空则连接成功后支付
     */
    private void startConnection(String productId){
        billingClient.startConnection(new BillingClientStateListener() {
            @Override
            public void onBillingSetupFinished(BillingResult billingResult) {
                if (billingResult.getResponseCode() ==  BillingClient.BillingResponseCode.OK) {
                    isGoogleInAppPayConnect = true;
                    if (!TextUtils.isEmpty(productId)){
                        //点击支付后建立连接再支付,支付之前向进行支付前的查询
                        queryProductDetail(productId);
                    }
                }
            }
            @Override
            public void onBillingServiceDisconnected() {
                isGoogleInAppPayConnect = false;
                startConnection(null);//只是重新建立连接
            }
        });
    }
    /**
     * 在将商品展示给用户之前,查询商品详情是非常重要的一步,因为查询会返回本地化的商品信息
     * @param productId
     */
    private void queryProductDetail(String productId){
        List list = new ArrayList();
        list.add(QueryProductDetailsParams.Product.newBuilder()
                .setProductId(productId)
                .setProductType(BillingClient.ProductType.INAPP)
                .build());
        QueryProductDetailsParams queryProductDetailsParams =
                QueryProductDetailsParams.newBuilder()
                        .setProductList(list)
                        .build();

        billingClient.queryProductDetailsAsync(
                queryProductDetailsParams,
                new ProductDetailsResponseListener() {
                    public void onProductDetailsResponse(BillingResult billingResult,
                                                         List<ProductDetails> productDetailsList) {
                        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
                            if (productDetailsList != null && productDetailsList.size() > 0){//查询到了商品
                                inAppPay(productDetailsList.get(0));
                            }
                        }
                    }
                }
        );
    }

4.购买逻辑

    /**
     * 启动支付
     * @param productDetails
     */
    private void inAppPay(ProductDetails productDetails) {
        //启动支付要放到主线程
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                List list = new ArrayList();
                list.add(BillingFlowParams.ProductDetailsParams.newBuilder()
                        .setProductDetails(productDetails)
                        .setOfferToken(productDetails.getSubscriptionOfferDetails().get(0).getOfferToken())
                        .build());
                BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
                        .setProductDetailsParamsList(list)
                        .build();

                BillingResult billingResult = billingClient.launchBillingFlow(GoogleInappPay.this, billingFlowParams);
            }
        });
    }

5.购买后消耗逻辑,不消耗无法重复购买,有些时候可能消耗不成功,就有了6 的补单逻辑

    /**
     * 处理购买结果
     * @param purchase
     */
    private void handlePurchase(Purchase purchase) {
        int purchaseState = purchase.getPurchaseState();
        if (purchaseState == Purchase.PurchaseState.PURCHASED){//已支付
            ConsumeParams consumeParams =
                    ConsumeParams.newBuilder()
                            .setPurchaseToken(purchase.getPurchaseToken())
                            .build();

            ConsumeResponseListener listener = new ConsumeResponseListener() {
                @Override
                public void onConsumeResponse(BillingResult billingResult, String purchaseToken) {
                    if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                        // 消耗成功,发货
                    }
                }
            };

            billingClient.consumeAsync(consumeParams, listener);
        }
    }

6.补单逻辑,一般放在onResume方法里,根据业务需求调整

        billingClient.queryPurchasesAsync(
                QueryPurchasesParams.newBuilder()
                        .setProductType(BillingClient.ProductType.INAPP)
                        .build(),
                new PurchasesResponseListener() {
                    @Override
                    public void onQueryPurchasesResponse(@NonNull BillingResult billingResult, @NonNull List<Purchase> list) {
                        int responseCode = billingResult.getResponseCode();//支付结果状态码
                        if (responseCode == BillingClient.BillingResponseCode.OK){
                            if (list != null){
                                for (Purchase purchase : list) {
                                    //处理购买结果
                                    handlePurchase(purchase);
                                }
                            }
                        }
                    }
                }
        );
posted @ 2022-08-11 18:10  呢哇哦比较  阅读(1047)  评论(0)    收藏  举报