com.android.billingclient.api.BillingClient Java Examples

The following examples show how to use com.android.billingclient.api.BillingClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BillingManager.java    From play-billing-codelab with Apache License 2.0 11 votes vote down vote up
public BillingManager(Activity activity) {
    mActivity = activity;
    mBillingClient = BillingClient.newBuilder(mActivity).setListener(this).build();
    mBillingClient.startConnection(new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(@BillingClient.BillingResponse int billingResponse) {
            if (billingResponse == BillingClient.BillingResponse.OK) {
                Log.i(TAG, "onBillingSetupFinished() response: " + billingResponse);
            } else {
                Log.w(TAG, "onBillingSetupFinished() error code: " + billingResponse);
            }
        }
        @Override
        public void onBillingServiceDisconnected() {
            Log.w(TAG, "onBillingServiceDisconnected()");
        }
    });
}
 
Example #2
Source File: BillingManager.java    From UpdogFarmer with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onPurchasesUpdated(int responseCode, @Nullable List<Purchase> purchases) {
    if (responseCode == BillingClient.BillingResponse.OK && purchases != null) {
        for (Purchase purchase : purchases) {
            handlePurchase(purchase);
        }
        Log.i(TAG, "Purchases updated.");
        listener.onPurchasesUpdated(purchases);
    } else if (responseCode == BillingClient.BillingResponse.USER_CANCELED) {
        // Handle an error caused by a user canceling the purchase flow.
        Log.i(TAG, "Purchase canceled.");
        listener.onPurchaseCanceled();
    } else {
        // Handle any other error codes.
        Log.i(TAG, "Unknown error. Response code: " + responseCode);
    }
}
 
Example #3
Source File: GooglePlayBillingVendorTest.java    From Cashier with Apache License 2.0 6 votes vote down vote up
GooglePlayBillingVendor successfullyInitializedVendor() {
    GooglePlayBillingVendor vendor = new GooglePlayBillingVendor(api, TestData.TEST_PUBLIC_KEY);
    vendor.setLogger(logger);
    Vendor.InitializationListener initializationListener = mock(Vendor.InitializationListener.class);

    when(api.initialize(eq(context), eq(vendor), eq(vendor), any(Logger.class))).thenAnswer(new Answer<Boolean>() {
        @Override
        public Boolean answer(InvocationOnMock invocation) {
            LifecycleListener listener = invocation.getArgument(2);
            listener.initialized(true);
            return true;
        }
    });
    when(api.isBillingSupported(BillingClient.SkuType.INAPP)).thenReturn(BillingClient.BillingResponse.OK);
    when(api.isBillingSupported(BillingClient.SkuType.SUBS)).thenReturn(BillingClient.BillingResponse.OK);
    when(api.available()).thenReturn(true);

    vendor.initialize(context, initializationListener);

    return vendor;
}
 
Example #4
Source File: GoogleIap.java    From remixed-dungeon with GNU General Public License v3.0 6 votes vote down vote up
public void querySkuList(final List<String> skuList) {
    Runnable queryRequest = () -> {
        SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
        params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
        mBillingClient.querySkuDetailsAsync(params.build(),
                (billingResult, list) -> {
                    if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK
                            && list != null) {
                        mSkuDetails = new HashMap<>();
                        for (SkuDetails skuDetails : list) {
                            mSkuDetails.put(skuDetails.getSku().toLowerCase(Locale.ROOT), skuDetails);
                        }
                    }
                });
    };
    executeServiceRequest(queryRequest);
}
 
