com.google.android.gms.wallet.WalletConstants Java Examples

The following examples show how to use com.google.android.gms.wallet.WalletConstants. 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: PromoAddressLookupFragment.java    From androidpay-quickstart with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        mPromoWasSelected = savedInstanceState.getBoolean(KEY_PROMO_CLICKED);
    }
    String accountName =
            ((BikestoreApplication) getActivity().getApplication()).getAccountName();
    AddressOptions options = new AddressOptions(WalletConstants.THEME_LIGHT);
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addApi(Address.API, options)
            .setAccountName(accountName)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}
 
Example #2
Source File: FlutterBraintreeDropIn.java    From FlutterBraintree with MIT License 6 votes vote down vote up
private static void readGooglePaymentParameters(DropInRequest dropInRequest, MethodCall call) {
  HashMap<String, Object> arg = call.argument("googlePaymentRequest");
  if (arg == null) {
    dropInRequest.disableGooglePayment();
    return;
  }
  GooglePaymentRequest googlePaymentRequest = new GooglePaymentRequest()
          .transactionInfo(TransactionInfo.newBuilder()
                  .setTotalPrice((String) arg.get("totalPrice"))
                  .setCurrencyCode((String) arg.get("currencyCode"))
                  .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
                  .build())
          .billingAddressRequired((Boolean) arg.get("billingAddressRequired"))
          .googleMerchantId((String) arg.get("merchantID"));
  dropInRequest.googlePaymentRequest(googlePaymentRequest);
}
 
Example #3
Source File: FullWalletConfirmationButtonFragment.java    From androidpay-quickstart with Apache License 2.0 6 votes vote down vote up
private void handleError(int errorCode) {
    switch (errorCode) {
        case WalletConstants.ERROR_CODE_SPENDING_LIMIT_EXCEEDED:
            // may be recoverable if the user tries to lower their charge
            // take the user back to the checkout page to try to handle
        case WalletConstants.ERROR_CODE_INVALID_PARAMETERS:
        case WalletConstants.ERROR_CODE_AUTHENTICATION_FAILURE:
        case WalletConstants.ERROR_CODE_BUYER_ACCOUNT_ERROR:
        case WalletConstants.ERROR_CODE_MERCHANT_ACCOUNT_ERROR:
        case WalletConstants.ERROR_CODE_SERVICE_UNAVAILABLE:
        case WalletConstants.ERROR_CODE_UNSUPPORTED_API_VERSION:
        case WalletConstants.ERROR_CODE_UNKNOWN:
        default:
            // unrecoverable error
            // take the user back to the checkout page to handle these errors
            handleUnrecoverableGoogleWalletError(errorCode);
    }
}
 
Example #4
Source File: FullWalletConfirmationButtonFragment.java    From androidpay-quickstart with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mActivityLaunchIntent = getActivity().getIntent();
    mItemId = mActivityLaunchIntent.getIntExtra(Constants.EXTRA_ITEM_ID, 0);
    mMaskedWallet = mActivityLaunchIntent.getParcelableExtra(Constants.EXTRA_MASKED_WALLET);

    String accountName = getApplication().getAccountName();

    // Set up an API client
    FragmentActivity fragmentActivity = getActivity();

    // [START build_google_api_client]
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .enableAutoManage(fragmentActivity, this /* onConnectionFailedListener */)
            .setAccountName(accountName) // optional
            .addApi(Wallet.API, new Wallet.WalletOptions.Builder()
                    .setEnvironment(Constants.WALLET_ENVIRONMENT)
                    .setTheme(WalletConstants.THEME_LIGHT)
                    .build())
            .build();
    // [END build_google_api_client]
}
 
Example #5
Source File: BikestoreFragmentActivity.java    From androidpay-quickstart with Apache License 2.0 6 votes vote down vote up
protected void handleError(int errorCode) {
    switch (errorCode) {
        case WalletConstants.ERROR_CODE_SPENDING_LIMIT_EXCEEDED:
            Toast.makeText(this, getString(R.string.spending_limit_exceeded, errorCode),
                    Toast.LENGTH_LONG).show();
            break;
        case WalletConstants.ERROR_CODE_INVALID_PARAMETERS:
        case WalletConstants.ERROR_CODE_AUTHENTICATION_FAILURE:
        case WalletConstants.ERROR_CODE_BUYER_ACCOUNT_ERROR:
        case WalletConstants.ERROR_CODE_MERCHANT_ACCOUNT_ERROR:
        case WalletConstants.ERROR_CODE_SERVICE_UNAVAILABLE:
        case WalletConstants.ERROR_CODE_UNSUPPORTED_API_VERSION:
        case WalletConstants.ERROR_CODE_UNKNOWN:
        default:
            // unrecoverable error
            String errorMessage = getString(R.string.google_wallet_unavailable) + "\n" +
                getString(R.string.error_code, errorCode);
            Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
            break;
    }
}
 
Example #6
Source File: GooglePaymentTest.java    From braintree_android with MIT License 6 votes vote down vote up
@Test
public void requestPayment_sendsAnalyticsEvent() {
    BraintreeFragment fragment = getSetupFragment();
    GooglePaymentRequest googlePaymentRequest = new GooglePaymentRequest()
            .transactionInfo(TransactionInfo.newBuilder()
                    .setTotalPrice("1.00")
                    .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
                    .setCurrencyCode("USD")
                    .build());

    GooglePayment.requestPayment(fragment, googlePaymentRequest);

    InOrder order = inOrder(fragment);
    order.verify(fragment).sendAnalyticsEvent("google-payment.selected");
    order.verify(fragment).sendAnalyticsEvent("google-payment.started");
}
 
