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;
  }
  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;
  }
  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;
  }
 @Test
 public void partnerIdAlias() {
   BraintreeGateway config =
       BraintreeGateway.forPartner(
           Environment.DEVELOPMENT, "partner_id", "publicKey", "privateKey");
   assertEquals(config.getPublicKey(), "publicKey");
   assertEquals(config.getPrivateKey(), "privateKey");
 }
 @Test
 public void sandboxBaseMerchantUrl() {
   BraintreeGateway config =
       new BraintreeGateway(Environment.SANDBOX, "sandbox_merchant_id", "publicKey", "privateKey");
   assertEquals(
       "https://api.sandbox.braintreegateway.com:443/merchants/sandbox_merchant_id",
       config.baseMerchantURL());
 }
 @Test
 public void productionBaseMerchantUrl() {
   BraintreeGateway config =
       new BraintreeGateway(
           Environment.PRODUCTION, "production_merchant_id", "publicKey", "privateKey");
   assertEquals(
       "https://api.braintreegateway.com:443/merchants/production_merchant_id",
       config.baseMerchantURL());
 }
 public static void escrow(BraintreeGateway gateway, String transactionId) {
   NodeWrapper response =
       new Http(gateway.getConfiguration())
           .put(
               gateway.getConfiguration().getMerchantPath()
                   + "/transactions/"
                   + transactionId
                   + "/escrow");
   assertTrue(response.isSuccess());
 }
 @Test
 public void developmentBaseMerchantUrl() {
   BraintreeGateway config =
       new BraintreeGateway(
           Environment.DEVELOPMENT, "integration_merchant_id", "publicKey", "privateKey");
   String port =
       System.getenv().get("GATEWAY_PORT") == null ? "3000" : System.getenv().get("GATEWAY_PORT");
   assertEquals(
       "http://localhost:" + port + "/merchants/integration_merchant_id",
       config.baseMerchantURL());
 }
 @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
 public void getAuthorizationHeader() {
   BraintreeGateway config =
       new BraintreeGateway(
           Environment.DEVELOPMENT,
           "development_merchant_id",
           "integration_public_key",
           "integration_private_key");
   assertEquals(
       "Basic aW50ZWdyYXRpb25fcHVibGljX2tleTppbnRlZ3JhdGlvbl9wcml2YXRlX2tleQ==",
       config.getAuthorizationHeader());
 }
  public static String createTest3DS(
      BraintreeGateway gateway, String merchantAccountId, ThreeDSecureRequestForTests request) {
    String url =
        gateway.getConfiguration().getMerchantPath()
            + "/three_d_secure/create_verification/"
            + merchantAccountId;
    NodeWrapper response = new Http(gateway.getConfiguration()).post(url, request);
    assertTrue(response.isSuccess());

    String token = response.findString("three-d-secure-token");
    assertNotNull(token);
    return token;
  }
  public static String createOAuthGrant(BraintreeGateway gateway, String merchantId, String scope) {
    Http http = new Http(gateway.getConfiguration());
    OAuthGrantRequest request = new OAuthGrantRequest().scope(scope).merchantId(merchantId);

    NodeWrapper node = http.post("/oauth_testing/grants", request);
    return node.findString("code");
  }
  public static String simulateFormPostForTR(
      BraintreeGateway gateway, Request trParams, Request request, String postUrl) {
    String response = "";
    try {
      String trData = gateway.transparentRedirect().trData(trParams, "http://example.com");
      StringBuilder postData =
          new StringBuilder("tr_data=")
              .append(URLEncoder.encode(trData, "UTF-8"))
              .append("&")
              .append(request.toQueryString());

      URL url = new URL(postUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setInstanceFollowRedirects(false);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");
      connection.addRequestProperty("Accept", "application/xml");
      connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      connection.getOutputStream().write(postData.toString().getBytes("UTF-8"));
      connection.getOutputStream().close();
      if (connection.getResponseCode() == 422) {
        connection.getErrorStream();
      } else {
        connection.getInputStream();
      }

      response = new URL(connection.getHeaderField("Location")).getQuery();
    } catch (IOException e) {
      throw new UnexpectedException(e.getMessage());
    }

    return response;
  }
  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;
  }
 public static Result<Transaction> settlement_decline(
     BraintreeGateway gateway, String transactionId) {
   return gateway.testing().settlementDecline(transactionId);
 }
 public static Result<Transaction> settlement_confirm(
     BraintreeGateway gateway, String transactionId) {
   return gateway.testing().settlementConfirm(transactionId);
 }