Example #5
Source File: ActivityBilling.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
private void onPurchase(Intent intent) {
    if (Helper.isPlayStoreInstall()) {
        BillingFlowParams.Builder flowParams = BillingFlowParams.newBuilder();
        if (skuDetails.containsKey(getSkuPro())) {
            Log.i("IAB purchase SKU=" + skuDetails.get(getSkuPro()));
            flowParams.setSkuDetails(skuDetails.get(getSkuPro()));
        }

        BillingResult result = billingClient.launchBillingFlow(this, flowParams.build());
        if (result.getResponseCode() != BillingClient.BillingResponseCode.OK)
            reportError(result, "IAB launch billing flow");
    } else
        try {
            Uri uri = Uri.parse(BuildConfig.PRO_FEATURES_URI + "?challenge=" + getChallenge(this));
            Helper.view(this, uri, true);
        } catch (NoSuchAlgorithmException ex) {
            Log.unexpectedError(getSupportFragmentManager(), ex);
        }
}
 
Example #6
Source File: AccelerateDevelop.java    From InviZible with GNU General Public License v3.0 6 votes vote down vote up
public void initBilling() {
    mBillingClient = BillingClient.newBuilder(activity)
            .enablePendingPurchases()
            .setListener(new PurchasesUpdatedListener() {
                @Override
                public void onPurchasesUpdated(BillingResult billingResult, @Nullable List<Purchase> purchasesList) {
                    if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && purchasesList != null) {
                        Log.i(LOG_TAG, "Purchases are updated");
                        handlePurchases(purchasesList);
                    }
                }
            }).build();

    CachedExecutor.INSTANCE.getExecutorService().submit(() -> {
        mBillingClient.startConnection(AccelerateDevelop.this);
    });
}
 
Example #7
Source File: BillingManager.java    From SchoolQuest with GNU General Public License v3.0 6 votes vote down vote up
private void onQueryPurchasesFinished(Purchase.PurchasesResult result) {
    if (mBillingClient == null || result.getResponseCode() != BillingClient.BillingResponse.OK) {
        Log.w(TAG, "Billing client was null or result code (" + result.getResponseCode()
                + ") was bad – quitting");
        return;
    }
    for (Purchase purchase: result.getPurchasesList()) {
        mBillingClient.consumeAsync(purchase.getPurchaseToken(), new ConsumeResponseListener() {
            @Override
            public void onConsumeResponse(int responseCode, String purchaseToken) {
                if (responseCode != BillingClient.BillingResponse.OK) {
                    startServiceConnection(null);
                }
            }
        });
    }
}
 
Example #8
Source File: ActivityBilling.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
private void onPurchaseCheck(Intent intent) {
    billingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP, new PurchaseHistoryResponseListener() {
        @Override
        public void onPurchaseHistoryResponse(BillingResult result, List<PurchaseHistoryRecord> records) {
            if (result.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                for (PurchaseHistoryRecord record : records)
                    Log.i("IAB history=" + record.toString());

                queryPurchases();

                ToastEx.makeText(ActivityBilling.this, R.string.title_setup_done, Toast.LENGTH_LONG).show();
            } else
                reportError(result, "IAB history");
        }
    });
}
 
Example #9
Source File: GooglePlayBillingVendorTest.java    From Cashier with Apache License 2.0 6 votes vote down vote up
@Test
public void initialize_successfully_when_subs_not_available() {
    GooglePlayBillingVendor vendor = new GooglePlayBillingVendor(api);
    vendor.setLogger(logger);
    Vendor.InitializationListener initializationListener = mock(Vendor.InitializationListener.class);

    mockSuccessfulInitialization(vendor);
    when(api.isBillingSupported(BillingClient.SkuType.INAPP)).thenReturn(BillingClient.BillingResponse.OK);
    when(api.isBillingSupported(BillingClient.SkuType.SUBS)).thenReturn(BillingClient.BillingResponse.FEATURE_NOT_SUPPORTED);
    when(api.available()).thenReturn(true);

    vendor.initialize(context, initializationListener);

    verify(api).initialize(eq(context), eq(vendor), eq(vendor), eq(logger));
    verify(initializationListener).initialized();
    assertTrue(vendor.available());
    assertTrue(vendor.canPurchase(TestData.productInappA));
    assertFalse(vendor.canPurchase(TestData.productSubA));
}
 