Example #7
Source File: MainActivity.java    From braintree_android with MIT License 6 votes vote down vote up
private DropInRequest getDropInRequest() {
    GooglePaymentRequest googlePaymentRequest = new GooglePaymentRequest()
            .transactionInfo(TransactionInfo.newBuilder()
                    .setCurrencyCode(Settings.getGooglePaymentCurrency(this))
                    .setTotalPrice("1.00")
                    .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
                    .build())
            .allowPrepaidCards(Settings.areGooglePaymentPrepaidCardsAllowed(this))
            .billingAddressFormat(WalletConstants.BILLING_ADDRESS_FORMAT_FULL)
            .billingAddressRequired(Settings.isGooglePaymentBillingAddressRequired(this))
            .emailRequired(Settings.isGooglePaymentEmailRequired(this))
            .phoneNumberRequired(Settings.isGooglePaymentPhoneNumberRequired(this))
            .shippingAddressRequired(Settings.isGooglePaymentShippingAddressRequired(this))
            .shippingAddressRequirements(ShippingAddressRequirements.newBuilder()
                    .addAllowedCountryCodes(Settings.getGooglePaymentAllowedCountriesForShipping(this))
                    .build())
            .googleMerchantId(Settings.getGooglePaymentMerchantId(this));

    return new DropInRequest()
            .amount("1.00")
            .clientToken(mAuthorization)
            .collectDeviceData(Settings.shouldCollectDeviceData(this))
            .requestThreeDSecureVerification(Settings.isThreeDSecureEnabled(this))
            .googlePaymentRequest(googlePaymentRequest);
}
 
Example #8
Source File: GooglePaymentActivity.java    From braintree_android with MIT License 6 votes vote down vote up
public void launchGooglePayment(View v) {
    setProgressBarIndeterminateVisibility(true);

    GooglePaymentRequest googlePaymentRequest = new GooglePaymentRequest()
            .transactionInfo(TransactionInfo.newBuilder()
                    .setCurrencyCode(Settings.getGooglePaymentCurrency(this))
                    .setTotalPrice("1.00")
                    .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
                    .build())
            .allowPrepaidCards(Settings.areGooglePaymentPrepaidCardsAllowed(this))
            .billingAddressFormat(WalletConstants.BILLING_ADDRESS_FORMAT_FULL)
            .billingAddressRequired(Settings.isGooglePaymentBillingAddressRequired(this))
            .emailRequired(Settings.isGooglePaymentEmailRequired(this))
            .phoneNumberRequired(Settings.isGooglePaymentPhoneNumberRequired(this))
            .shippingAddressRequired(Settings.isGooglePaymentShippingAddressRequired(this))
            .shippingAddressRequirements(ShippingAddressRequirements.newBuilder()
                    .addAllowedCountryCodes(Settings.getGooglePaymentAllowedCountriesForShipping(this))
                    .build())
            .googleMerchantId(Settings.getGooglePaymentMerchantId(this));

    GooglePayment.requestPayment(mBraintreeFragment, googlePaymentRequest);
}
 
Example #9
Source File: GooglePaymentTest.java    From braintree_android with MIT License 5 votes vote down vote up
@Test
public void requestPayment_startsActivity() {
    BraintreeFragment fragment = getSetupFragment();
    GooglePaymentRequest googlePaymentRequest = new GooglePaymentRequest()
            .transactionInfo(TransactionInfo.newBuilder()
                    .setTotalPrice("1.00")
                    .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
                    .setCurrencyCode("USD")
                    .build());

    GooglePayment.requestPayment(fragment, googlePaymentRequest);

    verify(fragment).startActivityForResult(any(Intent.class), eq(BraintreeRequestCodes.GOOGLE_PAYMENT));
}
 
Example #10
Source File: BraintreeFragment.java    From braintree_android with MIT License 5 votes vote down vote up
protected GoogleApiClient getGoogleApiClient() {
    if (getActivity() == null) {
        postCallback(new GoogleApiClientException(ErrorType.NotAttachedToActivity, 1));
        return null;
    }

    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addApi(Wallet.API, new Wallet.WalletOptions.Builder()
                        .setEnvironment(GooglePayment.getEnvironment(getConfiguration().getGooglePayment()))
                        .setTheme(WalletConstants.THEME_LIGHT)
                        .build())
                .build();
    }

    if (!mGoogleApiClient.isConnected() && !mGoogleApiClient.isConnecting()) {
        mGoogleApiClient.registerConnectionCallbacks(new ConnectionCallbacks() {
            @Override
            public void onConnected(Bundle bundle) {}

            @Override
            public void onConnectionSuspended(int i) {
                postCallback(new GoogleApiClientException(ErrorType.ConnectionSuspended, i));
            }
        });

        mGoogleApiClient.registerConnectionFailedListener(new OnConnectionFailedListener() {
            @Override
            public void onConnectionFailed(ConnectionResult connectionResult) {
                postCallback(new GoogleApiClientException(ErrorType.ConnectionFailed, connectionResult.getErrorCode()));
            }
        });

        mGoogleApiClient.connect();
    }

    return mGoogleApiClient;
}
 
Example #11
Source File: FullWalletConfirmationButtonFragment.java    From androidpay-quickstart with Apache License 2.0 5 votes vote down vote up
/**
 * For unrecoverable Google Wallet errors, send the user back to the checkout page to handle the
 * problem.
 *
 * @param errorCode
 */
protected void handleUnrecoverableGoogleWalletError(int errorCode) {
    Intent intent = new Intent(getActivity(), CheckoutActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra(WalletConstants.EXTRA_ERROR_CODE, errorCode);
    intent.putExtra(Constants.EXTRA_ITEM_ID, mItemId);
    startActivity(intent);
}
 
Example #12
Source File: CheckoutActivity.java    From androidpay-quickstart with Apache License 2.0 5 votes vote down vote up
/**
 * If the confirmation page encounters an error it can't handle, it will send the customer back
 * to this page.  The intent should include the error code as an {@code int} in the field
 * {@link WalletConstants#EXTRA_ERROR_CODE}.
 */
@Override
protected void onNewIntent(Intent intent) {
    if (intent.hasExtra(WalletConstants.EXTRA_ERROR_CODE)) {
        int errorCode = intent.getIntExtra(WalletConstants.EXTRA_ERROR_CODE, 0);
        handleError(errorCode);
    }
}
 
Example #13
Source File: CheckoutActivity.java    From androidpay-quickstart with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // retrieve the error code, if available
    int errorCode = -1;
    if (data != null) {
        errorCode = data.getIntExtra(WalletConstants.EXTRA_ERROR_CODE, -1);
    }
    switch (requestCode) {
        case REQUEST_CODE_MASKED_WALLET:
            switch (resultCode) {
                case Activity.RESULT_OK:
                    if (data != null) {
                        MaskedWallet maskedWallet =
                                data.getParcelableExtra(WalletConstants.EXTRA_MASKED_WALLET);
                        launchConfirmationPage(maskedWallet);
                    }
                    break;
                case WalletConstants.RESULT_ERROR:
                    handleError(errorCode);
                    break;
                case Activity.RESULT_CANCELED:
                    break;
                default:
                    handleError(errorCode);
                    break;
            }
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
    }
}
 
