@Test
  public void createTransactionFromTransparentRedirectSpecifyingLevel2Attributes() {
    TransactionRequest request =
        new TransactionRequest()
            .amount(TransactionAmount.AUTHORIZE.amount)
            .creditCard()
            .number(CreditCardNumber.VISA.number)
            .expirationDate("05/2009")
            .done();

    TransactionRequest trParams =
        new TransactionRequest()
            .type(Transaction.Type.SALE)
            .taxAmount(new BigDecimal("10.00"))
            .taxExempt(true)
            .purchaseOrderNumber("12345");

    String queryString =
        TestHelper.simulateFormPostForTR(
            gateway, trParams, request, gateway.transparentRedirect().url());
    Result<Transaction> result = gateway.transparentRedirect().confirmTransaction(queryString);

    assertTrue(result.isSuccess());
    Transaction transaction = result.getTarget();
    assertEquals(new BigDecimal("10.00"), transaction.getTaxAmount());
    assertTrue(transaction.isTaxExempt());
    assertEquals("12345", transaction.getPurchaseOrderNumber());
  }
  private static String generatePayPalNonce(BraintreeGateway gateway, QueryString payload) {
    String encodedClientToken = gateway.clientToken().generate();
    String clientToken = TestHelper.decodeClientToken(encodedClientToken);

    String authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken);
    Configuration configuration = gateway.getConfiguration();
    String url =
        configuration.getBaseURL()
            + configuration.getMerchantPath()
            + "/client_api/v1/payment_methods/paypal_accounts";

    payload
        .append("authorization_fingerprint", authorizationFingerprint)
        .append("shared_customer_identifier_type", "testing")
        .append("shared_customer_identifier", "test-identifier")
        .append("paypal_account[options][validate]", "false");

    String responseBody;
    String nonce = "";
    try {
      responseBody = HttpHelper.post(url, payload.toString());
      nonce = extractParamFromJson("nonce", responseBody);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return nonce;
  }
  @Test
  public void createTransactionFromTransparentRedirectSpecifyingDescriptor() {
    TransactionRequest request =
        new TransactionRequest()
            .amount(TransactionAmount.AUTHORIZE.amount)
            .creditCard()
            .number(CreditCardNumber.VISA.number)
            .expirationDate("05/2009")
            .done();

    TransactionRequest trParams =
        new TransactionRequest()
            .type(Transaction.Type.SALE)
            .descriptor()
            .name("123*123456789012345678")
            .phone("3334445555")
            .done();

    String queryString =
        TestHelper.simulateFormPostForTR(
            gateway, trParams, request, gateway.transparentRedirect().url());
    Result<Transaction> result = gateway.transparentRedirect().confirmTransaction(queryString);

    assertTrue(result.isSuccess());
    Transaction transaction = result.getTarget();
    assertEquals("123*123456789012345678", transaction.getDescriptor().getName());
    assertEquals("3334445555", transaction.getDescriptor().getPhone());
  }
  @Test
  public void updateCreditCardFromTransparentRedirect() {
    Customer customer = gateway.customer().create(new CustomerRequest()).getTarget();
    CreditCardRequest request =
        new CreditCardRequest()
            .customerId(customer.getId())
            .number("5105105105105100")
            .expirationDate("05/12");
    CreditCard card = gateway.creditCard().create(request).getTarget();

    CreditCardRequest updateRequest = new CreditCardRequest();
    CreditCardRequest trParams =
        new CreditCardRequest()
            .paymentMethodToken(card.getToken())
            .number("4111111111111111")
            .expirationDate("10/10");
    String queryString =
        TestHelper.simulateFormPostForTR(
            gateway, trParams, updateRequest, gateway.transparentRedirect().url());

    Result<CreditCard> result = gateway.transparentRedirect().confirmCreditCard(queryString);

    assertTrue(result.isSuccess());
    CreditCard updatedCreditCard = gateway.creditCard().find(card.getToken());
    assertEquals("411111", updatedCreditCard.getBin());
    assertEquals("1111", updatedCreditCard.getLast4());
    assertEquals("10/2010", updatedCreditCard.getExpirationDate());
  }
  public static String generateNonceForCreditCard(
      BraintreeGateway gateway,
      CreditCardRequest creditCardRequest,
      String customerId,
      boolean validate) {
    ClientTokenRequest clientTokenRequest = new ClientTokenRequest().customerId(customerId);

    String encodedClientToken = gateway.clientToken().generate(clientTokenRequest);
    String clientToken = TestHelper.decodeClientToken(encodedClientToken);

    String authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken);
    Configuration configuration = gateway.getConfiguration();
    String url =
        configuration.getBaseURL()
            + configuration.getMerchantPath()
            + "/client_api/v1/payment_methods/credit_cards";
    QueryString payload = new QueryString();
    payload
        .append("authorization_fingerprint", authorizationFingerprint)
        .append("shared_customer_identifier_type", "testing")
        .append("shared_customer_identifier", "fake_identifier")
        .append("credit_card[options][validate]", new Boolean(validate).toString());

    String responseBody;
    String nonce = "";
    try {
      String payloadString = payload.toString();
      payloadString += "&" + creditCardRequest.toQueryString();
      responseBody = HttpHelper.post(url, payloadString);
      nonce = extractParamFromJson("nonce", responseBody);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return nonce;
  }
  public static String generateUnlockedNonce(
      BraintreeGateway gateway, String customerId, String creditCardNumber) {
    ClientTokenRequest request = new ClientTokenRequest();
    if (customerId != null) {
      request = request.customerId(customerId);
    }
    String encodedClientToken = gateway.clientToken().generate(request);
    String clientToken = TestHelper.decodeClientToken(encodedClientToken);

    String authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken);
    Configuration configuration = gateway.getConfiguration();
    String url =
        configuration.getBaseURL() + configuration.getMerchantPath() + "/client_api/nonces.json";
    QueryString payload = new QueryString();
    payload
        .append("authorization_fingerprint", authorizationFingerprint)
        .append("shared_customer_identifier_type", "testing")
        .append("shared_customer_identifier", "test-identifier")
        .append("credit_card[number]", creditCardNumber)
        .append("credit_card[expiration_month]", "11")
        .append("share", "true")
        .append("credit_card[expiration_year]", "2099");

    String responseBody;
    String nonce = "";
    try {
      responseBody = HttpHelper.post(url, payload.toString());
      nonce = extractParamFromJson("nonce", responseBody);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return nonce;
  }
 @Test
 public void errorNotRaisedWhenReceivingApiErrorResponse() {
   TransactionRequest invalidRequest = new TransactionRequest();
   TransactionRequest trParams = new TransactionRequest().type(Transaction.Type.SALE);
   String queryString =
       TestHelper.simulateFormPostForTR(
           gateway, trParams, invalidRequest, gateway.transparentRedirect().url());
   Result<Transaction> result = gateway.transparentRedirect().confirmTransaction(queryString);
   assertFalse(result.isSuccess());
   assertTrue(result.getErrors().deepSize() > 0);
 }
 @Test(expected = AuthenticationException.class)
 public void authenticationExceptionRaisedWhenBadCredentialsUsingNewTR() {
   CustomerRequest request = new CustomerRequest();
   CustomerRequest trParams = new CustomerRequest();
   BraintreeGateway gateway =
       new BraintreeGateway(
           Environment.DEVELOPMENT, "integration_merchant_id", "bad_public", "bad_private");
   String queryString =
       TestHelper.simulateFormPostForTR(
           gateway, trParams, request, gateway.transparentRedirect().url());
   gateway.transparentRedirect().confirmCustomer(queryString);
 }
 @Test(expected = DownForMaintenanceException.class)
 public void downForMaintenanceExceptionRaisedWhenAppInMaintenanceModeUsingNewTR() {
   CustomerRequest request = new CustomerRequest();
   CustomerRequest trParams = new CustomerRequest();
   Configuration configuration = gateway.getConfiguration();
   String queryString =
       TestHelper.simulateFormPostForTR(
           gateway,
           trParams,
           request,
           configuration.getBaseURL() + configuration.getMerchantPath() + "/test/maintenance");
   gateway.transparentRedirect().confirmCustomer(queryString);
 }
  @Test
  public void createCustomerFromTransparentRedirect() {
    CustomerRequest request = new CustomerRequest().firstName("John");
    CustomerRequest trParams = new CustomerRequest().lastName("Doe");
    String queryString =
        TestHelper.simulateFormPostForTR(
            gateway, trParams, request, gateway.transparentRedirect().url());

    Result<Customer> result = gateway.transparentRedirect().confirmCustomer(queryString);

    assertTrue(result.isSuccess());
    assertEquals("John", result.getTarget().getFirstName());
    assertEquals("Doe", result.getTarget().getLastName());
  }
  @Test
  public void errorRaisedWhenConfirmingIncorrectResource() {
    CustomerRequest request = new CustomerRequest().firstName("John");
    CustomerRequest trParams = new CustomerRequest().lastName("Doe");
    String queryString =
        TestHelper.simulateFormPostForTR(
            gateway, trParams, request, gateway.transparentRedirect().url());

    try {
      gateway.transparentRedirect().confirmTransaction(queryString);
      assertTrue(false);
    } catch (IllegalArgumentException e) {
      assertEquals(
          "You attemped to confirm a transaction, but received a customer.", e.getMessage());
    }
  }
  public static String generateEuropeBankAccountNonce(BraintreeGateway gateway, Customer customer) {
    SEPAClientTokenRequest request = new SEPAClientTokenRequest();
    request.customerId(customer.getId());
    request.mandateType(EuropeBankAccount.MandateType.BUSINESS);
    request.mandateAcceptanceLocation("Rostock, Germany");

    String encodedClientToken = gateway.clientToken().generate(request);
    String clientToken = TestHelper.decodeClientToken(encodedClientToken);

    String authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken);
    Configuration configuration = gateway.getConfiguration();
    String url =
        configuration.getBaseURL()
            + configuration.getMerchantPath()
            + "/client_api/v1/sepa_mandates";
    QueryString payload = new QueryString();
    payload
        .append("authorization_fingerprint", authorizationFingerprint)
        .append("sepa_mandate[locale]", "de-DE")
        .append("sepa_mandate[bic]", "DEUTDEFF")
        .append("sepa_mandate[iban]", "DE89370400440532013000")
        .append("sepa_mandate[accountHolderName]", "Bob Holder")
        .append("sepa_mandate[billingAddress][streetAddress]", "123 Currywurst Way")
        .append("sepa_mandate[billingAddress][extendedAddress]", "Lager Suite")
        .append("sepa_mandate[billingAddress][firstName]", "Wilhelm")
        .append("sepa_mandate[billingAddress][lastName]", "Dix")
        .append("sepa_mandate[billingAddress][locality]", "Frankfurt")
        .append("sepa_mandate[billingAddress][postalCode]", "60001")
        .append("sepa_mandate[billingAddress][countryCodeAlpha2]", "DE")
        .append("sepa_mandate[billingAddress][region]", "Hesse");

    String responseBody;
    String nonce = "";
    try {
      responseBody = HttpHelper.post(url, payload.toString());
      nonce = extractParamFromJson("nonce", responseBody);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    return nonce;
  }
  @Test
  public void createTransactionFromTransparentRedirectSpecifyingMerchantAccountId() {
    TransactionRequest request =
        new TransactionRequest()
            .amount(TransactionAmount.AUTHORIZE.amount)
            .creditCard()
            .number(CreditCardNumber.VISA.number)
            .expirationDate("05/2009")
            .done();

    TransactionRequest trParams =
        new TransactionRequest()
            .type(Transaction.Type.SALE)
            .merchantAccountId(NON_DEFAULT_MERCHANT_ACCOUNT_ID);

    String queryString =
        TestHelper.simulateFormPostForTR(
            gateway, trParams, request, gateway.transparentRedirect().url());
    Result<Transaction> result = gateway.transparentRedirect().confirmTransaction(queryString);

    assertTrue(result.isSuccess());
    assertEquals(NON_DEFAULT_MERCHANT_ACCOUNT_ID, result.getTarget().getMerchantAccountId());
  }
  @Test
  public void createTransactionFromTransparentRedirect() {
    TransactionRequest request =
        new TransactionRequest()
            .amount(TransactionAmount.AUTHORIZE.amount)
            .creditCard()
            .number(CreditCardNumber.VISA.number)
            .expirationDate("05/2009")
            .done()
            .options()
            .storeInVault(true)
            .done();

    TransactionRequest trParams = new TransactionRequest().type(Transaction.Type.SALE);

    String queryString =
        TestHelper.simulateFormPostForTR(
            gateway, trParams, request, gateway.transparentRedirect().url());
    Result<Transaction> result = gateway.transparentRedirect().confirmTransaction(queryString);
    assertTrue(result.isSuccess());
    assertEquals(
        CreditCardNumber.VISA.number.substring(0, 6), result.getTarget().getCreditCard().getBin());
    assertEquals(TransactionAmount.AUTHORIZE.amount, result.getTarget().getAmount());
  }