Example #10
Source File: GooglePlayBillingVendorTest.java    From Cashier with Apache License 2.0 6 votes vote down vote up
@Test
public void initialize_when_cannot_buy_anything() {
    GooglePlayBillingVendor vendor = new GooglePlayBillingVendor(api);
    vendor.setLogger(logger);
    Vendor.InitializationListener initializationListener = mock(Vendor.InitializationListener.class);

    mockSuccessfulInitialization(vendor);
    when(api.isBillingSupported(BillingClient.SkuType.INAPP)).thenReturn(BillingClient.BillingResponse.FEATURE_NOT_SUPPORTED);
    when(api.isBillingSupported(BillingClient.SkuType.SUBS)).thenReturn(BillingClient.BillingResponse.FEATURE_NOT_SUPPORTED);
    when(api.available()).thenReturn(true);

    vendor.initialize(context, initializationListener);

    verify(api).initialize(eq(context), eq(vendor), eq(vendor), eq(logger));
    verify(initializationListener).initialized();
    assertFalse(vendor.available());
    assertFalse(vendor.canPurchase(TestData.productInappA));
    assertFalse(vendor.canPurchase(TestData.productSubA));
}
 
Example #11
Source File: GooglePlayBillingVendorTest.java    From Cashier with Apache License 2.0 6 votes vote down vote up
@Test
public void purchase_user_canceled() {
    GooglePlayBillingVendor vendor = successfullyInitializedVendor();
    PurchaseListener listener = mock(PurchaseListener.class);
    mockApiPurchaseFailure(vendor, TestData.productInappA, BillingClient.BillingResponse.USER_CANCELED);

    vendor.purchase(activity, TestData.productInappA, null, listener);

    ArgumentCaptor<Vendor.Error> argumentError = ArgumentCaptor.forClass(Vendor.Error.class);
    ArgumentCaptor<Product> argumentProduct = ArgumentCaptor.forClass(Product.class);
    verify(listener).failure(argumentProduct.capture(), argumentError.capture());

    assertEquals( TestData.productInappA.sku(), argumentProduct.getValue().sku() );
    assertEquals(VendorConstants.PURCHASE_CANCELED, argumentError.getValue().code);

    // Should be able to make another purchase now
    vendor.purchase(activity, TestData.productInappA, null, listener);
}
 
Example #12
Source File: GooglePlayBillingVendorTest.java    From Cashier with Apache License 2.0 6 votes vote down vote up
@Test
public void initialize_successfully() {
    GooglePlayBillingVendor vendor = new GooglePlayBillingVendor(api);
    vendor.setLogger(logger);
    Vendor.InitializationListener initializationListener = mock(Vendor.InitializationListener.class);

    mockSuccessfulInitialization(vendor);
    when(api.isBillingSupported(BillingClient.SkuType.INAPP)).thenReturn(BillingClient.BillingResponse.OK);
    when(api.isBillingSupported(BillingClient.SkuType.SUBS)).thenReturn(BillingClient.BillingResponse.OK);
    when(api.available()).thenReturn(true);

    vendor.initialize(context, initializationListener);

    verify(api).initialize(eq(context), eq(vendor), eq(vendor), eq(logger));
    verify(initializationListener).initialized();
    assertTrue(vendor.available());
    assertTrue(vendor.canPurchase(TestData.productInappA));
    assertTrue(vendor.canPurchase(TestData.productSubA));
}
 
Example #13
Source File: TestHelper.java    From Cashier with Apache License 2.0 6 votes vote down vote up
static void mockSkuDetails(AbstractGooglePlayBillingApi api, String type, final Map<String, SkuDetails> skuDetailsMap) {
    doAnswer(
            new Answer() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    List<String> skus = invocation.getArgument(1);
                    SkuDetailsResponseListener listener = invocation.getArgument(2);
                    List<SkuDetails> result = new ArrayList<>();
                    for (String sku : skus) {
                        result.add(skuDetailsMap.get(sku));
                    }
                    listener.onSkuDetailsResponse(BillingClient.BillingResponse.OK, result);
                    return null;
                }
            }
    ).when(api).getSkuDetails(
            eq(type),
            Mockito.<String>anyList(),
            any(SkuDetailsResponseListener.class));
}
 