Example #14
Source File: ConfirmationActivity.java    From androidpay-quickstart with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    int errorCode = 0;
    if (data != null) {
        errorCode = data.getIntExtra(WalletConstants.EXTRA_ERROR_CODE, 0);
    }
    switch (requestCode) {
        case REQUEST_CODE_CHANGE_MASKED_WALLET:
            switch (resultCode) {
                case Activity.RESULT_OK:
                    if (data != null && data.hasExtra(WalletConstants.EXTRA_MASKED_WALLET)) {
                        mMaskedWallet = data.getParcelableExtra(WalletConstants.EXTRA_MASKED_WALLET);
                        ((FullWalletConfirmationButtonFragment) getResultTargetFragment())
                                .updateMaskedWallet(mMaskedWallet);
                    }
                    break;
                case WalletConstants.RESULT_ERROR:
                    handleError(errorCode);
                    break;
                case Activity.RESULT_CANCELED:
                    break;
                default:
                    handleError(errorCode);
                    break;
            }
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
    }
}
 
Example #15
Source File: ConfirmationActivity.java    From androidpay-quickstart with Apache License 2.0 5 votes vote down vote up
private void createAndAddWalletFragment() {
    WalletFragmentStyle walletFragmentStyle = new WalletFragmentStyle()
            .setMaskedWalletDetailsTextAppearance(
                    R.style.BikestoreWalletFragmentDetailsTextAppearance)
            .setMaskedWalletDetailsHeaderTextAppearance(
                    R.style.BikestoreWalletFragmentDetailsHeaderTextAppearance)
            .setMaskedWalletDetailsBackgroundColor(
                    getResources().getColor(R.color.bikestore_white))
            .setMaskedWalletDetailsButtonBackgroundResource(
                    R.drawable.bikestore_btn_default_holo_light);

    // [START wallet_fragment_options]
    WalletFragmentOptions walletFragmentOptions = WalletFragmentOptions.newBuilder()
            .setEnvironment(Constants.WALLET_ENVIRONMENT)
            .setFragmentStyle(walletFragmentStyle)
            .setTheme(WalletConstants.THEME_LIGHT)
            .setMode(WalletFragmentMode.SELECTION_DETAILS)
            .build();
    mWalletFragment = SupportWalletFragment.newInstance(walletFragmentOptions);
    // [END wallet_fragment_options]

    // Now initialize the Wallet Fragment
    String accountName = ((BikestoreApplication) getApplication()).getAccountName();
    WalletFragmentInitParams.Builder startParamsBuilder = WalletFragmentInitParams.newBuilder()
            .setMaskedWallet(mMaskedWallet)
            .setMaskedWalletRequestCode(REQUEST_CODE_CHANGE_MASKED_WALLET)
            .setAccountName(accountName);
    mWalletFragment.initialize(startParamsBuilder.build());

    // add Wallet fragment to the UI
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.dynamic_wallet_masked_wallet_fragment, mWalletFragment)
            .commit();
}
 
Example #16
Source File: MainActivity.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(Wallet.API, new Wallet.WalletOptions.Builder()
            .setEnvironment(WalletConstants.ENVIRONMENT_PRODUCTION)
            .setTheme(WalletConstants.THEME_HOLO_LIGHT)
            .build())
        .build();

    setContentView(R.layout.activity_main);
}
 
Example #17
Source File: MainActivity.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode,resultCode,data);

  switch (requestCode) {
    case MASKED_WALLET_REQUEST_CODE:
      switch (resultCode) {
        case Activity.RESULT_OK:
          mMaskedWallet =
              data.getParcelableExtra(WalletConstants.EXTRA_MASKED_WALLET);
          break;
        case Activity.RESULT_CANCELED:
          break;
        default:
          Toast.makeText(this, "An Error Occurred", Toast.LENGTH_LONG).show();
          break;
      }
      break;
    case FULL_WALLET_REQUEST_CODE:
      switch (resultCode) {
        case Activity.RESULT_OK:
          mFullWallet =
              data.getParcelableExtra(WalletConstants.EXTRA_FULL_WALLET);
          Toast.makeText(this, mFullWallet.getProxyCard().getPan().toString(), Toast.LENGTH_LONG).show();

          Wallet.Payments.notifyTransactionStatus(mGoogleApiClient,
              generateNotifyTransactionStatusRequest(mFullWallet.getGoogleTransactionId(),
                  NotifyTransactionStatusRequest.Status.SUCCESS));

          break;
        default:
          Toast.makeText(this, "An Error Occurred", Toast.LENGTH_LONG).show();
          break;
      }
      break;
    case WalletConstants.RESULT_ERROR:
      Toast.makeText(this, "An Error Occurred", Toast.LENGTH_LONG).show();
      break;
  }
}
 
Example #18
Source File: FullWalletConfirmationButtonFragment.java    From androidpay-quickstart with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    mProgressDialog.hide();

    // retrieve the error code, if available
    int errorCode = -1;
    if (data != null) {
        errorCode = data.getIntExtra(WalletConstants.EXTRA_ERROR_CODE, -1);
    }

    switch (requestCode) {
        case REQUEST_CODE_RESOLVE_LOAD_FULL_WALLET:
            switch (resultCode) {
                case Activity.RESULT_OK:
                    if (data != null && data.hasExtra(WalletConstants.EXTRA_FULL_WALLET)) {
                        FullWallet fullWallet = data.getParcelableExtra(WalletConstants.EXTRA_FULL_WALLET);
                        // the full wallet can now be used to process the customer's payment
                        // send the wallet info up to server to process, and to get the result
                        // for sending a transaction status
                        fetchTransactionStatus(fullWallet);
                    } else if (data != null && data.hasExtra(WalletConstants.EXTRA_MASKED_WALLET)) {
                        // re-launch the activity with new masked wallet information
                        mMaskedWallet =  data.getParcelableExtra(WalletConstants.EXTRA_MASKED_WALLET);
                        mActivityLaunchIntent.putExtra(Constants.EXTRA_MASKED_WALLET,
                                mMaskedWallet);
                        startActivity(mActivityLaunchIntent);
                    }
                    break;
                case Activity.RESULT_CANCELED:
                    // nothing to do here
                    break;
                default:
                    handleError(errorCode);
                    break;
            }
            break;
    }
}
 
