public static string GetNonceForNewPaymentMethod(BraintreeGateway gateway, Params @params, bool isCreditCard) { var clientToken = GenerateDecodedClientToken(gateway); var authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken); var paymentMethodType = isCreditCard ? "credit_card" : "paypal_account"; var paymentMethodTypePlural = paymentMethodType + "s"; var builder = new RequestBuilder(); builder. AddTopLevelElement("authorization_fingerprint", authorizationFingerprint). AddTopLevelElement("shared_customer_identifier", "test-identifier"). AddTopLevelElement("shared_customer_identifier_type", "testing"); foreach (var param in @params) { builder.AddTopLevelElement(string.Format("{0}[{1}]", paymentMethodType, param.Key), param.Value.ToString()); } var response = new BraintreeTestHttpService().Post( gateway.MerchantId, "v1/payment_methods/" + paymentMethodTypePlural, builder.ToQueryString()); #if netcore StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8); string responseBody = reader.ReadToEnd(); return(extractParamFromJson("nonce", responseBody)); #else return(extractParamFromJson("nonce", response)); #endif }
public static string GenerateFuturePaymentPayPalNonce(BraintreeGateway gateway) { var clientToken = GenerateDecodedClientToken(gateway); var authorizationFingerprint = extractParamFromJson("authorizationFingerprint", clientToken); RequestBuilder builder = new RequestBuilder(""); builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint). AddTopLevelElement("shared_customer_identifier_type", "testing"). AddTopLevelElement("shared_customer_identifier", "test-identifier"). AddTopLevelElement("paypal_account[consent_code]", "consent"). AddTopLevelElement("paypal_account[correlation_id]", Guid.NewGuid().ToString()). AddTopLevelElement("paypal_account[options][validate]", "false"); var response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/paypal_accounts", builder.ToQueryString()); #if netcore StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8); #else StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); #endif string responseBody = reader.ReadToEnd(); Regex regex = new Regex("nonce\":\"(?<nonce>[a-f0-9\\-]+)\""); Match match = regex.Match(responseBody); return(match.Groups["nonce"].Value); }
public void Constructor_RaisesDownForMaintenanceExceptionIfDownForMaintenance() { BraintreeGateway gateway = new BraintreeGateway() { Environment = Environment.DEVELOPMENT, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; BraintreeService service = new BraintreeService(gateway.Configuration); Exception exception = null; try { CustomerRequest trParams = new CustomerRequest(); CustomerRequest request = new CustomerRequest { FirstName = "John", LastName = "Doe" }; string queryString = TestHelper.QueryStringForTR(trParams, request, service.BaseMerchantURL() + "/test/maintenance", service); gateway.Customer.ConfirmTransparentRedirect(queryString); } catch (Exception localException) { exception = localException; } Assert.IsNotNull(exception); Assert.IsInstanceOfType(typeof(DownForMaintenanceException), exception); }
public void Constructor_AuthenticationExceptionIfBadCredentials() { BraintreeGateway gateway = new BraintreeGateway() { Environment = Environment.DEVELOPMENT, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "bad_key" }; BraintreeService service = new BraintreeService(gateway.Configuration); Exception exception = null; try { CustomerRequest trParams = new CustomerRequest(); CustomerRequest request = new CustomerRequest { FirstName = "John", LastName = "Doe" }; string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.Customer.TransparentRedirectURLForCreate(), service); gateway.Customer.ConfirmTransparentRedirect(queryString); } catch (Exception localException) { exception = localException; } Assert.IsNotNull(exception); Assert.IsInstanceOfType(typeof(AuthenticationException), exception); }
public void Generate_RaisesExceptionIfFailOnDuplicatePaymentMethodIsIncludedWithoutCustomerId() { BraintreeGateway gateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; Exception exception = null; try { gateway.ClientToken.generate( new ClientTokenRequest { Options = new ClientTokenOptionsRequest { FailOnDuplicatePaymentMethod = true } } ); } catch (Exception tempException) { exception = tempException; } Assert.IsNotNull(exception); Assert.IsTrue(Regex.Match(exception.Message, @"FailOnDuplicatePaymentMethod").Success); Assert.IsInstanceOf(typeof(ArgumentException), exception); }
public static string GenerateDecodedClientToken(BraintreeGateway gateway, ClientTokenRequest request = null) { var encodedClientToken = gateway.ClientToken.Generate(request); var decodedClientToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(encodedClientToken)); var unescapedClientToken = System.Text.RegularExpressions.Regex.Unescape(decodedClientToken); return unescapedClientToken; }
public void Generate_DefaultToken() { var gateway = new BraintreeGateway(); Assert.IsNotNull(gateway.ClientToken); string token = gateway.ClientToken.Generate(); Assert.IsNotEmpty(token); }
public void Setup() { gateway = new BraintreeGateway( "client_id$development$integration_client_id", "client_secret$development$integration_client_secret" ); }
private static TokenizedCreditCardResponse TokenizedCreditCard( BraintreeGateway client, string encryptedCreditCardNumber, string encryptedExpirationDate, string encryptedCvv, string paymentMethodNonce = null) { try { var request = new CustomerRequest { CreditCard = new CreditCardRequest { Number = encryptedCreditCardNumber, ExpirationDate = encryptedExpirationDate, CVV = encryptedCvv, PaymentMethodNonce = paymentMethodNonce, // Used for tokenization from javascript API Options = new CreditCardOptionsRequest { VerifyCard = true } } }; var result = client.Customer.Create(request); var customer = result.Target; var creditCardCvvSuccess = CheckCvvResponseCodeForSuccess(customer); if (!result.IsSuccess() || !creditCardCvvSuccess) { return(new TokenizedCreditCardResponse { IsSuccessful = false, Message = result.Message }); } var creditCard = customer.CreditCards.First(); return(new TokenizedCreditCardResponse { CardOnFileToken = creditCard.Token, CardType = creditCard.CardType.ToString(), LastFour = creditCard.LastFour, IsSuccessful = result.IsSuccess(), Message = result.Message }); } catch (Exception e) { return(new TokenizedCreditCardResponse { IsSuccessful = false, Message = e.Message }); } }
public CheckoutController(BurgerStoreDbContext burgerstoredbcontext, EmailService emailService, SignInManager <BurgerStoreUser> signInManager, BraintreeGateway braintreeGateway, SmartyStreets.USStreetApi.Client usStreetApiClient) { this._burgerStoreDbContext = burgerstoredbcontext; this._emailService = emailService; this._signInManager = signInManager; this._braintreeGateway = braintreeGateway; this._usStreetApiClient = usStreetApiClient; }
public static string GenerateDecodedClientToken(BraintreeGateway gateway, ClientTokenRequest request = null) { var encodedClientToken = gateway.ClientToken.generate(request); var decodedClientToken = Encoding.UTF8.GetString(Convert.FromBase64String(encodedClientToken)); var unescapedClientToken = Regex.Unescape(decodedClientToken); return(unescapedClientToken); }
public void CreateTokenFromCode_RaisesIfWrongCredentials() { gateway = new BraintreeGateway( "access_token$development$merchant_id$_oops_this_is_not_a_client_id_and_secret" ); gateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest()); }
//public AccountController(SignInManager<OrganicStoreUser> signInManager, IConfiguration configuration) //{ // this._signInManager = signInManager; // this._sendGridKey = configuration["SendGridKey"]; //} public AccountController(SignInManager <OrganicStoreUser> signInManager, EmailService emailService, BraintreeGateway braintreeGateway) { this._signInManager = signInManager; this._emailService = emailService; _braintreeGateway = braintreeGateway; }
public static string ProcessRequest(HttpContext context) { BraintreeGateway gateway = new BraintreeGateway("access_token$sandbox$ym2fhwysk723gtg4$2e18ce46a546af041a2f90f2d46eb441"); var clientToken = gateway.ClientToken.Generate(); context.Response.WriteAsync(clientToken); return(clientToken); }
public IActionResult Payment(int Id) { ViewData["AllCategories"] = _categoryRepository.GetAll().ToList(); ViewData["Index"] = Id; ViewData["BraintreeClientID"] = new BraintreeGateway("sandbox", "ncsh7wwqvzs3cx9q", "6j4d7qspt5n48kx4", "bd1c26e53a6d811243fcc3eb268113e1").ClientToken.Generate(); return(View()); }
public CheckoutController(CountryClubDbContext countryClubDbContext, EmailService emailService, SignInManager <CountryClubUser> signInManager, BraintreeGateway braintreeGateway, SmartyStreets.USStreetApi.Client usStreetApiClient) { this._countryClubDbContext = countryClubDbContext; this._emailService = emailService; this._signInManager = signInManager; this._brainTreeGateway = braintreeGateway; this._usStreetApiClient = usStreetApiClient; }
public void CreateTokenFromCode_RaisesIfWrongCredentials() { gateway = new BraintreeGateway( "access_token$development$merchant_id$_oops_this_is_not_a_client_id_and_secret" ); Assert.Throws<ConfigurationException>(() => gateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest())); }
public RegistrationController(ApplicationDbContext db, ILoggerFactory factory, IOptions <Secrets> secrets, IEmailSender esvc, ITotalCalculator calc) { _db = db; _logger = factory.CreateLogger("All"); _gateway = new BraintreeGateway(secrets.Value.paypaltoken); _email = esvc; _calc = calc; }
public void CreateTokenFromCode_RaisesIfWrongCredentials() { gateway = new BraintreeGateway( "access_token$development$merchant_id$_oops_this_is_not_a_client_id_and_secret" ); Assert.Throws <ConfigurationException>(() => gateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest())); }
public BraintreeResponse MakePayment(string nonce) { BraintreeGateway braintreeGateway = GetGateway(); TransactionRequest request = new TransactionRequest { Amount = _cartModel.TotalToPay, PaymentMethodNonce = nonce, BillingAddress = GetBillingAddress(), Options = new TransactionOptionsRequest { ThreeDSecure = new TransactionOptionsThreeDSecureRequest { Required = _braintreeSettings.ThreeDSecureRequired } } }; Result <Transaction> result = braintreeGateway.Transaction.Sale(request); // send transction request if (result.IsSuccess()) { Order order = _orderPlacementService.PlaceOrder(_cartModel, o => { o.PaymentStatus = PaymentStatus.Paid; o.CaptureTransactionId = result.Target.Id; }); // Success return(new BraintreeResponse { Success = true, Order = order }); } // error return List <string> errorList = result.Errors.DeepAll() .Select( error => string.Format("Code: {0}, Message: {1}, Attribute: {2}", error.Code, error.Message, error.Attribute)) .ToList(); _logAdminService.Insert(new Log { Error = new Error(), Message = "Braintree Error Details", Detail = string.Join("<br/>", errorList) }); return(new BraintreeResponse { Success = false, Errors = new List <string> { result.Message } }); }
/// <summary> /// Invoke view component /// </summary> /// <param name="widgetZone">Widget zone name</param> /// <param name="additionalData">Additional data</param> /// <returns>View component result</returns> public IViewComponentResult Invoke(string widgetZone, object additionalData) { var model = new PaymentInfoModel(); if (_braintreePaymentSettings.Use3DS) { try { var gateway = new BraintreeGateway { Environment = _braintreePaymentSettings.UseSandbox ? Environment.SANDBOX : Environment.PRODUCTION, MerchantId = _braintreePaymentSettings.MerchantId, PublicKey = _braintreePaymentSettings.PublicKey, PrivateKey = _braintreePaymentSettings.PrivateKey }; var clientToken = gateway.ClientToken.Generate(); var cart = _shoppingCartService .GetShoppingCart(_workContext.CurrentCustomer, ShoppingCartType.ShoppingCart, _storeContext.CurrentStore.Id); var orderTotal = _orderTotalCalculationService.GetShoppingCartTotal(cart); model.ClientToken = clientToken; model.OrderTotal = orderTotal; } catch (Exception exception) { model.Errors = exception.Message; if (_orderSettings.OnePageCheckoutEnabled) { ModelState.AddModelError(string.Empty, exception.Message); } else { _notificationService.ErrorNotification(exception); } } return(View("~/Plugins/Payments.Braintree/Views/PaymentInfo.3DS.cshtml", model)); } for (var i = 0; i < 15; i++) { var year = Convert.ToString(DateTime.Now.Year + i); model.ExpireYears.Add(new SelectListItem { Text = year, Value = year, }); } for (var i = 1; i <= 12; i++) { var text = (i < 10) ? "0" + i : i.ToString(); model.ExpireMonths.Add(new SelectListItem { Text = text, Value = i.ToString(), }); } return(View("~/Plugins/Payments.Braintree/Views/PaymentInfo.cshtml", model)); }
public BakedPiPaymentServices() { string merchantId = System.Configuration.ConfigurationManager.AppSettings["Braintree.MerchantId"]; string environment = System.Configuration.ConfigurationManager.AppSettings["Braintree.Environment"]; string publicKey = System.Configuration.ConfigurationManager.AppSettings["Braintree.PublicKey"]; string privateKey = System.Configuration.ConfigurationManager.AppSettings["Braintree.PrivateKey"]; gateway = new BraintreeGateway(environment, merchantId, publicKey, privateKey); }
public void Generate_GatewayRespectsFailOnDuplicatePaymentMethod() { BraintreeGateway gateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; Result <Customer> result = gateway.Customer.Create(new CustomerRequest()); Assert.IsTrue(result.IsSuccess()); string customerId = result.Target.Id; var request = new CreditCardRequest { CustomerId = customerId, Number = "4111111111111111", ExpirationDate = "05/2099" }; Result <CreditCard> creditCardResult = gateway.CreditCard.Create(request); Assert.IsTrue(creditCardResult.IsSuccess()); var clientToken = TestHelper.GenerateDecodedClientToken(gateway, new ClientTokenRequest { CustomerId = customerId, Options = new ClientTokenOptionsRequest { FailOnDuplicatePaymentMethod = true } } ); var authorizationFingerprint = TestHelper.extractParamFromJson("authorizationFingerprint", clientToken); RequestBuilder builder = new RequestBuilder(""); builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint). AddTopLevelElement("shared_customer_identifier_type", "testing"). AddTopLevelElement("shared_customer_identifier", "test-identifier"). AddTopLevelElement("credit_card[number]", "4111111111111111"). AddTopLevelElement("credit_card[expiration_month]", "11"). AddTopLevelElement("credit_card[expiration_year]", "2099"); HttpWebResponse response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/credit_cards.json", builder.ToQueryString()); response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/credit_cards.json", builder.ToQueryString()); Assert.AreEqual(422, (int)response.StatusCode); response.Close(); Customer customer = gateway.Customer.Find(customerId); Assert.AreEqual(1, customer.CreditCards.Length); }
public void MultipleAttemptConfirm_MicroTransferVerification() { gateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "integration2_merchant_id", PublicKey = "integration2_public_key", PrivateKey = "integration2_private_key" }; Result <Customer> customer = gateway.Customer.Create(new CustomerRequest()); Assert.IsTrue(customer.IsSuccess()); var request = new PaymentMethodRequest { CustomerId = customer.Target.Id, PaymentMethodNonce = TestHelper.GenerateValidUsBankAccountNonce(gateway, "1000000000"), Options = new PaymentMethodOptionsRequest { VerificationMerchantAccountId = MerchantAccountIDs.ANOTHER_US_BANK_MERCHANT_ACCOUNT_ID, UsBankAccountVerificationMethod = UsBankAccountVerificationMethod.MICRO_TRANSFERS } }; Result <PaymentMethod> result = gateway.PaymentMethod.Create(request); Assert.IsTrue(result.IsSuccess()); UsBankAccount usBankAccount = (UsBankAccount)result.Target; Assert.IsNotNull(usBankAccount.Token); UsBankAccountVerification verification = usBankAccount.Verifications[0]; Assert.AreEqual(UsBankAccountVerificationMethod.MICRO_TRANSFERS, verification.VerificationMethod); Assert.AreEqual(UsBankAccountVerificationStatus.PENDING, verification.Status); var confirmRequest = new UsBankAccountVerificationConfirmRequest { DepositAmounts = new int[] { 1, 1 } }; for (int i = 0; i < 4; i++) { var r = gateway.UsBankAccountVerification.ConfirmMicroTransferAmounts(verification.Id, confirmRequest); Assert.IsFalse(r.IsSuccess()); Assert.AreEqual( ValidationErrorCode.US_BANK_ACCOUNT_VERIFICATION_AMOUNTS_DO_NOT_MATCH, r.Errors.ForObject("us-bank-account-verification").OnField("base")[0].Code); } var confirmResult = gateway.UsBankAccountVerification.ConfirmMicroTransferAmounts(verification.Id, confirmRequest); Assert.IsFalse(confirmResult.IsSuccess()); Assert.AreEqual( ValidationErrorCode.US_BANK_ACCOUNT_VERIFICATION_TOO_MANY_CONFIRMATION_ATTEMPTS, confirmResult.Errors.ForObject("us-bank-account-verification").OnField("base")[0].Code); }
/// <summary> /// Returns the customer information on Braintree for the given userID, /// or null if not exists. /// </summary> /// <param name="userID"></param> /// <param name="gateway">Optional, to reuse an opened gateway, else a new one is transparently created</param> /// <returns></returns> public static Braintree.Customer GetBraintreeCustomer(int userID, BraintreeGateway gateway = null) { gateway = LcPayment.NewBraintreeGateway(gateway); try { return(gateway.Customer.Find(GetCustomerId(userID))); } catch (Braintree.Exceptions.NotFoundException ex) { } return(null); }
public static Response SampleNotificationFromXml(BraintreeGateway gateway, string xml) { var response = new Response(); var service = new BraintreeService(gateway.Configuration); response["bt_payload"] = xml; response["bt_signature"] = string.Format("{0}|{1}", service.PublicKey, new Sha1Hasher().HmacHash(service.PrivateKey, xml).Trim().ToLower()); return(response); }
public static string GenerateAuthorizationFingerprint(BraintreeGateway gateway, string customerId = null) { var clientTokenRequest = customerId == null ? null : new ClientTokenRequest { CustomerId = customerId }; var clientToken = GenerateDecodedClientToken(gateway, clientTokenRequest); return(extractParamFromJson("authorizationFingerprint", clientToken)); }
public ReceiptController(ThisSiteDbContext thisSiteDbContext, EmailService emailService, SignInManager <ThisSiteUser> signInManager, BraintreeGateway braintreeGateway) { this._thisSiteDbContext = thisSiteDbContext; this._emailService = emailService; this._signInManager = signInManager; this._brainTreeGateway = braintreeGateway; }
public PaymentService() { gateway = new BraintreeGateway { Environment = ConfigurationManager.AppSettings["Environment"] == "SandBox" ? Braintree.Environment.SANDBOX : Braintree.Environment.PRODUCTION, MerchantId = ConfigurationManager.AppSettings["merchant_id"], PublicKey = ConfigurationManager.AppSettings["public_key"], PrivateKey = ConfigurationManager.AppSettings["private_key"] }; }
public PaymentService() { Gateway = new BraintreeGateway { Environment = Environment.SANDBOX, MerchantId = Settings.Instance["Braintree:MerchantId"], PublicKey = Settings.Instance["Braintree:PublicKey"], PrivateKey = Settings.Instance["Braintree:PrivateKey"] }; }
public BraintreeController() { gateway = new BraintreeGateway() { Environment = Braintree.Environment.SANDBOX, MerchantId = "2p74nh8g8w24swnd", PublicKey = "d4hbp8tbx8yryk3j", PrivateKey = "fecf8ebde9e0da0f62d6fa1f3e2a9f99" }; }
public void Setup() { gateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; }
public static string CreateGrant(BraintreeGateway gateway, string merchantId, string scope) { var service = new BraintreeService(gateway.Configuration); XmlNode node = service.Post("/oauth_testing/grants", new OAuthGrantRequest { MerchantId = merchantId, Scope = scope }); return(node["code"].InnerText); }
public BraintreeController() { _Gateway = new BraintreeGateway { Environment = Braintree.Environment.SANDBOX, MerchantId = "x4g6yxg36ypds2rv", PublicKey = "r4k9gn8zy6vgd6n3", PrivateKey = "1d4028fb0f72c72109b6602f20e0fda6" }; }
public void Setup() { gateway = new BraintreeGateway { //Environment = Environment.DEVELOPMENT, //MerchantId = "integration_merchant_id", //PublicKey = "integration_public_key", //PrivateKey = "integration_private_key" }; service = new BraintreeService(gateway.Configuration); }
/// <summary> /// Constructor /// </summary> /// <param name="account_id"></param> public ProudSourceBrainTree(int account_id) : base(account_id) { gateway = new BraintreeGateway { Environment = Braintree.Environment.SANDBOX, MerchantId = merchant_ID, PublicKey = public_key, PrivateKey = private_key }; }
public void All_RaisesIfMissingCredentials() { gateway = new BraintreeGateway { MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; Assert.Throws<ConfigurationException> (() => gateway.AddOn.All()); }
public void SetConfigurationEnvironment_WithEnvironment() { BraintreeGateway gateway = new BraintreeGateway( Environment.DEVELOPMENT, "integration_merchant_id", "integration_public_key", "integration_private_key" ); Assert.AreEqual(gateway.Environment, Environment.DEVELOPMENT); }
public void FailsInProduction() { var productionGateway = new BraintreeGateway { Environment = Environment.PRODUCTION, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; Assert.Throws<Braintree.Exceptions.TestOperationPerformedInProductionException>(() => productionGateway.TestTransaction.Settle("production_transaction_id")); }
public void Setup() { gateway = new BraintreeGateway { //Environment = Environment.DEVELOPMENT, //MerchantId = "integration_merchant_id", //PublicKey = "integration_public_key", //PrivateKey = "integration_private_key" }; XmlDocument attributesXml = CreateAttributesXml(); attributes = new NodeWrapper(attributesXml).GetNode("//disbursement"); }
public void All_RaisesIfMissingCredentials() { gateway = new BraintreeGateway { MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; try { gateway.AddOn.All(); Assert.Fail("Should throw ConfigurationException"); } catch (ConfigurationException) {} }
public virtual void TestFixtureSetup() { this.TestCustomer = MerchelloContext.Current.Services.CustomerService.CreateCustomerWithKey( Guid.NewGuid().ToString(), "first", "last", "*****@*****.**"); this.BraintreeProviderSettings = TestHelper.GetBraintreeProviderSettings(); AutoMapperMappings.CreateMappings(); this.Gateway = this.BraintreeProviderSettings.AsBraintreeGateway(); this.BraintreeApiService = new BraintreeApiService(this.BraintreeProviderSettings); }
public void Create_MultiCurrencyMerchant() { gateway = new BraintreeGateway( "client_id$development$signup_client_id", "client_secret$development$signup_client_secret" ); ResultImpl<Merchant> result = gateway.Merchant.Create(new MerchantRequest { Email = "*****@*****.**", CountryCodeAlpha3 = "USA", PaymentMethods = new string[] {"paypal"}, CompanyName = "Ziarog LTD", Currencies = new string[] {"GBP", "USD"}, PayPalAccount = new PayPalOnlyAccountRequest { ClientId = "paypal_client_id", ClientSecret = "paypal_client_secret" } }); Assert.IsTrue(result.IsSuccess()); Assert.IsFalse(string.IsNullOrEmpty(result.Target.Id)); Assert.AreEqual("*****@*****.**", result.Target.Email); Assert.AreEqual("Ziarog LTD", result.Target.CompanyName); Assert.AreEqual("USA", result.Target.CountryCodeAlpha3); Assert.AreEqual("US", result.Target.CountryCodeAlpha2); Assert.AreEqual("840", result.Target.CountryCodeNumeric); Assert.AreEqual("United States of America", result.Target.CountryName); Assert.IsTrue(result.Target.Credentials.AccessToken.StartsWith("access_token$")); Assert.IsTrue(result.Target.Credentials.RefreshToken.StartsWith("refresh_token$")); Assert.IsTrue(result.Target.Credentials.ExpiresAt > DateTime.Now); Assert.AreEqual("bearer", result.Target.Credentials.TokenType); Assert.AreEqual(2, result.Target.MerchantAccounts.Length); var usdMerchantAccount = (from ma in result.Target.MerchantAccounts where ma.Id == "USD" select ma).ToArray()[0]; Assert.AreEqual("USD", usdMerchantAccount.CurrencyIsoCode); Assert.IsTrue(usdMerchantAccount.IsDefault.Value); var gbpMerchantAccount = (from ma in result.Target.MerchantAccounts where ma.Id == "GBP" select ma).ToArray()[0]; Assert.AreEqual("GBP", gbpMerchantAccount.CurrencyIsoCode); Assert.IsFalse(gbpMerchantAccount.IsDefault.Value); }
public void Generate_RaisesExceptionIfFailOnDuplicatePaymentMethodIsIncludedWithoutCustomerId() { var gateway = new BraintreeGateway(); try { gateway.ClientToken.Generate( new ClientTokenRequest { Options = new ClientTokenOptionsRequest { FailOnDuplicatePaymentMethod = true } } ); Assert.Fail("Should raise ArgumentException"); } catch (ArgumentException e) { Match match = Regex.Match(e.Message, @"FailOnDuplicatePaymentMethod"); Assert.IsTrue(match.Success); } }
public void Setup() { gateway = new BraintreeGateway { //Environment = Environment.DEVELOPMENT, //MerchantId = "integration_merchant_id", //PublicKey = "integration_public_key", //PrivateKey = "integration_private_key" }; CustomerRequest request = new CustomerRequest { CreditCard = new CreditCardRequest { CardholderName = "Fred Jones", Number = "5555555555554444", ExpirationDate = "05/12" } }; customer = gateway.Customer.Create(request).Target; creditCard = customer.CreditCards[0]; }
public void Setup() { gateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; partnerMerchantGateway = new BraintreeGateway ( Environment.DEVELOPMENT, "integration_merchant_public_id", "oauth_app_partner_user_public_key", "oauth_app_partner_user_private_key" ); oauthGateway = new BraintreeGateway ( "client_id$development$integration_client_id", "client_secret$development$integration_client_secret" ); }
public void Setup() { gateway = new BraintreeGateway(); service = new BraintreeService(gateway.Configuration); }
public void CreateTokenFromCode_RaisesIfWrongCredentials() { try { gateway = new BraintreeGateway( "access_token$development$merchant_id$_oops_this_is_not_a_client_id_and_secret" ); gateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest()); Assert.Fail("Should throw ConfigurationException"); } catch (ConfigurationException) {} }
public void RevokeAccessToken_RevokesAccessToken() { string code = OAuthTestHelper.CreateGrant(gateway, "integration_merchant_id", "read_write"); ResultImpl<OAuthCredentials> accessTokenResult = gateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest { Code = code, Scope = "read_write" }); string accessToken = accessTokenResult.Target.AccessToken; ResultImpl<OAuthResult> result = gateway.OAuth.RevokeAccessToken(accessToken); Assert.IsTrue(result.Target.Result.Value); try { gateway = new BraintreeGateway( accessToken ); gateway.Customer.Create(); Assert.Fail("Should throw AuthenticationException"); } catch (AuthenticationException) {} }
public void Generate_GeneratedFingerprintIsAcceptedByGateway() { var gateway = new BraintreeGateway(); var clientToken = TestHelper.GenerateDecodedClientToken(gateway); var authorizationFingerprint = TestHelper.extractParamFromJson("authorizationFingerprint", clientToken); var encodedFingerprint = HttpUtility.UrlEncode(authorizationFingerprint, Encoding.UTF8); var url = "v1/payment_methods.json"; url += "?authorizationFingerprint=" + encodedFingerprint; url += "&sharedCustomerIdentifierType=testing"; url += "&sharedCustomerIdentifier=test-identifier"; HttpWebResponse response = new BraintreeTestHttpService().Get(gateway.MerchantId, url); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); response.Close(); }
public void PaymentMethodGrantAndRevoke() { Result<Customer> result = partnerMerchantGateway.Customer.Create(new CustomerRequest()); var token = partnerMerchantGateway.PaymentMethod.Create(new PaymentMethodRequest { PaymentMethodNonce = Nonce.Transactable, CustomerId = result.Target.Id }).Target.Token; string code = OAuthTestHelper.CreateGrant(oauthGateway, "integration_merchant_id", "grant_payment_method"); ResultImpl<OAuthCredentials> accessTokenResult = oauthGateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest { Code = code, Scope = "grant_payment_method" }); BraintreeGateway accessTokenGateway = new BraintreeGateway(accessTokenResult.Target.AccessToken); PaymentMethodGrantRequest grantRequest = new PaymentMethodGrantRequest() { AllowVaulting = false, IncludeBillingPostalCode = true }; Result<PaymentMethodNonce> grantResult = accessTokenGateway.PaymentMethod.Grant(token, grantRequest); Assert.IsTrue(grantResult.IsSuccess()); Assert.IsNotNull(grantResult.Target.Nonce); Result<PaymentMethod> revokeResult = accessTokenGateway.PaymentMethod.Revoke(token); Assert.IsTrue(revokeResult.IsSuccess()); }
public void Create_CreateCustomerUsingAccessToken() { var createRequest = new CustomerRequest() { FirstName = "Michael", LastName = "Angelo", Company = "Some Company", Email = "*****@*****.**", Phone = "312.555.1111", Fax = "312.555.1112", Website = "www.example.com", }; //BraintreeGateway oauthGateway = new BraintreeGateway( // "client_id$development$integration_client_id", // "client_secret$development$integration_client_secret" //); //string code = OAuthTestHelper.CreateGrant(oauthGateway, "integration_merchant_id", "read_write"); BraintreeGateway oauthGateway = new BraintreeGateway( "client_id$" + Environment.CONFIGURED.EnvironmentName + "$integration_client_id", "client_secret$" + Environment.CONFIGURED.EnvironmentName + "$integration_client_secret" ); string code = OAuthTestHelper.CreateGrant(oauthGateway, gateway.Configuration.MerchantId, "read_write"); ResultImpl<OAuthCredentials> accessTokenResult = oauthGateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest { Code = code, Scope = "read_write" }); gateway = new BraintreeGateway(accessTokenResult.Target.AccessToken); Customer customer = gateway.Customer.Create(createRequest).Target; Assert.AreEqual("Michael", customer.FirstName); Assert.AreEqual("Angelo", customer.LastName); Assert.AreEqual("Some Company", customer.Company); Assert.AreEqual("*****@*****.**", customer.Email); Assert.AreEqual("312.555.1111", customer.Phone); Assert.AreEqual("312.555.1112", customer.Fax); Assert.AreEqual("www.example.com", customer.Website); Assert.AreEqual(DateTime.Now.Year, customer.CreatedAt.Value.Year); Assert.AreEqual(DateTime.Now.Year, customer.UpdatedAt.Value.Year); }
public void Generate_GatewayRespectsVerifyCard() { var gateway = new BraintreeGateway(); Result<Customer> result = gateway.Customer.Create(new CustomerRequest()); Assert.IsTrue(result.IsSuccess()); string customerId = result.Target.Id; var clientToken = TestHelper.GenerateDecodedClientToken(gateway, new ClientTokenRequest { CustomerId = customerId, Options = new ClientTokenOptionsRequest { VerifyCard = true } } ); var authorizationFingerprint = TestHelper.extractParamFromJson("authorizationFingerprint", clientToken); var builder = new RequestBuilder(""); builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint). AddTopLevelElement("shared_customer_identifier_type", "testing"). AddTopLevelElement("shared_customer_identifier", "test-identifier"). AddTopLevelElement("credit_card[number]", "4000111111111115"). AddTopLevelElement("credit_card[expiration_month]", "11"). AddTopLevelElement("credit_card[expiration_year]", "2099"); HttpWebResponse response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/credit_cards.json", builder.ToQueryString()); Assert.AreEqual(422, (int)response.StatusCode); response.Close(); Customer customer = gateway.Customer.Find(customerId); Assert.AreEqual(0, customer.CreditCards.Length); }
public void Generate_DefaultsToVersionTwo() { var gateway = new BraintreeGateway(); var encodedClientToken = gateway.ClientToken.Generate(); var decodedClientToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(encodedClientToken)); int version = TestHelper.extractIntParamFromJson("version", decodedClientToken); Assert.AreEqual(2, version); }
public void Generate_SupportsVersionOption() { var gateway = new BraintreeGateway(); var clientToken = gateway.ClientToken.Generate( new ClientTokenRequest { Version = 1 } ); int version = TestHelper.extractIntParamFromJson("version", clientToken); Assert.AreEqual(1, version); }
public void Setup() { gateway = new BraintreeGateway(); }
public void Generate_GatewayRespectsMakeDefault() { var gateway = new BraintreeGateway(); Result<Customer> result = gateway.Customer.Create(new CustomerRequest()); Assert.IsTrue(result.IsSuccess()); string customerId = result.Target.Id; var request = new CreditCardRequest { CustomerId = customerId, Number = "5555555555554444", ExpirationDate = "05/2099" }; Result<CreditCard> creditCardResult = gateway.CreditCard.Create(request); Assert.IsTrue(creditCardResult.IsSuccess()); var clientToken = TestHelper.GenerateDecodedClientToken(gateway, new ClientTokenRequest { CustomerId = customerId, Options = new ClientTokenOptionsRequest { MakeDefault = true } } ); var authorizationFingerprint = TestHelper.extractParamFromJson("authorizationFingerprint", clientToken); var builder = new RequestBuilder(""); builder.AddTopLevelElement("authorization_fingerprint", authorizationFingerprint). AddTopLevelElement("shared_customer_identifier_type", "testing"). AddTopLevelElement("shared_customer_identifier", "test-identifier"). AddTopLevelElement("credit_card[number]", "4111111111111111"). AddTopLevelElement("credit_card[expiration_month]", "11"). AddTopLevelElement("credit_card[expiration_year]", "2099"); HttpWebResponse response = new BraintreeTestHttpService().Post(gateway.MerchantId, "v1/payment_methods/credit_cards.json", builder.ToQueryString()); Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); response.Close(); Customer customer = gateway.Customer.Find(customerId); Assert.AreEqual(2, customer.CreditCards.Length); foreach (CreditCard creditCard in customer.CreditCards) { if (creditCard.LastFour == "1111") { Assert.IsTrue(creditCard.IsDefault.Value); } } }
public void FailsInProduction() { var productionGateway = new BraintreeGateway { Environment = Environment.PRODUCTION, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; productionGateway.TestTransaction.Settle("production_transaction_id"); }
public void Generate_ThrowExceptionWhenCustomerNotFound() { var gateway = new BraintreeGateway(); string encodedClientToken = ""; try { encodedClientToken += gateway.ClientToken.Generate( new ClientTokenRequest { CustomerId = "NON_EXISTENT_CUSTOMER_ID" } ); Assert.Fail("Should raise ArgumentException"); } catch (ArgumentException e) { Match match = Regex.Match(e.Message, @"customer_id"); Assert.IsTrue(match.Success); } }