Example #14
Source File: BillingManager.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
public void querySkuDetailsAsync(@BillingClient.SkuType final String itemType,
                                 final List<String> skuList, final SkuDetailsResponseListener listener) {
    // Specify a runnable to start when connection to Billing client is established
    Runnable executeOnConnectedService = new Runnable() {
        @Override
        public void run() {
            SkuDetailsParams skuDetailsParams = SkuDetailsParams.newBuilder()
                    .setSkusList(skuList).setType(itemType).build();
            mBillingClient.querySkuDetailsAsync(skuDetailsParams,
                    new SkuDetailsResponseListener() {
                        @Override
                        public void onSkuDetailsResponse(@NonNull BillingResult billingResult, List<SkuDetails> skuDetailsList) {
                            listener.onSkuDetailsResponse(billingResult, skuDetailsList);
                        }
                    });
        }
    };

    // If Billing client was disconnected, we retry 1 time and if success, execute the query
    startServiceConnectionIfNeeded(executeOnConnectedService);
}
 
Example #15
Source File: InventoryQueryTest.java    From Cashier with Apache License 2.0 6 votes vote down vote up
@Test
public void returns_error_when_sub_purchases_call_fails() {
    when(api.getPurchases(BillingClient.SkuType.SUBS)).thenReturn(null);
    when(api.getPurchases(BillingClient.SkuType.INAPP)).thenReturn(new ArrayList<Purchase>());

    InventoryListener listener = mock(InventoryListener.class);
    InventoryQuery.execute(
            TestHelper.mockThreading(),
            api,
            listener,
            TestData.allInAppSkus,
            TestData.allSubSkus
    );

    verify(listener).failure(any(Vendor.Error.class));
}
 
Example #16
Source File: ActivityBilling.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
private void querySkus(List<String> query) {
    Log.i("IAB query SKUs");
    SkuDetailsParams.Builder builder = SkuDetailsParams.newBuilder();
    builder.setSkusList(query);
    builder.setType(BillingClient.SkuType.INAPP);
    billingClient.querySkuDetailsAsync(builder.build(),
            new SkuDetailsResponseListener() {
                @Override
                public void onSkuDetailsResponse(BillingResult result, List<SkuDetails> skuDetailsList) {
                    if (result.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                        for (SkuDetails skuDetail : skuDetailsList) {
                            Log.i("IAB SKU detail=" + skuDetail);
                            skuDetails.put(skuDetail.getSku(), skuDetail);
                            for (IBillingListener listener : listeners)
                                listener.onSkuDetails(skuDetail.getSku(), skuDetail.getPrice());
                        }
                    } else
                        reportError(result, "IAB query SKUs");
                }
            });
}
 
Example #17
Source File: BillingManager.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
@Override
public void onPurchasesUpdated(BillingResult billingResult, @Nullable List<Purchase> purchases) {
    int responseCode = billingResult.getResponseCode();
    //PPApplication.logE(TAG, "onPurchasesUpdated() response: " + responseCode);
    if (responseCode == BillingClient.BillingResponseCode.OK) {
        getFragment().purchaseSuccessful(purchases);

        if (purchases != null) {
            for (Purchase purchase : purchases) {
                consumePurchase(purchase);
            }
        }
    }
    else {
        getFragment().purchaseUnsuccessful(purchases);
        getFragment().displayAnErrorIfNeeded(responseCode);
    }
}
 