Example #19
Source File: MainActivity.java    From braintree-android-drop-in with MIT License 5 votes vote down vote up
private GooglePaymentRequest getGooglePaymentRequest() {
    return new GooglePaymentRequest()
            .transactionInfo(TransactionInfo.newBuilder()
                    .setTotalPrice("1.00")
                    .setCurrencyCode("USD")
                    .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
                    .build())
            .emailRequired(true);
}
 
Example #20
Source File: CollectCardInfoActivity.java    From gateway-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = DataBindingUtil.setContentView(this, R.layout.activity_collect_card_info);

    // get bundle extras and set txn amount and currency for google pay
    Intent i = getIntent();
    googlePayTxnAmount = i.getStringExtra(EXTRA_GOOGLE_PAY_TXN_AMOUNT);
    googlePayTxnCurrency = i.getStringExtra(EXTRA_GOOGLE_PAY_TXN_CURRENCY);

    // init manual text field listeners
    binding.nameOnCard.requestFocus();
    binding.nameOnCard.addTextChangedListener(textChangeListener);
    binding.cardnumber.addTextChangedListener(textChangeListener);
    binding.expiryMonth.addTextChangedListener(textChangeListener);
    binding.expiryYear.addTextChangedListener(textChangeListener);
    binding.cvv.addTextChangedListener(textChangeListener);

    binding.submitButton.setEnabled(false);
    binding.submitButton.setOnClickListener(v -> continueButtonClicked());


    // init Google Pay client
    paymentsClient = Wallet.getPaymentsClient(this, new Wallet.WalletOptions.Builder()
            .setEnvironment(WalletConstants.ENVIRONMENT_TEST)
            .build());

    // init google pay button
    binding.googlePayButton.setOnClickListener(v -> googlePayButtonClicked());

    // check if Google Pay is available
    isReadyToPay();
}
 
Example #21
Source File: GPay.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Override
public Map<String, Object> getConstants() {
    final Map<String, Object> constants = new HashMap<>();
    constants.put(ENVIRONMENT_PRODUCTION_KEY, WalletConstants.ENVIRONMENT_PRODUCTION);
    constants.put(ENVIRONMENT_TEST_KEY, WalletConstants.ENVIRONMENT_TEST);
    return constants;
}
 
Example #22
Source File: GPay.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Override
public Map<String, Object> getConstants() {
    final Map<String, Object> constants = new HashMap<>();
    constants.put(ENVIRONMENT_PRODUCTION_KEY, WalletConstants.ENVIRONMENT_PRODUCTION);
    constants.put(ENVIRONMENT_TEST_KEY, WalletConstants.ENVIRONMENT_TEST);
    return constants;
}
 
Example #23
Source File: CheckoutActivity.java    From in-app-payments-android-quickstart with Apache License 2.0 5 votes vote down vote up
private void startGooglePayActivity() {
  TransactionInfo transactionInfo = TransactionInfo.newBuilder()
      .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
      .setTotalPrice("1.00")
      .setCurrencyCode("USD")
      .build();

  PaymentDataRequest paymentDataRequest =
      GooglePay.createPaymentDataRequest(ConfigHelper.GOOGLE_PAY_MERCHANT_ID,
          transactionInfo);

  Task<PaymentData> googlePayActivityTask = paymentsClient.loadPaymentData(paymentDataRequest);

  AutoResolveHelper.resolveTask(googlePayActivityTask, this, LOAD_PAYMENT_DATA_REQUEST_CODE);
}
 
Example #24
Source File: CheckoutActivity.java    From in-app-payments-android-quickstart with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_cookie);

  googlePayChargeClient = (GooglePayChargeClient) getLastCustomNonConfigurationInstance();
  if (googlePayChargeClient == null) {
    googlePayChargeClient = ExampleApplication.createGooglePayChargeClient(this);
  }
  googlePayChargeClient.onActivityCreated(this);

  paymentsClient = Wallet.getPaymentsClient(this,
      new Wallet.WalletOptions.Builder()
          .setEnvironment(WalletConstants.ENVIRONMENT_TEST)
          .build());

  orderSheet = new OrderSheet();

  enableGooglePayButton(orderSheet);
  orderSheet.setOnPayWithCardClickListener(this::startCardEntryActivity);
  orderSheet.setOnPayWithGoogleClickListener(this::startGooglePayActivity);

  View buyButton = findViewById(R.id.buy_button);
  buyButton.setOnClickListener(v -> {
    if (InAppPaymentsSdk.INSTANCE.getSquareApplicationId().equals("REPLACE_ME")) {
      showMissingSquareApplicationIdDialog();
    } else {
      showOrderSheet();
    }
  });
}
 
