public void ToXml_Includes_FraudMerchantId() { CreditCardRequest request = new CreditCardRequest(); request.FraudMerchantId = "my_fmid"; Assert.IsTrue(request.ToXml().Contains("my_fmid")); }
public void ToXml_Includes_PaymentMethodNonce() { CreditCardRequest request = new CreditCardRequest(); request.PaymentMethodNonce = "my-payment-method-nonce"; Assert.IsTrue(request.ToXml().Contains("my-payment-method-nonce")); }
public void ToXml_Includes_Token() { CreditCardRequest request = new CreditCardRequest(); request.Token = "my-token"; Assert.IsTrue(request.ToXml().Contains("my-token")); }
public void ToXml_Includes_DeviceSessionId() { CreditCardRequest request = new CreditCardRequest(); request.DeviceSessionId = "my_dsid"; Assert.IsTrue(request.ToXml().Contains("my_dsid")); }
public void ToXml_Includes_DeviceData() { CreditCardRequest request = new CreditCardRequest(); request.DeviceData = "{\"device_session_id\":\"my_dsid\", \"fraud_merchant_id\":\"my_fmid\"}"; Assert.IsTrue(request.ToXml().Contains("device-data")); Assert.IsTrue(request.ToXml().Contains("device_session_id")); Assert.IsTrue(request.ToXml().Contains("my_dsid")); Assert.IsTrue(request.ToXml().Contains("fraud_merchant_id")); Assert.IsTrue(request.ToXml().Contains("my_fmid")); }
public void AppendWithRequest() { Request request = new CreditCardRequest { CVV = "123", CardholderName = "Drew" }; string actual = new QueryString().Append("[credit_card]", request).ToString(); Assert.AreEqual("%5bcredit_card%5d%5bcardholder_name%5d=Drew&%5bcredit_card%5d%5bcvv%5d=123", actual); }
public void AppendWithNestedRequest() { Request request = new CreditCardRequest { CVV = "123", CardholderName = "Drew", Options = new CreditCardOptionsRequest { VerifyCard = true, MakeDefault = true } }; string actual = new QueryString().Append("[credit_card]", request).ToString(); Assert.AreEqual("%5bcredit_card%5d%5bcardholder_name%5d=Drew&%5bcredit_card%5d%5bcvv%5d=123&%5bcredit_card%5d%5boptions%5d%5bmake_default%5d=true&%5bcredit_card%5d%5boptions%5d%5bverify_card%5d=true", actual); }
public void Create_CreatesCreditCardWithAVenmoSdkPaymentMethodCode() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, VenmoSdkPaymentMethodCode = SandboxValues.VenmoSdk.VISA_PAYMENT_METHOD_CODE, }; Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest); Assert.IsTrue(result.IsSuccess()); CreditCard creditCard = result.Target; Assert.AreEqual("1111", creditCard.LastFour); Assert.IsTrue(creditCard.IsVenmoSdk.Value); }
public void Create_CreatesCreditCardForGivenCustomerId() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo", BillingAddress = new CreditCardAddressRequest { FirstName = "John", CountryName = "Chad", CountryCodeAlpha2 = "TD", CountryCodeAlpha3 = "TCD", CountryCodeNumeric = "148" } }; CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target; Assert.AreEqual("510510", creditCard.Bin); Assert.AreEqual("5100", creditCard.LastFour); Assert.AreEqual("510510******5100", creditCard.MaskedNumber); Assert.AreEqual("05", creditCard.ExpirationMonth); Assert.AreEqual("2012", creditCard.ExpirationYear); Assert.AreEqual("Michael Angelo", creditCard.CardholderName); Assert.IsTrue(creditCard.IsDefault.Value); Assert.IsFalse(creditCard.IsVenmoSdk.Value); Assert.AreEqual(DateTime.Now.Year, creditCard.CreatedAt.Value.Year); Assert.AreEqual(DateTime.Now.Year, creditCard.UpdatedAt.Value.Year); Assert.IsNotNull(creditCard.ImageUrl); Address billingAddress = creditCard.BillingAddress; Assert.AreEqual("Chad", billingAddress.CountryName); Assert.AreEqual("TD", billingAddress.CountryCodeAlpha2); Assert.AreEqual("TCD", billingAddress.CountryCodeAlpha3); Assert.AreEqual("148", billingAddress.CountryCodeNumeric); Assert.IsTrue(Regex.IsMatch(creditCard.UniqueNumberIdentifier, "\\A\\w{32}\\z")); }
public CreditCardPaymentProcessingResponse CompletePreAuth(CreditCardRequest request, long invoiceNumber) { string cardNumber = request.CardNumber; string swipe = request.CardSwipe; var encryptor = new CreditCardEncryption(); request.CardNumber = encryptor.Encrypt(cardNumber); request.CardSwipe = encryptor.Encrypt(swipe); var returnValue = new CreditCardPaymentProcessingResponse(); try { using (var client = new PaymentServiceClient()) { client.Open(); returnValue = client.CompletePreAuth(request, invoiceNumber); return returnValue; } } finally { request.CardNumber = cardNumber; request.CardSwipe = swipe; returnValue.CardNumber = cardNumber; } }
/// <summary> /// Updates a CreditCard in the DB /// </summary> /// <param name="customerId"> The Id of the Customer the CreditCard belongs to </param> /// <param name="creditCardId"> ID of the CreditCard to update</param> /// <param name="creditCard"> The CreditCard to be updated </param> /// <param name="format"> The data format used (xml/json) </param> /// <returns> A CreditCardResponse object representing the newly-updated CreditCard </returns> public CreditCardResponse UpdateCreditCard(string customerId, string creditCardId, CreditCardRequest creditCard, string format = ContentFormat.XML) { return _service.Put<CreditCardRequest, CreditCardResponse>(string.Format("{0}/{1}/credit-card/{2}.{3}", _gatewayURL, customerId, creditCardId, format), creditCard); }
/// <summary> /// Inserts a new Credit Card in the DB /// </summary> /// <param name="customerId"> The Id of the Customer the new CreditCard will belong to </param> /// <param name="newCreditCard"> The CreditCard to be iserted </param> /// <param name="format"> The desired data format (xml/json) </param> /// <returns> A CreditCardResponse representing the newly-added CreditCard </returns> public CreditCardResponse AddCreditCard(string customerId, CreditCardRequest newCreditCard, string format = ContentFormat.XML) { return _service.Post<CreditCardRequest, CreditCardResponse>(string.Format("{0}/{1}/credit-card.{2}", _gatewayURL, customerId, format), newCreditCard); }
public void Create_CanMakeDefaultAndSetToken() { Result<Customer> customerResult = gateway.Customer.Create(new CustomerRequest()); Assert.IsTrue(customerResult.IsSuccess()); var creditCardRequest = new CreditCardRequest { CustomerId = customerResult.Target.Id, Number = "5105105105105100", ExpirationDate = "05/12" }; CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target; Assert.IsTrue(creditCard.IsDefault.Value); string nonce = TestHelper.GenerateUnlockedNonce(gateway); Random random = new Random(); int randomNumber = random.Next(0, 10000); var token = "token_" + randomNumber; var request = new PaymentMethodRequest { CustomerId = customerResult.Target.Id, PaymentMethodNonce = nonce, Token = token, Options = new PaymentMethodOptionsRequest { MakeDefault = true } }; Result<PaymentMethod> paymentMethodResult = gateway.PaymentMethod.Create(request); Assert.IsTrue(paymentMethodResult.IsSuccess()); Assert.IsTrue(paymentMethodResult.Target.IsDefault.Value); Assert.AreEqual(token, paymentMethodResult.Target.Token); }
public async Task <IActionResult> Index(CheckoutViewModel model) { if (ModelState.IsValid) { Cart cart = null; if (User.Identity.IsAuthenticated) { var currentStoreUser = await _context.Users .Include(x => x.Cart) .ThenInclude(x => x.CartItems) .ThenInclude(x => x.Product) .FirstAsync(x => x.UserName == User.Identity.Name); if (currentStoreUser.Cart != null) { cart = currentStoreUser.Cart; } } else if (Request.Cookies.ContainsKey("CartID")) { if (Guid.TryParse(Request.Cookies["CartID"], out Guid cookieId)) { cart = await _context.Carts .Include(x => x.CartItems) .ThenInclude(x => x.Product) .FirstOrDefaultAsync(x => x.CookieID == cookieId); } } if (cart == null) { ModelState.AddModelError("Cart", "There was a problem with your cart, please check your cart to verify that all items are correct"); } else { if ((User.Identity.IsAuthenticated) && model.CreditCardSave) { //First, check if the customer exists CustomerSearchRequest customerSearchRequest = new CustomerSearchRequest(); customerSearchRequest.Email.Is(User.Identity.Name); Customer customer = null; var customers = await _braintreeGateway.Customer.SearchAsync(customerSearchRequest); if (customers.Ids.Any()) { customer = customers.FirstItem; } else { CustomerRequest newCustomer = new CustomerRequest(); newCustomer.Email = User.Identity.Name; var createResult = await _braintreeGateway.Customer.CreateAsync(newCustomer); if (createResult.IsSuccess()) { customer = createResult.Target; } else { throw new Exception(createResult.Message); } } CreditCardRequest newPaymentMethod = new CreditCardRequest(); newPaymentMethod.CustomerId = customer.Id; newPaymentMethod.Number = model.CreditCardNumber; newPaymentMethod.CVV = model.CreditCardVerificationValue; newPaymentMethod.ExpirationMonth = (model.CreditCardExpirationMonth ?? 0).ToString().PadLeft(2, '0'); newPaymentMethod.ExpirationYear = (model.CreditCardExpirationYear ?? 0).ToString(); var createPaymentResult = await _braintreeGateway.CreditCard.CreateAsync(newPaymentMethod); if (!createPaymentResult.IsSuccess()) { throw new Exception(createPaymentResult.Message); } else { model.SavedCreditCardToken = createPaymentResult.Target.Token; } } Lookup lookup = new Lookup(); lookup.Street = model.ShippingStreet; lookup.City = model.ShippingCity; lookup.State = model.ShippingState; lookup.ZipCode = model.ShippingPostalCode; _streetClient.Send(lookup); if (lookup.Result.Any()) { TransactionRequest braintreeTransaction = new TransactionRequest { Amount = cart.CartItems.Sum(x => x.Quantity * (x.Product.Price ?? 0)), }; if (model.SavedCreditCardToken == null) { braintreeTransaction.CreditCard = new TransactionCreditCardRequest { CVV = model.CreditCardVerificationValue, ExpirationMonth = (model.CreditCardExpirationMonth ?? 0).ToString().PadLeft(2, '0'), ExpirationYear = (model.CreditCardExpirationYear ?? 0).ToString(), Number = model.CreditCardNumber //https://developers.braintreepayments.com/guides/credit-cards/testing-go-live/dotnet }; } else { braintreeTransaction.PaymentMethodToken = model.SavedCreditCardToken; } var transactionResult = await _braintreeGateway.Transaction.SaleAsync(braintreeTransaction); if (transactionResult.IsSuccess()) { // Take the existing cart, and convert the cart and cart items to an "order" with "order items" // - when creating order items, I'm going to "denormalize" the info to copy the price, description, // etc. of what the customer ordered. StoreOrder order = new StoreOrder { ContactEmail = model.ContactEmail, Created = DateTime.UtcNow, FirstName = model.FirstName, LastModified = DateTime.UtcNow, LastName = model.LastName, ShippingCity = model.ShippingCity, ShippingPostalCode = model.ShippingPostalCode, ShippingState = model.ShippingState, ShippingStreet = model.ShippingStreet, StoreOrderItems = cart.CartItems.Select(x => new StoreOrderItem { Created = DateTime.UtcNow, LastModified = DateTime.UtcNow, ProductDescription = x.Product.Description, ProductID = x.Product.ID, ProductName = x.Product.Name, ProductPrice = x.Product.Price, Quantity = x.Quantity }).ToHashSet() }; _context.StoreOrders.Add(order); // Delete the cart, cart items, and clear the cookie or "user cart" info so that the user // will get a new cart next time. _context.Carts.Remove(cart); if (User.Identity.IsAuthenticated) { var currentStoreUser = await _context.Users .Include(x => x.Cart) .ThenInclude(x => x.CartItems) .ThenInclude(x => x.Product) .FirstAsync(x => x.UserName == User.Identity.Name); currentStoreUser.Cart = null; } Response.Cookies.Delete("CartID"); await _context.SaveChangesAsync(); string subject = "Congratulations, order # " + order.ID + " has been placed"; UriBuilder builder = new UriBuilder( Request.Scheme, Request.Host.Host, Request.Host.Port ?? 80, "receipt/index/" + order.ID); string htmlContent = string.Format("<a href=\"{0}\">Check out your order</a>", builder.ToString()); await _emailSender.SendEmailAsync(model.ContactEmail, subject, htmlContent); // Redirect to the receipt page return(RedirectToAction("Index", "Receipt", new { order.ID })); } else { foreach (var transactionError in transactionResult.Errors.All()) { this.ModelState.AddModelError(transactionError.Code.ToString(), transactionError.Message); } } } } } return(View(model)); }
public async Task <IActionResult> Index(CheckoutViewModel model) { await GetCurrentCart(model); if (ModelState.IsValid) { if (!string.IsNullOrEmpty(model.SavedAddressId) || (!string.IsNullOrEmpty(model.ShippingAddressLine1) && !string.IsNullOrEmpty(model.ShippingLocale) && !string.IsNullOrEmpty(model.ShippingRegion) && !string.IsNullOrEmpty(model.ShippingPostalCode) && !string.IsNullOrEmpty(model.ShippingCountry))) { Order newOrder = new Order { TrackingNumber = Guid.NewGuid().ToString(), OrderDate = DateTime.Now, OrderItems = model.Cart.CartItems.Select(x => new OrderItem { ProductID = x.Product.ID, ProductName = x.Product.Name, ProductPrice = (x.Product.Price ?? 0), Quantity = x.Quantity }).ToArray(), AddressLine1 = model.ShippingAddressLine1, AddressLine2 = model.ShippingAddressLine2, Country = model.ShippingCountry, Email = model.ContactEmail, PhoneNumber = model.ContactPhoneNumber, Locale = model.ShippingLocale, PostalCode = model.ShippingPostalCode, Region = model.ShippingRegion }; Braintree.Customer customer = null; Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest(); search.Email.Is(model.ContactEmail); var searchResult = await _brainTreeGateway.Customer.SearchAsync(search); if (searchResult.Ids.Count == 0) { //Create a new Braintree Customer Braintree.Result <Customer> creationResult = await _brainTreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest { Email = model.ContactEmail, Phone = model.ContactPhoneNumber }); customer = creationResult.Target; } else { customer = searchResult.FirstItem; } CreditCard creditCard = null; if (model.SaveBillingCard) { var newCardRequest = new CreditCardRequest { CardholderName = model.BillingNameOnCard, CustomerId = customer.Id, ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'), ExpirationYear = model.BillingCardExpirationYear.ToString(), Number = model.BillingCardNumber, CVV = model.BillingCardVerificationValue }; var newCardResult = await _brainTreeGateway.CreditCard.CreateAsync(newCardRequest); if (newCardResult.IsSuccess()) { creditCard = newCardResult.Target; } } Address savedAddress = null; if (model.SaveShippingAddress) { var newAddressRequest = new AddressRequest { StreetAddress = model.ShippingAddressLine1, ExtendedAddress = model.ShippingAddressLine2, CountryName = model.ShippingCountry, PostalCode = model.ShippingPostalCode, Locality = model.ShippingLocale, Region = model.ShippingRegion }; var newAddressResult = await _brainTreeGateway.Address.CreateAsync(customer.Id, newAddressRequest); if (newAddressResult.IsSuccess()) { savedAddress = newAddressResult.Target; } } else { } TransactionRequest transaction = new TransactionRequest { Amount = model.Cart.CartItems.Sum(x => x.Quantity * (x.Product.Price ?? 0)), CustomerId = customer.Id, LineItems = model.Cart.CartItems.Select(x => new TransactionLineItemRequest { Name = x.Product.Name, Description = x.Product.Description, ProductCode = x.Product.ID.ToString(), Quantity = x.Quantity, LineItemKind = TransactionLineItemKind.DEBIT, UnitAmount = x.Product.Price * x.Quantity, TotalAmount = x.Product.Price * x.Quantity }).ToArray() }; if (creditCard == null) { transaction.CreditCard = new TransactionCreditCardRequest { Number = model.BillingCardNumber, CardholderName = model.BillingNameOnCard, CVV = model.BillingCardVerificationValue, ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'), ExpirationYear = model.BillingCardExpirationYear.ToString() }; } else { transaction.PaymentMethodToken = creditCard.Token; } if (savedAddress != null) { transaction.ShippingAddressId = savedAddress.Id; } var transactionResult = await _brainTreeGateway.Transaction.SaleAsync(transaction); if (transactionResult.IsSuccess()) { _thisSiteDbContext.Orders.Add(newOrder); _thisSiteDbContext.CartItems.RemoveRange(model.Cart.CartItems); _thisSiteDbContext.Carts.Remove(model.Cart); await _thisSiteDbContext.SaveChangesAsync(); //Try to checkout //Confirmation Email //TODO: var serOrder serializes user order. I want to parse this JSON and send to SendGrid template for custom receipt /*var serOrder = JsonConvert.SerializeObject(newOrder, Formatting.Indented, * new JsonSerializerSettings * { * ReferenceLoopHandling = ReferenceLoopHandling.Ignore * }); */ var user = model.ContactEmail; var orderCompleteSubject = "Order #" + newOrder.TrackingNumber + " Completed"; var htmlContent = "Thanks for placing your order with us! Please reference your order number above."; var plainTextContent = "Thanks for placing your order with us! Please reference your order number above."; var emailResult = await _emailService.SendEmailAsync(user, orderCompleteSubject, htmlContent, plainTextContent); //await _emailService.SendEmailAsync(user, orderCompleteSubject, htmlContent, plainTextContent); if (!emailResult.Success) { throw new Exception(string.Join(',', emailResult.Errors.Select(x => x.Message))); } Response.Cookies.Delete("cartId"); return(RedirectToAction("Index", "Receipt", new { id = newOrder.TrackingNumber })); } for (int i = 0; i < transactionResult.Errors.Count; i++) { ModelState.AddModelError("BillingCardNumber" + i, transactionResult.Errors.All()[i].Message); } } } return(View(model)); }
public void Generate_GatewayRespectsMakeDefault() { 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 = "5105105105105100", 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); 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()); 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 UpdateCreditCardFromTransparentRedirect() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5555555555554444", ExpirationDate = "05/22", CardholderName = "Beverly D'angelo" }; CreditCard createdCreditCard = gateway.CreditCard.Create(creditCardRequest).Target; CreditCardRequest trParams = new CreditCardRequest { PaymentMethodToken = createdCreditCard.Token, Number = "4111111111111111", ExpirationDate = "10/10" }; CreditCardRequest request = new CreditCardRequest { CardholderName = "Sampsonite" }; string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service); Result<CreditCard> result = gateway.TransparentRedirect.ConfirmCreditCard(queryString); Assert.IsTrue(result.IsSuccess()); CreditCard creditCard = gateway.CreditCard.Find(createdCreditCard.Token); Assert.AreEqual("Sampsonite", creditCard.CardholderName); Assert.AreEqual("411111", creditCard.Bin); Assert.AreEqual("1111", creditCard.LastFour); Assert.AreEqual("10/2010", creditCard.ExpirationDate); }
public CustomerResponse CreateCustomer(CreditCardRequest card = null, string coupon = null, string email = null, string description = null, string plan = null, DateTimeOffset?trialEnd = null) { if (card != null) { Require.Argument("card[number]", card.Number); Require.Argument("card[exp_month]", card.ExpMonth); Require.Argument("card[exp_year]", card.ExpYear); } var request = new RestRequest(); request.Method = Method.POST; request.Resource = "customers"; if (card != null) { request.AddParameter("card[number]", card.Number); request.AddParameter("card[exp_month]", card.ExpMonth); request.AddParameter("card[exp_year]", card.ExpYear); if (card.Cvc.HasValue()) { request.AddParameter("card[cvc]", card.ExpYear); } if (card.Name.HasValue()) { request.AddParameter("card[name]", card.ExpYear); } if (card.AddressLine1.HasValue()) { request.AddParameter("card[address_line1]", card.ExpYear); } if (card.AddressLine2.HasValue()) { request.AddParameter("card[address_line2]", card.ExpYear); } if (card.AddressZip.HasValue()) { request.AddParameter("card[address_zip]", card.ExpYear); } if (card.AddressState.HasValue()) { request.AddParameter("card[address_state]", card.ExpYear); } if (card.AddressCountry.HasValue()) { request.AddParameter("card[address_country]", card.ExpYear); } } if (coupon.HasValue()) { request.AddParameter("coupon", coupon); } if (email.HasValue()) { request.AddParameter("email", email); } if (description.HasValue()) { request.AddParameter("description", description); } if (plan.HasValue()) { request.AddParameter("plan", plan); } if (trialEnd.HasValue) { request.AddParameter("trialEnd", trialEnd.Value.ToUnixEpoch()); } return(Execute <CustomerResponse>(request)); }
public void VerifyValidCreditCardWithVerificationRiskData() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "4111111111111111", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsTrue(result.IsSuccess()); CreditCard card = result.Target; CreditCardVerification verification = card.Verification; Assert.IsNotNull(verification); Assert.IsNotNull(verification.RiskData); }
public void CheckDuplicateCreditCard() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "4111111111111111", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { FailOnDuplicatePaymentMethod = true } }; gateway.CreditCard.Create(request); Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsFalse(result.IsSuccess()); Assert.AreEqual( ValidationErrorCode.CREDIT_CARD_DUPLICATE_CARD_EXISTS, result.Errors.ForObject("CreditCard").OnField("Number")[0].Code ); }
public void Delete_DeletesTheCreditCard() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, Number = "5105105105105100", ExpirationDate = "05/12", CVV = "123", CardholderName = "Michael Angelo" }; CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target; Assert.AreEqual(creditCard.Token, gateway.CreditCard.Find(creditCard.Token).Token); gateway.CreditCard.Delete(creditCard.Token); Assert.Throws<NotFoundException>(() => gateway.CreditCard.Find(creditCard.Token)); }
public PayPros Initiate(PayPros payment, string cardNumber) { #region CREATE REQUEST CreditCardRequest request = new CreditCardRequest(); try { request.setCreditCardNumber(cardNumber); if (!string.IsNullOrEmpty(payment.CCV)) { request.setCreditCardVerificationNumber(payment.CCV); } request.setExpireMonth(payment.CCExpireMonth); request.setExpireYear(payment.CCExpireYear); request.setChargeType(CreditCardRequest.SALE); request.setPurchaseOrderNumber(payment.PaymentAccount); request.setChargeTotal((double)payment.PaymentAmount); request.setPartialApprovalFlag(false); if (!string.IsNullOrEmpty(payment.RequestingOrigin)) { request.setCustomerIpAddress(payment.RequestingOrigin); } switch (_account) { case PaymentAccounts.UBO: request.setIndustry("DIRECT_MARKETING"); break; case PaymentAccounts.Judicial: break; default: break; } switch (_method) { case PaymentMethods.Web: request.setTransactionConditionCode(5); break; case PaymentMethods.Phone: request.setTransactionConditionCode(2); break; default: break; } } catch (Exception) { throw new ArgumentException("Unable to create request"); } #endregion #region PROCESS REQUEST string payprosToken = (payment.IsTest ? testTokens[_account] : accountTokens[_account]); CreditCardResponse response = (CreditCardResponse)TransactionClient.doTransaction(request, payprosToken); payment.responseCode = (payment.IsTest ? (-1 * response.getResponseCode()) : response.getResponseCode());//flip sign of response code for test payments (keeps it from being written for processing) payment.responseText = response.getResponseCodeText(); payment.retryRecommended = response.getRetryRecommended(); payment.timestamp = response.getTimeStamp(); #endregion #region RECORD RESPONSE double authorizedAmount = 0; if (double.TryParse(response.getAuthorizedAmount(), out authorizedAmount)) { payment.PaymentAmount = (decimal)authorizedAmount; } long orderID; if (long.TryParse(response.getOrderId(), out orderID)) { payment.orderID = orderID; } long batchID; if (long.TryParse(response.getBatchId(), out batchID)) { payment.batchID = batchID; } long bankApprovalCode; if (long.TryParse(response.getBankApprovalCode(), out bankApprovalCode)) { payment.bankApprovalCode = bankApprovalCode; } long bankTransactionId; if (long.TryParse(response.getBankTransactionId(), out bankTransactionId)) { payment.bankTransactionId = bankTransactionId; } int creditCardVerification; if (int.TryParse(response.getCreditCardVerificationResponse(), out creditCardVerification)) { payment.creditCardVerificationResponse = creditCardVerification; } #endregion return(payment); }
/// <summary> /// Updates a CreditCard in the DB /// </summary> /// <param name="siteSubdomanin">Subdomain of the Site where the Customer is registered</param> /// <param name="customerReferenceId">The RefereceId of the Customer the CreditCard belongs to</param> /// <param name="creditCardId"> ID of the CreditCard to update</param> /// <param name="creditCard"> The CreditCard to be updated </param> /// <param name="format"> The data format used (xml/json) </param> /// <returns> A CreditCardResponse object representing the newly-updated CreditCard </returns> public CreditCardResponse UpdateCreditCardByCustomerReferenceId(string siteSubdomanin, string customerReferenceId, string creditCardId, CreditCardRequest creditCard, string format = ContentFormat.XML) { return _service.Put<CreditCardRequest, CreditCardResponse>(string.Format("{0}/{1}/reference-id/{2}/credit-card/{3}.{4}", _gatewayURL, siteSubdomanin, customerReferenceId, creditCardId, format), creditCard); }
public void CreateCreditCardFromTransparentRedirect() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest trParams = new CreditCardRequest { CustomerId = customer.Id, Number = "4111111111111111", ExpirationDate = "10/10" }; CreditCardRequest request = new CreditCardRequest { CardholderName = "John Doe" }; string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service); Result<CreditCard> result = gateway.TransparentRedirect.ConfirmCreditCard(queryString); Assert.IsTrue(result.IsSuccess()); CreditCard creditCard = result.Target; Assert.AreEqual("John Doe", creditCard.CardholderName); Assert.AreEqual("411111", creditCard.Bin); Assert.AreEqual("1111", creditCard.LastFour); Assert.AreEqual("10/2010", creditCard.ExpirationDate); }
public ActionResult Register(RegisterModel model) { string message = ""; if (ModelState.IsValid) { // Attempt to register the user MembershipCreateStatus createStatus; Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus); //if the registration process was successful, //add the newly registered user to your Customers and subscribe him to the Selected Plan if (createStatus == MembershipCreateStatus.Success) { FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false); try { //get your Site data through Billing Gateway var mySite = _dynabicBillingGateway.Sites.GetSiteBySubdomain(Config.MySiteSubdomain); //get the selected plan var selectedPlan = _dynabicBillingGateway.Products.GetProductById(model.Plans.SelectedPlan.ToString()); //generate a random Customer Reference Id //CustomerReferenceId does not permit the usage of any other special characters except "-" and //it isn't allowed to begin or end with this character nor it can be consecutive Random r = new Random(); long value = (long)((r.NextDouble() * 2.0 - 1.0) * long.MaxValue); string newCustomerReferenceId = string.Format("{0}-{1}", mySite.Id, Math.Abs(value)); //create a new CustomerRequest CustomerRequest newCustomer = new CustomerRequest() { //this fields are required FirstName = model.UserName, LastName = model.UserName, Email = model.Email, ReferenceId = newCustomerReferenceId }; //create a new Subscription Request SubscriptionRequest newSubscription = new SubscriptionRequest() { Customer = newCustomer, ProductId = selectedPlan.Id, ProductPricingPlanId = selectedPlan.PricingPlans[0].Id, }; //if the Credit Card is required at Signup //create a new Credit Card Request and add it to your Subscription //isCreditCardAtSignupRequired may be "No", "Yes", "YesOptional" if (selectedPlan.isCreditCardAtSignupRequired != BoolOptional.No) { CreditCardRequest newCreditCard = new CreditCardRequest() { Cvv = model.CreditCard.Cvv, ExpirationDate = model.CreditCard.ExpirationDate, FirstNameOnCard = model.CreditCard.FirstNameOnCard, LastNameOnCard = model.CreditCard.LastNameOnCard, Number = model.CreditCard.Number }; newSubscription.CreditCard = newCreditCard; } //if the Billing Address is required at Signup //create a new Billing Address Request and add it to your Subscription //isBillingAddressAtSignupRequired may be "No", "Yes", "YesOptional" if (selectedPlan.isBillingAddressAtSignupRequired != BoolOptional.No) { AddressRequest billingAddress = new AddressRequest() { Address1 = model.BillingAddress.BillingAddress1, City = model.BillingAddress.BillingCity, Country = model.BillingAddress.BillingCountry, StateProvince = model.BillingAddress.BillingProvince, ZipPostalCode = model.BillingAddress.BillingZipPostalCode, FirstName = model.BillingAddress.BillingFirstName, LastName = model.BillingAddress.BillingLastName }; newSubscription.BillingAddress = billingAddress; } //subscribe the newly created Customer to selected Plan _dynabicBillingGateway.Subscription.AddSubscription(mySite.Subdomain, newSubscription); //create a User Profile and save some data that we may need later ProfileCommon profile = ProfileCommon.GetUserProfile(model.UserName); profile.CurrentPlanId = model.Plans.SelectedPlan; profile.CustomerReferenceId = newCustomerReferenceId; //redirect to Home page return RedirectToAction("Index", "Home"); } catch (Exception) { message = "Something went wrong. Please try again later."; } } else { message = ErrorCodeToString(createStatus); } } //provide an error message in case something went wrong model.PageMessage = new PageMessageModel { Type = PageMessageModel.MessageType.Error, Message = message }; model.Plans.MyPlans = model.Plans.GetAllPlans(_dynabicBillingGateway); // If we got this far, something failed, redisplay form return View(model); }
public CustomerSubscriptionResponse UpdateCustomersSubscription(string customerId, string planId, string coupon = null, bool?prorate = null, DateTimeOffset?trialEnd = null, CreditCardRequest card = null) { Require.Argument("customerId", customerId); Require.Argument("planId", planId); if (card != null) { Require.Argument("card[number]", card.Number); Require.Argument("card[exp_month]", card.ExpMonth); Require.Argument("card[exp_year]", card.ExpYear); } var request = new RestRequest(); request.Method = Method.POST; request.Resource = "customers/{customerId}/subscription"; request.AddUrlSegment("customerId", customerId); request.AddParameter("plan", planId); if (coupon.HasValue()) { request.AddParameter("coupon", coupon); } if (prorate.HasValue) { request.AddParameter("prorate", prorate.Value); } if (trialEnd.HasValue) { request.AddParameter("trial_end", trialEnd.Value.ToUnixEpoch()); } if (card != null) { request.AddParameter("card[number]", card.Number); request.AddParameter("card[exp_month]", card.ExpMonth); request.AddParameter("card[exp_year]", card.ExpYear); if (card.Cvc.HasValue()) { request.AddParameter("card[cvc]", card.ExpYear); } if (card.Name.HasValue()) { request.AddParameter("card[name]", card.ExpYear); } if (card.AddressLine1.HasValue()) { request.AddParameter("card[address_line1]", card.ExpYear); } if (card.AddressLine2.HasValue()) { request.AddParameter("card[address_line2]", card.ExpYear); } if (card.AddressZip.HasValue()) { request.AddParameter("card[address_zip]", card.ExpYear); } if (card.AddressState.HasValue()) { request.AddParameter("card[address_state]", card.ExpYear); } if (card.AddressCountry.HasValue()) { request.AddParameter("card[address_country]", card.ExpYear); } } return(Execute <CustomerSubscriptionResponse>(request)); }
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 override Task <DefaultResponse> AddCreditCard(CreditCardRequest request, ServerCallContext context) { return(base.AddCreditCard(request, context)); }
public void Search_FindDuplicateCardsGivenPaymentMethodToken() { CreditCardRequest creditCard = new CreditCardRequest { Number = "4111111111111111", ExpirationDate = "05/2012" }; CustomerRequest jimRequest = new CustomerRequest { FirstName = "Jim", CreditCard = creditCard }; CustomerRequest joeRequest = new CustomerRequest { FirstName = "Jim", CreditCard = creditCard }; Customer jim = gateway.Customer.Create(jimRequest).Target; Customer joe = gateway.Customer.Create(joeRequest).Target; CustomerSearchRequest searchRequest = new CustomerSearchRequest(). PaymentMethodTokenWithDuplicates.Is(jim.CreditCards[0].Token); ResourceCollection<Customer> collection = gateway.Customer.Search(searchRequest); List<string> customerIds = new List<string>(); foreach (Customer customer in collection) { customerIds.Add(customer.Id); } Assert.IsTrue(customerIds.Contains(jim.Id)); Assert.IsTrue(customerIds.Contains(joe.Id)); }
public void VerifyValidCreditCardWithVerificationAmount() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "4111111111111111", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true, VerificationAmount = "1.02" } }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsTrue(result.IsSuccess()); }
public CustomerResponse UpdateCustomer(string customerId, CreditCardRequest card = null, string coupon = null, string email = null, string description = null) { if (card != null) { Require.Argument("card[number]", card.Number); Require.Argument("card[exp_month]", card.ExpMonth); Require.Argument("card[exp_year]", card.ExpYear); } var request = new RestRequest(); request.Method = Method.POST; request.Resource = "customers/{customerId}"; request.AddUrlSegment("customerId", customerId); if (card != null) { request.AddParameter("card[number]", card.Number); request.AddParameter("card[exp_month]", card.ExpMonth); request.AddParameter("card[exp_year]", card.ExpYear); if (card.Cvc.HasValue()) { request.AddParameter("card[cvc]", card.ExpYear); } if (card.Name.HasValue()) { request.AddParameter("card[name]", card.ExpYear); } if (card.AddressLine1.HasValue()) { request.AddParameter("card[address_line1]", card.ExpYear); } if (card.AddressLine2.HasValue()) { request.AddParameter("card[address_line2]", card.ExpYear); } if (card.AddressZip.HasValue()) { request.AddParameter("card[address_zip]", card.ExpYear); } if (card.AddressState.HasValue()) { request.AddParameter("card[address_state]", card.ExpYear); } if (card.AddressCountry.HasValue()) { request.AddParameter("card[address_country]", card.ExpYear); } } if (coupon.HasValue()) { request.AddParameter("coupon", coupon); } if (email.HasValue()) { request.AddParameter("email", email); } if (description.HasValue()) { request.AddParameter("description", description); } return(Execute <CustomerResponse>(request)); }
public void VerifyValidCreditCardSpecifyingMerhantAccount() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "5105105105105100", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true, VerificationMerchantAccountId = MerchantAccountIDs.NON_DEFAULT_MERCHANT_ACCOUNT_ID } }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsFalse(result.IsSuccess()); Assert.AreEqual(MerchantAccountIDs.NON_DEFAULT_MERCHANT_ACCOUNT_ID, result.CreditCardVerification.MerchantAccountId); }
public void Create_CreatesCreditCardWithSecurityParams() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; var creditCardRequest = new CreditCardRequest { CustomerId = customer.Id, DeviceSessionId = "abc123", FraudMerchantId = "7", CardholderName = "John Doe", Number = "5105105105105100", ExpirationDate = "05/12", BillingAddress = new CreditCardAddressRequest { CountryName = "Greece", CountryCodeAlpha2 = "GR", CountryCodeAlpha3 = "GRC", CountryCodeNumeric = "300" } }; Result<CreditCard> result = gateway.CreditCard.Create(creditCardRequest); Assert.IsTrue(result.IsSuccess()); }
public ActionResult PaymentInfo(PaymentInfoModel model, string cancel) { if (cancel != null) { return (RedirectToAction("Index", "Home")); } else { if (ModelState.IsValid) { try { //Credit Card CreditCardRequest creditCard = new CreditCardRequest() { Cvv = model.CreditCard.Cvv, ExpirationDate = model.CreditCard.ExpirationDate, FirstNameOnCard = model.CreditCard.FirstNameOnCard, LastNameOnCard = model.CreditCard.LastNameOnCard, Number = model.CreditCard.Number }; //Billing Address AddressRequest billingAddress = new AddressRequest() { Address1 = model.BillingAddress.BillingAddress1, City = model.BillingAddress.BillingCity, Country = model.BillingAddress.BillingCountry, FirstName = model.BillingAddress.BillingFirstName, LastName = model.BillingAddress.BillingLastName, StateProvince = model.BillingAddress.BillingProvince, ZipPostalCode = model.BillingAddress.BillingZipPostalCode }; ProfileCommon profile = ProfileCommon.GetUserProfile(User.Identity.Name); // add or update the Credit card if (model.CreditCard.Id <= 0) { var customer = _dynabicBillingGateway.Customer.GetCustomerByReferenceId(Config.MySiteSubdomain, profile.CustomerReferenceId); _dynabicBillingGateway.Customer.AddCreditCard(customer.Id.ToString(), creditCard); } else { _dynabicBillingGateway.Customer.UpdateCreditCardByCustomerReferenceId(Config.MySiteSubdomain, profile.CustomerReferenceId, model.CreditCard.Id.ToString(), creditCard); } // add or update the Billing Address if (model.BillingAddress.BillingAddressId <= 0) { var customer = _dynabicBillingGateway.Customer.GetCustomerByReferenceId(Config.MySiteSubdomain, profile.CustomerReferenceId); _dynabicBillingGateway.Customer.AddBillingAddress(customer.Id.ToString(), billingAddress); } else { _dynabicBillingGateway.Customer.UpdateBillingAddressByCustomerReferenceId(Config.MySiteSubdomain, profile.CustomerReferenceId, model.BillingAddress.BillingAddressId.ToString(), billingAddress); } //set the Success message TempData["PageMessage"] = new PageMessageModel { Type = PageMessageModel.MessageType.Success, Message = "Your Payment details have been updated successfully." }; return RedirectToAction("PaymentInfo", "Account"); } catch { //provide an error message in case something went wrong model.PageMessage = new PageMessageModel { Type = PageMessageModel.MessageType.Error, Message = "Something went wrong. Please try again later." }; } } } if (model.PageMessage == null) model.PageMessage = new PageMessageModel(); // If we got this far, something failed, redisplay form return View(model); }
public void VerifyInvalidCreditCard() { Customer customer = gateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "123", Number = "5105105105105100", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; Result<CreditCard> result = gateway.CreditCard.Create(request); Assert.IsFalse(result.IsSuccess()); CreditCardVerification verification = result.CreditCardVerification; Assert.AreEqual(VerificationStatus.PROCESSOR_DECLINED, verification.Status); Assert.IsNull(verification.GatewayRejectionReason); }
/// <summary> /// Creates a new <see cref="CreditCardRequest"/> /// </summary> /// <param name="paymentMethodNonce"> /// The "nonce-from-the-client" /// </param> /// <param name="optionsRequest"> /// The options request. /// </param> /// <param name="billingAddress">The billing address associated with the credit card</param> /// <param name="isUpdate">A value indicating whether or not this is an update request</param> /// <returns> /// The <see cref="CreditCardRequest"/>. /// </returns> public CreditCardRequest CreateCreditCardRequest(string paymentMethodNonce, CreditCardOptionsRequest optionsRequest, IAddress billingAddress = null, bool isUpdate = false) { Mandate.ParameterNotNullOrEmpty(paymentMethodNonce, "paymentMethodNonce"); var request = new CreditCardRequest() { PaymentMethodNonce = paymentMethodNonce }; if (optionsRequest != null) request.Options = optionsRequest; if (billingAddress != null) request.BillingAddress = this.CreateCreditCardAddressRequest(billingAddress, isUpdate); return request; }
public void GatewayRejectionReason_ExposedOnVerification() { BraintreeGateway processingRulesGateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "processing_rules_merchant_id", PublicKey = "processing_rules_public_key", PrivateKey = "processing_rules_private_key" }; Customer customer = processingRulesGateway.Customer.Create(new CustomerRequest()).Target; CreditCardRequest request = new CreditCardRequest { CustomerId = customer.Id, CardholderName = "John Doe", CVV = "200", Number = "4111111111111111", ExpirationDate = "05/12", Options = new CreditCardOptionsRequest { VerifyCard = true } }; Result<CreditCard> result = processingRulesGateway.CreditCard.Create(request); Assert.IsFalse(result.IsSuccess()); CreditCardVerification verification = result.CreditCardVerification; Assert.AreEqual(TransactionGatewayRejectionReason.CVV, verification.GatewayRejectionReason); }
public void Update_CanMakeDefault() { Result<Customer> customerResult = gateway.Customer.Create(new CustomerRequest()); Assert.IsTrue(customerResult.IsSuccess()); var creditCardRequest = new CreditCardRequest { CustomerId = customerResult.Target.Id, Number = "5555555555554444", ExpirationDate = "05/22" }; CreditCard creditCard = gateway.CreditCard.Create(creditCardRequest).Target; Assert.IsTrue(creditCard.IsDefault.Value); var request = new PaymentMethodRequest { CustomerId = customerResult.Target.Id, PaymentMethodNonce = Nonce.PayPalFuturePayment }; Result<PaymentMethod> result = gateway.PaymentMethod.Create(request); Assert.IsTrue(result.IsSuccess()); var updateRequest = new PayPalAccountRequest { Options = new PayPalOptionsRequest { MakeDefault = true } }; var updateResult = gateway.PayPalAccount.Update(result.Target.Token, updateRequest); Assert.IsTrue(updateResult.IsSuccess()); Assert.IsTrue(updateResult.Target.IsDefault.Value); }
public async Task <IActionResult> Index(CheckoutViewModel model) { await GetCurrentCart(model); if (ModelState.IsValid) { if (!string.IsNullOrEmpty(model.SavedAddressId) || (!string.IsNullOrEmpty(model.ShippingAddressLine1) && !string.IsNullOrEmpty(model.ShippingLocale) && !string.IsNullOrEmpty(model.ShippingRegion) && !string.IsNullOrEmpty(model.ShippingPostalCode) && !string.IsNullOrEmpty(model.ShippingCountry))) { Order newOrder = new Order { TrackingNumber = Guid.NewGuid().ToString(), OrderDate = DateTime.Now, OrderItems = model.Cart.CartItems.Select(x => new OrderItem { ProductID = x.Product.ID, ProductName = x.Product.Name, ProductPrice = (x.Product.Price ?? 0), Quantity = x.Quantity }).ToArray(), AddressLine1 = model.ShippingAddressLine1, AddressLine2 = model.ShippingAddressLine2, Country = model.ShippingCountry, Email = model.ContactEmail, PhoneNumber = model.ContactPhoneNumber, Locale = model.ShippingLocale, PostalCode = model.ShippingPostalCode, Region = model.ShippingRegion }; Braintree.Customer customer = null; Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest(); search.Email.Is(model.ContactEmail); var searchResult = await _brainTreeGateway.Customer.SearchAsync(search); if (searchResult.Ids.Count == 0) { //Create a new Braintree Customer Braintree.Result <Customer> creationResult = await _brainTreeGateway.Customer.CreateAsync(new Braintree.CustomerRequest { Email = model.ContactEmail, Phone = model.ContactPhoneNumber }); customer = creationResult.Target; } else { customer = searchResult.FirstItem; } CreditCard creditCard = null; if (model.SaveBillingCard) { var newCardRequest = new CreditCardRequest { CardholderName = model.BillingNameOnCard, CustomerId = customer.Id, ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'), ExpirationYear = model.BillingCardExpirationYear.ToString(), Number = model.BillingCardNumber, CVV = model.BillingCardVerificationValue }; var newCardResult = await _brainTreeGateway.CreditCard.CreateAsync(newCardRequest); if (newCardResult.IsSuccess()) { creditCard = newCardResult.Target; } } Address savedAddress = null; if (model.SaveShippingAddress) { var newAddressRequest = new AddressRequest { StreetAddress = model.ShippingAddressLine1, ExtendedAddress = model.ShippingAddressLine2, CountryName = model.ShippingCountry, PostalCode = model.ShippingPostalCode, Locality = model.ShippingLocale, Region = model.ShippingRegion }; var newAddressResult = await _brainTreeGateway.Address.CreateAsync(customer.Id, newAddressRequest); if (newAddressResult.IsSuccess()) { savedAddress = newAddressResult.Target; } } //More on card testing: https://developers.braintreepayments.com/reference/general/testing/dotnet TransactionRequest transaction = new TransactionRequest { //Amount = 1, Amount = model.Cart.CartItems.Sum(x => x.Quantity * (x.Product.Price ?? 0)), CustomerId = customer.Id, LineItems = model.Cart.CartItems.Select(x => new TransactionLineItemRequest { Name = x.Product.Name, Description = x.Product.Description, ProductCode = x.Product.ID.ToString(), Quantity = x.Quantity, LineItemKind = TransactionLineItemKind.DEBIT, UnitAmount = x.Product.Price * x.Quantity, TotalAmount = x.Product.Price * x.Quantity }).ToArray() }; if (creditCard == null) { transaction.CreditCard = new TransactionCreditCardRequest { Number = model.BillingCardNumber, CardholderName = model.BillingNameOnCard, CVV = model.BillingCardVerificationValue, ExpirationMonth = model.BillingCardExpirationMonth.ToString().PadLeft(2, '0'), ExpirationYear = model.BillingCardExpirationYear.ToString() }; } else { transaction.PaymentMethodToken = creditCard.Token; } if (savedAddress != null) { transaction.ShippingAddressId = savedAddress.Id; } var transactionResult = await _brainTreeGateway.Transaction.SaleAsync(transaction); if (transactionResult.IsSuccess()) { _countryClubDbContext.Orders.Add(newOrder); _countryClubDbContext.CartItems.RemoveRange(model.Cart.CartItems); _countryClubDbContext.Carts.Remove(model.Cart); await _countryClubDbContext.SaveChangesAsync(); //Send email after purchase button is hit. Sends email first before moving onto the reciept page view //Try to checkout Response.Cookies.Delete("cartId"); return(RedirectToAction("Index", "Receipt", new { id = newOrder.TrackingNumber })); } for (int i = 0; i < transactionResult.Errors.Count; i++) { ModelState.AddModelError("BillingCardNumber" + i, transactionResult.Errors.All()[i].Message); } } } return(View(model)); }