Example #18
Source File: ActivityBilling.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
private void reportError(BillingResult result, String stage) {
    String message;
    if (result == null)
        message = stage;
    else {
        String debug = result.getDebugMessage();
        message = getBillingResponseText(result) + (debug == null ? "" : " " + debug) + " " + stage;

        // https://developer.android.com/reference/com/android/billingclient/api/BillingClient.BillingResponse#service_disconnected
        if (result.getResponseCode() == BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
            retry(60);
    }

    EntityLog.log(this, message);

    if (result.getResponseCode() != BillingClient.BillingResponseCode.USER_CANCELED)
        for (IBillingListener listener : listeners)
            listener.onError(message);
}
 
Example #19
Source File: InventoryQueryTest.java    From Cashier with Apache License 2.0 6 votes vote down vote up
@Test
public void returns_inventory() {
    InventoryListener listener = mock(InventoryListener.class);
    InventoryQuery.execute(
            TestHelper.mockThreading(),
            api,
            listener,
            TestData.allInAppSkus,
            TestData.allSubSkus
    );
    ArgumentCaptor<Inventory> argument = ArgumentCaptor.forClass(Inventory.class);

    // Check if API gets called correctly
    verify(api).getPurchases(BillingClient.SkuType.SUBS);
    verify(api).getPurchases(BillingClient.SkuType.INAPP);
    verify(api).getSkuDetails(eq(BillingClient.SkuType.SUBS), eq(TestData.allSubSkus), any(SkuDetailsResponseListener.class));
    verify(api).getSkuDetails(eq(BillingClient.SkuType.INAPP), eq(TestData.allInAppSkus), any(SkuDetailsResponseListener.class));

    // Check if result is delivered
    verify(listener).success(argument.capture());
    assertEquals(TestData.allProducts.size(), argument.getValue().products().size());
    assertEquals(1, argument.getValue().purchases().size());
    for (Product product : argument.getValue().products()) {
        assertTrue(TestData.allProducts.contains(product));
    }
}
 
Example #20
Source File: PreferencesBillingHelper.java    From CommonUtils with Apache License 2.0 6 votes vote down vote up
public void onStart(@NonNull Activity activity) {
    billingClient = BillingClient.newBuilder(activity).enablePendingPurchases().setListener(new InternalListener()).build();
    billingClient.startConnection(new BillingClientStateListener() {
        private boolean retried = false;

        @Override
        public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
            if (billingResult.getResponseCode() == BillingResponseCode.OK) {
                synchronized (billingReady) {
                    billingReady.notifyAll();
                }
            } else {
                handleBillingErrors(billingResult.getResponseCode());
            }
        }

        @Override
        public void onBillingServiceDisconnected() {
            if (!retried) {
                retried = true;
                billingClient.startConnection(this);
            } else {
                listener.showToast(Toaster.build().message(R.string.failedBillingConnection));
            }
        }
    });
}
 
Example #21
Source File: GooglePlayBillingVendorTest.java    From Cashier with Apache License 2.0 6 votes vote down vote up
@Test
public void get_product_details_failure() {
    GooglePlayBillingVendor vendor = successfullyInitializedVendor();
    ProductDetailsListener listener = mock(ProductDetailsListener.class);
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            List<String> skus = invocation.getArgument(1);
            SkuDetailsResponseListener responseListener = invocation.getArgument(2);

            assertEquals(1, skus.size());

            responseListener.onSkuDetailsResponse(BillingClient.BillingResponse.SERVICE_UNAVAILABLE, null);
            return null;
        }
    }).when(api).getSkuDetails(eq(BillingClient.SkuType.INAPP), ArgumentMatchers.<String>anyList(), any(SkuDetailsResponseListener.class));

    vendor.getProductDetails(context, TestData.productInappA.sku(), false, listener);

    ArgumentCaptor<Vendor.Error> argumentError = ArgumentCaptor.forClass(Vendor.Error.class);
    verify(listener).failure(argumentError.capture());
    assertEquals(VendorConstants.PRODUCT_DETAILS_UNAVAILABLE, argumentError.getValue().code);
}
 