Example #25
Source File: DropInRequestUnitTest.java    From braintree-android-drop-in with MIT License 4 votes vote down vote up
@Test
public void isParcelable() {
    Cart cart = Cart.newBuilder()
            .setTotalPrice("5.00")
            .build();
    GooglePaymentRequest googlePaymentRequest = new GooglePaymentRequest()
            .transactionInfo(TransactionInfo.newBuilder()
                    .setTotalPrice("10")
                    .setCurrencyCode("USD")
                    .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
                    .build())
            .emailRequired(true);

    PayPalRequest paypalRequest = new PayPalRequest("10")
            .currencyCode("USD");

    ThreeDSecureRequest threeDSecureRequest = new ThreeDSecureRequest()
            .nonce("abc-123")
            .versionRequested(ThreeDSecureRequest.VERSION_2)
            .amount("10.00")
            .email("[email protected]")
            .mobilePhoneNumber("3125551234")
            .billingAddress(new ThreeDSecurePostalAddress()
                    .givenName("Given")
                    .surname("Surname")
                    .streetAddress("555 Smith St.")
                    .extendedAddress("#5")
                    .locality("Chicago")
                    .region("IL")
                    .postalCode("54321")
                    .countryCodeAlpha2("US")
                    .phoneNumber("3125557890")
            )
            .additionalInformation(new ThreeDSecureAdditionalInformation()
                    .shippingMethodIndicator("GEN")
            );

    DropInRequest dropInRequest = new DropInRequest()
            .tokenizationKey(TOKENIZATION_KEY)
            .collectDeviceData(true)
            .amount("1.00")
            .googlePaymentRequest(googlePaymentRequest)
            .disableGooglePayment()
            .paypalRequest(paypalRequest)
            .disablePayPal()
            .disableVenmo()
            .disableCard()
            .requestThreeDSecureVerification(true)
            .threeDSecureRequest(threeDSecureRequest)
            .maskCardNumber(true)
            .maskSecurityCode(true)
            .vaultManager(true)
            .vaultCard(true)
            .allowVaultCardOverride(true)
            .cardholderNameStatus(CardForm.FIELD_OPTIONAL);

    Parcel parcel = Parcel.obtain();
    dropInRequest.writeToParcel(parcel, 0);
    parcel.setDataPosition(0);
    DropInRequest parceledDropInRequest = DropInRequest.CREATOR.createFromParcel(parcel);

    assertEquals(TOKENIZATION_KEY, parceledDropInRequest.getAuthorization());
    assertTrue(parceledDropInRequest.shouldCollectDeviceData());
    assertEquals("1.00", parceledDropInRequest.getAmount());
    assertEquals("10", dropInRequest.getGooglePaymentRequest().getTransactionInfo().getTotalPrice());
    assertEquals("USD", dropInRequest.getGooglePaymentRequest().getTransactionInfo().getCurrencyCode());
    assertEquals(WalletConstants.TOTAL_PRICE_STATUS_FINAL, dropInRequest.getGooglePaymentRequest().getTransactionInfo().getTotalPriceStatus());
    assertTrue(dropInRequest.getGooglePaymentRequest().isEmailRequired());
    assertEquals("10", dropInRequest.getPayPalRequest().getAmount());
    assertEquals("USD", dropInRequest.getPayPalRequest().getCurrencyCode());
    assertFalse(dropInRequest.isGooglePaymentEnabled());
    assertFalse(parceledDropInRequest.isPayPalEnabled());
    assertFalse(parceledDropInRequest.isVenmoEnabled());
    assertFalse(parceledDropInRequest.isCardEnabled());
    assertTrue(parceledDropInRequest.shouldRequestThreeDSecureVerification());
    assertEquals("abc-123", dropInRequest.getThreeDSecureRequest().getNonce());
    assertEquals("2", dropInRequest.getThreeDSecureRequest().getVersionRequested());
    assertEquals("10.00", dropInRequest.getThreeDSecureRequest().getAmount());
    assertEquals("[email protected]", dropInRequest.getThreeDSecureRequest().getEmail());
    assertEquals("3125551234", dropInRequest.getThreeDSecureRequest().getMobilePhoneNumber());
    assertEquals("Given", dropInRequest.getThreeDSecureRequest().getBillingAddress().getGivenName());
    assertEquals("Surname", dropInRequest.getThreeDSecureRequest().getBillingAddress().getSurname());
    assertEquals("555 Smith St.", dropInRequest.getThreeDSecureRequest().getBillingAddress().getStreetAddress());
    assertEquals("#5", dropInRequest.getThreeDSecureRequest().getBillingAddress().getExtendedAddress());
    assertEquals("Chicago", dropInRequest.getThreeDSecureRequest().getBillingAddress().getLocality());
    assertEquals("IL", dropInRequest.getThreeDSecureRequest().getBillingAddress().getRegion());
    assertEquals("54321", dropInRequest.getThreeDSecureRequest().getBillingAddress().getPostalCode());
    assertEquals("US", dropInRequest.getThreeDSecureRequest().getBillingAddress().getCountryCodeAlpha2());
    assertEquals("3125557890", dropInRequest.getThreeDSecureRequest().getBillingAddress().getPhoneNumber());
    assertEquals("GEN", dropInRequest.getThreeDSecureRequest().getAdditionalInformation().getShippingMethodIndicator());
    assertTrue(parceledDropInRequest.shouldMaskCardNumber());
    assertTrue(parceledDropInRequest.shouldMaskSecurityCode());
    assertTrue(parceledDropInRequest.isVaultManagerEnabled());
    assertTrue(parceledDropInRequest.getDefaultVaultSetting());
    assertTrue(parceledDropInRequest.isSaveCardCheckBoxShown());
    assertEquals(CardForm.FIELD_OPTIONAL, parceledDropInRequest.getCardholderNameStatus());
}
 
Example #26
Source File: DropInRequestUnitTest.java    From braintree-android-drop-in with MIT License 4 votes vote down vote up
@Test
public void includesAllOptions() {
    GooglePaymentRequest googlePaymentRequest = new GooglePaymentRequest()
            .transactionInfo(TransactionInfo.newBuilder()
                    .setTotalPrice("10")
                    .setCurrencyCode("USD")
                    .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
                    .build())
            .emailRequired(true);

    PayPalRequest paypalRequest = new PayPalRequest("10")
            .currencyCode("USD");

    ThreeDSecureRequest threeDSecureRequest = new ThreeDSecureRequest()
            .nonce("abc-123")
            .versionRequested(ThreeDSecureRequest.VERSION_2)
            .amount("10.00")
            .email("[email protected]")
            .mobilePhoneNumber("3125551234")
            .billingAddress(new ThreeDSecurePostalAddress()
                    .givenName("Given")
                    .surname("Surname")
                    .streetAddress("555 Smith St.")
                    .extendedAddress("#5")
                    .locality("Chicago")
                    .region("IL")
                    .postalCode("54321")
                    .countryCodeAlpha2("US")
                    .phoneNumber("3125557890")
            )
            .additionalInformation(new ThreeDSecureAdditionalInformation()
                    .shippingMethodIndicator("GEN")
            );


    Intent intent = new DropInRequest()
            .tokenizationKey(TOKENIZATION_KEY)
            .collectDeviceData(true)
            .amount("1.00")
            .googlePaymentRequest(googlePaymentRequest)
            .disableGooglePayment()
            .paypalRequest(paypalRequest)
            .disablePayPal()
            .disableVenmo()
            .disableCard()
            .requestThreeDSecureVerification(true)
            .threeDSecureRequest(threeDSecureRequest)
            .maskCardNumber(true)
            .maskSecurityCode(true)
            .vaultManager(true)
            .allowVaultCardOverride(true)
            .vaultCard(true)
            .cardholderNameStatus(CardForm.FIELD_OPTIONAL)
            .getIntent(RuntimeEnvironment.application);

    DropInRequest dropInRequest = intent.getParcelableExtra(DropInRequest.EXTRA_CHECKOUT_REQUEST);

    assertEquals(DropInActivity.class.getName(), intent.getComponent().getClassName());
    assertEquals(TOKENIZATION_KEY, dropInRequest.getAuthorization());
    assertTrue(dropInRequest.shouldCollectDeviceData());
    assertEquals("1.00", dropInRequest.getAmount());
    assertEquals("10", dropInRequest.getGooglePaymentRequest().getTransactionInfo().getTotalPrice());
    assertEquals("USD", dropInRequest.getGooglePaymentRequest().getTransactionInfo().getCurrencyCode());
    assertEquals(WalletConstants.TOTAL_PRICE_STATUS_FINAL, dropInRequest.getGooglePaymentRequest().getTransactionInfo().getTotalPriceStatus());
    assertTrue(dropInRequest.getGooglePaymentRequest().isEmailRequired());
    assertFalse(dropInRequest.isGooglePaymentEnabled());
    assertEquals("10", dropInRequest.getPayPalRequest().getAmount());
    assertEquals("USD", dropInRequest.getPayPalRequest().getCurrencyCode());
    assertFalse(dropInRequest.isPayPalEnabled());
    assertFalse(dropInRequest.isVenmoEnabled());
    assertFalse(dropInRequest.isCardEnabled());
    assertTrue(dropInRequest.shouldRequestThreeDSecureVerification());
    assertEquals("abc-123", dropInRequest.getThreeDSecureRequest().getNonce());
    assertEquals("2", dropInRequest.getThreeDSecureRequest().getVersionRequested());
    assertEquals("10.00", dropInRequest.getThreeDSecureRequest().getAmount());
    assertEquals("[email protected]", dropInRequest.getThreeDSecureRequest().getEmail());
    assertEquals("3125551234", dropInRequest.getThreeDSecureRequest().getMobilePhoneNumber());
    assertEquals("Given", dropInRequest.getThreeDSecureRequest().getBillingAddress().getGivenName());
    assertEquals("Surname", dropInRequest.getThreeDSecureRequest().getBillingAddress().getSurname());
    assertEquals("555 Smith St.", dropInRequest.getThreeDSecureRequest().getBillingAddress().getStreetAddress());
    assertEquals("#5", dropInRequest.getThreeDSecureRequest().getBillingAddress().getExtendedAddress());
    assertEquals("Chicago", dropInRequest.getThreeDSecureRequest().getBillingAddress().getLocality());
    assertEquals("IL", dropInRequest.getThreeDSecureRequest().getBillingAddress().getRegion());
    assertEquals("54321", dropInRequest.getThreeDSecureRequest().getBillingAddress().getPostalCode());
    assertEquals("US", dropInRequest.getThreeDSecureRequest().getBillingAddress().getCountryCodeAlpha2());
    assertEquals("3125557890", dropInRequest.getThreeDSecureRequest().getBillingAddress().getPhoneNumber());
    assertEquals("GEN", dropInRequest.getThreeDSecureRequest().getAdditionalInformation().getShippingMethodIndicator());
    assertTrue(dropInRequest.shouldMaskCardNumber());
    assertTrue(dropInRequest.shouldMaskSecurityCode());
    assertTrue(dropInRequest.isVaultManagerEnabled());
    assertTrue(dropInRequest.getDefaultVaultSetting());
    assertTrue(dropInRequest.isSaveCardCheckBoxShown());
    assertEquals(CardForm.FIELD_OPTIONAL, dropInRequest.getCardholderNameStatus());
}
 
Example #27
Source File: CheckoutActivity.java    From androidpay-quickstart with Apache License 2.0 4 votes vote down vote up
private void createAndAddWalletFragment() {
    // [START fragment_style_and_options]
    WalletFragmentStyle walletFragmentStyle = new WalletFragmentStyle()
            .setBuyButtonText(WalletFragmentStyle.BuyButtonText.BUY_WITH)
            .setBuyButtonAppearance(WalletFragmentStyle.BuyButtonAppearance.ANDROID_PAY_DARK)
            .setBuyButtonWidth(WalletFragmentStyle.Dimension.MATCH_PARENT);

    WalletFragmentOptions walletFragmentOptions = WalletFragmentOptions.newBuilder()
            .setEnvironment(Constants.WALLET_ENVIRONMENT)
            .setFragmentStyle(walletFragmentStyle)
            .setTheme(WalletConstants.THEME_LIGHT)
            .setMode(WalletFragmentMode.BUY_BUTTON)
            .build();
    mWalletFragment = SupportWalletFragment.newInstance(walletFragmentOptions);
    // [END fragment_style_and_options]

    // Now initialize the Wallet Fragment
    String accountName = ((BikestoreApplication) getApplication()).getAccountName();
    MaskedWalletRequest maskedWalletRequest;
    if (mUseStripe) {
        // Stripe integration
        maskedWalletRequest = WalletUtil.createStripeMaskedWalletRequest(
                Constants.ITEMS_FOR_SALE[mItemId],
                getString(R.string.stripe_publishable_key),
                getString(R.string.stripe_version));
    } else {
        // Direct integration
        maskedWalletRequest = WalletUtil.createMaskedWalletRequest(
                Constants.ITEMS_FOR_SALE[mItemId],
                getString(R.string.public_key));
    }

    // [START params_builder]
    WalletFragmentInitParams.Builder startParamsBuilder = WalletFragmentInitParams.newBuilder()
            .setMaskedWalletRequest(maskedWalletRequest)
            .setMaskedWalletRequestCode(REQUEST_CODE_MASKED_WALLET)
            .setAccountName(accountName);
    mWalletFragment.initialize(startParamsBuilder.build());

    // add Wallet fragment to the UI
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.dynamic_wallet_button_fragment, mWalletFragment)
            .commit();
    // [END params_builder]
}
 