Example #22
Source File: DefaultBillingManager.java    From SAI with GNU General Public License v3.0 6 votes vote down vote up
private void loadProducts() {
    List<String> skuList = new ArrayList<>();
    skuList.add(SKU_DONATION);

    SkuDetailsParams params = SkuDetailsParams.newBuilder()
            .setSkusList(skuList)
            .setType(BillingClient.SkuType.INAPP)
            .build();

    mBillingClient.querySkuDetailsAsync(params, (billingResult, skuDetailsList) -> {
        if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK) {
            Log.d(TAG, String.format("Unable to query sku details: %d - %s", billingResult.getResponseCode(), billingResult.getDebugMessage()));
            return;
        }

        ArrayList<BillingProduct> products = new ArrayList<>(skuDetailsList.size());
        for (SkuDetails skuDetails : skuDetailsList)
            products.add(new SkuDetailsBillingProduct(skuDetails));

        mAllProducts.setValue(products);
        invalidateProductsPurchaseStatus();
    });
}
 
Example #23
Source File: MainActivity.java    From FCM-for-Mojo with GNU General Public License v3.0 6 votes vote down vote up
private void showDonateGooglePlay() {
    mBillingClient = BillingClient.newBuilder(this).setListener(this).build();

    mBillingClient.startConnection(new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(@BillingResponse int billingResponseCode) {
            if (billingResponseCode == BillingResponse.OK) {
                // The billing client is ready. You can query purchases here.
                BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                        .setSku("donate_2")
                        .setType(SkuType.INAPP)
                        .build();
                mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
            }
        }

        @Override
        public void onBillingServiceDisconnected() {
            // Try to restart the connection on the next request to
            // Google Play by calling the startConnection() method.
        }
    });
}
 
Example #24
Source File: BillingManager.java    From play-billing-codelab with Apache License 2.0 6 votes vote down vote up
public void querySkuDetailsAsync(@BillingClient.SkuType final String itemType,
        final List<String> skuList, final SkuDetailsResponseListener listener) {
    // Specify a runnable to start when connection to Billing client is established
    Runnable executeOnConnectedService = new Runnable() {
        @Override
        public void run() {
            SkuDetailsParams skuDetailsParams = SkuDetailsParams.newBuilder()
                    .setSkusList(skuList).setType(itemType).build();
            mBillingClient.querySkuDetailsAsync(skuDetailsParams,
                    new SkuDetailsResponseListener() {
                        @Override
                        public void onSkuDetailsResponse(int responseCode,
                                List<SkuDetails> skuDetailsList) {
                            listener.onSkuDetailsResponse(responseCode, skuDetailsList);
                        }
                    });
        }
    };

    // If Billing client was disconnected, we retry 1 time and if success, execute the query
    startServiceConnectionIfNeeded(executeOnConnectedService);
}
 
Example #25
Source File: MainActivity.java    From scroball with MIT License 6 votes vote down vote up
@Override
protected void onResume() {
  super.onResume();
  billingClient = new BillingClient.Builder(this).setListener(this).build();
  billingClient.startConnection(
      new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(@BillingResponse int billingResponseCode) {
          if (billingResponseCode == BillingResponse.OK) {
            Purchase.PurchasesResult purchasesResult =
                billingClient.queryPurchases(BillingClient.SkuType.INAPP);
            onPurchasesUpdated(
                purchasesResult.getResponseCode(), purchasesResult.getPurchasesList());
          }
        }

        @Override
        public void onBillingServiceDisconnected() {}
      });
}
 