Example #28
Source File: PaymentFormActivity.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onActivityResultFragment(int requestCode, int resultCode, Intent data) {
    if (requestCode == LOAD_MASKED_WALLET_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {
            showEditDoneProgress(true, true);
            setDonePressed(true);

            MaskedWallet maskedWallet = data.getParcelableExtra(WalletConstants.EXTRA_MASKED_WALLET);

            Cart.Builder cardBuilder = Cart.newBuilder()
                    .setCurrencyCode(paymentForm.invoice.currency)
                    .setTotalPrice(totalPriceDecimal);

            ArrayList<TLRPC.TL_labeledPrice> arrayList = new ArrayList<>(paymentForm.invoice.prices);
            if (shippingOption != null) {
                arrayList.addAll(shippingOption.prices);
            }
            for (int a = 0; a < arrayList.size(); a++) {
                TLRPC.TL_labeledPrice price = arrayList.get(a);
                String amount = LocaleController.getInstance().formatCurrencyDecimalString(price.amount, paymentForm.invoice.currency, false);
                cardBuilder.addLineItem(LineItem.newBuilder()
                        .setCurrencyCode(paymentForm.invoice.currency)
                        .setQuantity("1")
                        .setDescription(price.label)
                        .setTotalPrice(amount)
                        .setUnitPrice(amount).build());
            }
            FullWalletRequest fullWalletRequest = FullWalletRequest.newBuilder()
                    .setCart(cardBuilder.build())
                    .setGoogleTransactionId(maskedWallet.getGoogleTransactionId())
                    .build();
            Wallet.Payments.loadFullWallet(googleApiClient, fullWalletRequest, LOAD_FULL_WALLET_REQUEST_CODE);
        } else {
            showEditDoneProgress(true, false);
            setDonePressed(false);
        }
    } else if (requestCode == LOAD_FULL_WALLET_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {
            FullWallet fullWallet = data.getParcelableExtra(WalletConstants.EXTRA_FULL_WALLET);
            String tokenJSON = fullWallet.getPaymentMethodToken().getToken();
            try {
                if (androidPayPublicKey != null) {
                    androidPayCredentials = new TLRPC.TL_inputPaymentCredentialsAndroidPay();
                    androidPayCredentials.payment_token = new TLRPC.TL_dataJSON();
                    androidPayCredentials.payment_token.data = tokenJSON;
                    androidPayCredentials.google_transaction_id = fullWallet.getGoogleTransactionId();
                    String[] descriptions = fullWallet.getPaymentDescriptions();
                    if (descriptions.length > 0) {
                        cardName = descriptions[0];
                    } else {
                        cardName = "Android Pay";
                    }
                } else {
                    Token token = TokenParser.parseToken(tokenJSON);
                    paymentJson = String.format(Locale.US, "{\"type\":\"%1$s\", \"id\":\"%2$s\"}", token.getType(), token.getId());
                    Card card = token.getCard();
                    cardName = card.getType() + " *" + card.getLast4();
                }
                goToNextStep();
                showEditDoneProgress(true, false);
                setDonePressed(false);
            } catch (JSONException ignore) {
                showEditDoneProgress(true, false);
                setDonePressed(false);
            }
        } else {
            showEditDoneProgress(true, false);
            setDonePressed(false);
        }
    }
}
 
Example #29
Source File: GooglePaymentTest.java    From braintree_android with MIT License 4 votes vote down vote up
@Test
public void requestPayment_startsActivityWithOptionalValues() throws JSONException {
    BraintreeFragment fragment = getSetupFragment();
    String googlePaymentModuleVersion = com.braintreepayments.api.googlepayment.BuildConfig.VERSION_NAME;
    GooglePaymentRequest googlePaymentRequest = new GooglePaymentRequest()
            .allowPrepaidCards(true)
            .billingAddressFormat(1)
            .billingAddressRequired(true)
            .emailRequired(true)
            .phoneNumberRequired(true)
            .shippingAddressRequired(true)
            .shippingAddressRequirements(ShippingAddressRequirements.newBuilder().addAllowedCountryCode("USA").build())
            .transactionInfo(TransactionInfo.newBuilder()
                    .setTotalPrice("1.00")
                    .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
                    .setCurrencyCode("USD")
                    .build());

    GooglePayment.requestPayment(fragment, googlePaymentRequest);

    ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
    verify(fragment).startActivityForResult(captor.capture(), eq(BraintreeRequestCodes.GOOGLE_PAYMENT));
    Intent intent = captor.getValue();

    assertEquals(GooglePaymentActivity.class.getName(), intent.getComponent().getClassName());
    assertEquals(WalletConstants.ENVIRONMENT_TEST, intent.getIntExtra(EXTRA_ENVIRONMENT, -1));
    PaymentDataRequest paymentDataRequest = intent.getParcelableExtra(EXTRA_PAYMENT_DATA_REQUEST);

    JSONObject paymentDataRequestJson = new JSONObject(paymentDataRequest.toJson());

    assertEquals(2, paymentDataRequestJson.get("apiVersion"));
    assertEquals(0, paymentDataRequestJson.get("apiVersionMinor"));

    assertEquals(true, paymentDataRequestJson.get("emailRequired"));
    assertEquals(true, paymentDataRequestJson.get("shippingAddressRequired"));

    JSONObject transactionInfoJson = paymentDataRequestJson.getJSONObject("transactionInfo");
    assertEquals("FINAL", transactionInfoJson.getString("totalPriceStatus"));
    assertEquals("1.00", transactionInfoJson.getString("totalPrice"));
    assertEquals("USD", transactionInfoJson.getString("currencyCode"));

    JSONArray allowedPaymentMethods = paymentDataRequestJson.getJSONArray("allowedPaymentMethods");
    JSONObject paypal = allowedPaymentMethods.getJSONObject(0);
    assertEquals("PAYPAL", paypal.getString("type"));

    JSONArray purchaseUnits = paypal.getJSONObject("parameters")
            .getJSONObject("purchase_context")
            .getJSONArray("purchase_units");
    assertEquals(1, purchaseUnits.length());

    JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
    assertEquals("paypal-client-id-for-google-payment", purchaseUnit.getJSONObject("payee")
            .getString("client_id"));
    assertEquals("true", purchaseUnit.getString("recurring_payment"));

    JSONObject paypalTokenizationSpecification = paypal.getJSONObject("tokenizationSpecification");
    assertEquals("PAYMENT_GATEWAY", paypalTokenizationSpecification.getString("type"));

    JSONObject paypalTokenizationSpecificationParams = paypalTokenizationSpecification.getJSONObject("parameters");
    assertEquals("braintree", paypalTokenizationSpecificationParams.getString("gateway"));
    assertEquals("v1", paypalTokenizationSpecificationParams.getString("braintree:apiVersion"));
    assertEquals(googlePaymentModuleVersion, paypalTokenizationSpecificationParams.getString("braintree:sdkVersion"));
    assertEquals("android-pay-merchant-id", paypalTokenizationSpecificationParams.getString("braintree:merchantId"));
    assertEquals("{\"source\":\"client\",\"version\":\"" + googlePaymentModuleVersion + "\",\"platform\":\"android\"}", paypalTokenizationSpecificationParams.getString("braintree:metadata"));
    assertFalse(paypalTokenizationSpecificationParams.has("braintree:clientKey"));
    assertEquals("paypal-client-id-for-google-payment", paypalTokenizationSpecificationParams.getString("braintree:paypalClientId"));

    JSONObject card = allowedPaymentMethods.getJSONObject(1);
    assertEquals("CARD", card.getString("type"));

    JSONObject cardParams = card.getJSONObject("parameters");
    assertTrue(cardParams.getBoolean("billingAddressRequired"));
    assertTrue(cardParams.getBoolean("allowPrepaidCards"));

    assertEquals("PAN_ONLY", cardParams.getJSONArray("allowedAuthMethods").getString(0));
    assertEquals("CRYPTOGRAM_3DS", cardParams.getJSONArray("allowedAuthMethods").getString(1));

    assertEquals("VISA", cardParams.getJSONArray("allowedCardNetworks").getString(0));
    assertEquals("MASTERCARD", cardParams.getJSONArray("allowedCardNetworks").getString(1));
    assertEquals("AMEX", cardParams.getJSONArray("allowedCardNetworks").getString(2));
    assertEquals("DISCOVER", cardParams.getJSONArray("allowedCardNetworks").getString(3));

    JSONObject tokenizationSpecification = card.getJSONObject("tokenizationSpecification");
    assertEquals("PAYMENT_GATEWAY", tokenizationSpecification.getString("type"));

    JSONObject cardTokenizationSpecificationParams = tokenizationSpecification.getJSONObject("parameters");
    assertEquals("braintree", cardTokenizationSpecificationParams.getString("gateway"));
    assertEquals("v1", cardTokenizationSpecificationParams.getString("braintree:apiVersion"));
    assertEquals(googlePaymentModuleVersion, cardTokenizationSpecificationParams.getString("braintree:sdkVersion"));
    assertEquals("android-pay-merchant-id", cardTokenizationSpecificationParams.getString("braintree:merchantId"));
    assertEquals("{\"source\":\"client\",\"version\":\"" + googlePaymentModuleVersion + "\",\"platform\":\"android\"}", cardTokenizationSpecificationParams.getString("braintree:metadata"));
    assertEquals("sandbox_tokenization_key", cardTokenizationSpecificationParams.getString("braintree:clientKey"));
}
 