Example #26
Source File: BillingManager.java    From UpdogFarmer with GNU General Public License v3.0 6 votes vote down vote up
public BillingManager(Activity activity) {
    this.activity = activity;
    try {
        listener = (BillingUpdatesListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement BillingUpdatesListener.");
    }

    // Setup the billing client
    billingClient = BillingClient.newBuilder(activity).setListener(this).build();

    // Start the setup asynchronously.
    // The specified listener is called once setup completes.
    // New purchases are reported through the onPurchasesUpdated() callback
    // of the class specified using the setListener() method above.
    startServiceConnection(new Runnable() {
        @Override
        public void run() {
            // Query existing purchases
            queryPurchases();
            // Notify the listener that the billing client is ready.
            listener.onBillingClientSetupFinished();
        }
    });
}
 
Example #27
Source File: InventoryQueryTest.java    From Cashier with Apache License 2.0 6 votes vote down vote up
@Test
public void returns_error_when_inapp_purchases_call_fails() {
    when(api.getPurchases(BillingClient.SkuType.INAPP)).thenReturn(null);
    when(api.getPurchases(BillingClient.SkuType.SUBS)).thenReturn(new ArrayList<Purchase>());

    InventoryListener listener = mock(InventoryListener.class);
    InventoryQuery.execute(
            TestHelper.mockThreading(),
            api,
            listener,
            TestData.allInAppSkus,
            TestData.allSubSkus
    );

    verify(listener).failure(any(Vendor.Error.class));
}
 
Example #28
Source File: BillingManager.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
public BillingManager(AppCompatActivity activity) {
    //PPApplication.logE(TAG, "start client");
    mActivity = activity;
    mBillingClient = BillingClient.newBuilder(mActivity)
            .enablePendingPurchases()
            .setListener(this)
            .build();
    startServiceConnectionIfNeeded(null);
}
 
Example #29
Source File: MainActivity.java    From scroball with MIT License 5 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case R.id.settings_item:
      Intent intent = new Intent(getBaseContext(), SettingsActivity.class);
      startActivityForResult(intent, 1);
      return true;
    case R.id.remove_ads_item:
      BillingFlowParams.Builder builder =
          new BillingFlowParams.Builder()
              .setSku(REMOVE_ADS_SKU)
              .setType(BillingClient.SkuType.INAPP);
      int responseCode = billingClient.launchBillingFlow(this, builder.build());
      if (responseCode != BillingResponse.OK) {
        purchaseFailed();
      }
      return true;
    case R.id.privacy_policy_item:
      Intent browserIntent =
          new Intent(
              Intent.ACTION_VIEW,
              Uri.parse("https://scroball.peterjosling.com/privacy_policy.html"));
      startActivity(browserIntent);
      return true;
    case R.id.logout_item:
      logout();
      return true;
    default:
      return super.onOptionsItemSelected(item);
  }
}
 
Example #30
Source File: GooglePlayBillingVendorTest.java    From Cashier with Apache License 2.0 5 votes vote down vote up
@Test
public void get_product_details() {
    GooglePlayBillingVendor vendor = successfullyInitializedVendor();
    ProductDetailsListener listener = mock(ProductDetailsListener.class);
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            List<String> skus = invocation.getArgument(1);
            SkuDetailsResponseListener responseListener = invocation.getArgument(2);

            assertEquals(1, skus.size());

            responseListener.onSkuDetailsResponse(BillingClient.BillingResponse.OK,
                    Collections.singletonList( TestData.getSkuDetail(skus.get(0)) ));
            return null;
        }
    }).when(api).getSkuDetails(eq(BillingClient.SkuType.INAPP), ArgumentMatchers.<String>anyList(), any(SkuDetailsResponseListener.class));

    vendor.getProductDetails(context, TestData.productInappA.sku(), false, listener);

    ArgumentCaptor<List<String>> argumentSkus = ArgumentCaptor.forClass(List.class);
    verify(api).getSkuDetails(eq(BillingClient.SkuType.INAPP), argumentSkus.capture(), any(SkuDetailsResponseListener.class));
    assertEquals(1, argumentSkus.getValue().size());
    assertEquals(TestData.productInappA.sku(), argumentSkus.getValue().get(0));

    ArgumentCaptor<Product> argumentProduct = ArgumentCaptor.forClass(Product.class);
    verify(listener).success(argumentProduct.capture());
    assertEquals(TestData.productInappA, argumentProduct.getValue());
}