Example #30
Source File: PaymentFormActivity.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
private void showAndroidPay() {
    if (getParentActivity() == null || androidPayContainer == null) {
        return;
    }

    WalletFragmentOptions.Builder optionsBuilder = WalletFragmentOptions.newBuilder();
    optionsBuilder.setEnvironment(paymentForm.invoice.test ? WalletConstants.ENVIRONMENT_TEST : WalletConstants.ENVIRONMENT_PRODUCTION);
    optionsBuilder.setMode(WalletFragmentMode.BUY_BUTTON);

    WalletFragmentStyle walletFragmentStyle;
    if (androidPayPublicKey != null) {
        androidPayContainer.setBackgroundColor(androidPayBackgroundColor);
        walletFragmentStyle = new WalletFragmentStyle()
                .setBuyButtonText(WalletFragmentStyle.BuyButtonText.BUY_WITH)
                .setBuyButtonAppearance(androidPayBlackTheme ? WalletFragmentStyle.BuyButtonAppearance.ANDROID_PAY_LIGHT_WITH_BORDER : WalletFragmentStyle.BuyButtonAppearance.ANDROID_PAY_DARK)
                .setBuyButtonWidth(WalletFragmentStyle.Dimension.MATCH_PARENT);
    } else {
        walletFragmentStyle = new WalletFragmentStyle()
                .setBuyButtonText(WalletFragmentStyle.BuyButtonText.LOGO_ONLY)
                .setBuyButtonAppearance(WalletFragmentStyle.BuyButtonAppearance.ANDROID_PAY_LIGHT_WITH_BORDER)
                .setBuyButtonWidth(WalletFragmentStyle.Dimension.WRAP_CONTENT);
    }

    optionsBuilder.setFragmentStyle(walletFragmentStyle);
    WalletFragment walletFragment = WalletFragment.newInstance(optionsBuilder.build());
    FragmentManager fragmentManager = getParentActivity().getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(fragment_container_id, walletFragment);
    fragmentTransaction.commit();

    ArrayList<TLRPC.TL_labeledPrice> arrayList = new ArrayList<>(paymentForm.invoice.prices);
    if (shippingOption != null) {
        arrayList.addAll(shippingOption.prices);
    }
    totalPriceDecimal = getTotalPriceDecimalString(arrayList);

    PaymentMethodTokenizationParameters parameters;
    if (androidPayPublicKey != null) {
        parameters = PaymentMethodTokenizationParameters.newBuilder()
                .setPaymentMethodTokenizationType(PaymentMethodTokenizationType.NETWORK_TOKEN)
                .addParameter("publicKey", androidPayPublicKey)
                .build();
    } else {
        parameters = PaymentMethodTokenizationParameters.newBuilder()
                .setPaymentMethodTokenizationType(PaymentMethodTokenizationType.PAYMENT_GATEWAY)
                .addParameter("gateway", "stripe")
                .addParameter("stripe:publishableKey", stripeApiKey)
                .addParameter("stripe:version", StripeApiHandler.VERSION)
                .build();
    }

    MaskedWalletRequest maskedWalletRequest = MaskedWalletRequest.newBuilder()
            .setPaymentMethodTokenizationParameters(parameters)
            .setEstimatedTotalPrice(totalPriceDecimal)
            .setCurrencyCode(paymentForm.invoice.currency)
            .build();

    WalletFragmentInitParams initParams = WalletFragmentInitParams.newBuilder()
            .setMaskedWalletRequest(maskedWalletRequest)
            .setMaskedWalletRequestCode(LOAD_MASKED_WALLET_REQUEST_CODE)
            .build();

    walletFragment.initialize(initParams);
    androidPayContainer.setVisibility(View.VISIBLE);
    AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.playTogether(ObjectAnimator.ofFloat(androidPayContainer, "alpha", 0.0f, 1.0f));
    animatorSet.setInterpolator(new DecelerateInterpolator());
    animatorSet.setDuration(180);
    animatorSet.start();
}