A class for building requests to manipulate Customer records in the vault.
Inheritance: Braintree.Request
        public ActionResult CreateCustomer(FormCollection collection)
        {
            CustomerRequest request = new CustomerRequest
            {
                FirstName = collection["first_name"],
                LastName = collection["last_name"],
                CreditCard = new CreditCardRequest
                {
                    BillingAddress = new CreditCardAddressRequest
                    {
                        PostalCode = collection["postal_code"]
                    },
                    Number = collection["number"],
                    ExpirationMonth = collection["month"],
                    ExpirationYear = collection["year"],
                    CVV = collection["cvv"]
                }
            };

            Result<Customer> result = Constants.Gateway.Customer.Create(request);
            if (result.IsSuccess())
            {
                Customer customer = result.Target;
                ViewData["CustomerName"] = customer.FirstName + " " + customer.LastName;
                ViewData["CustomerId"] = customer.Id;
            }
            else
            {
                ViewData["Message"] = result.Message;
            }

            return View();
        }
        public void Customer()
        {
            CustomerRequest request = new CustomerRequest
            {
                PaymentMethodNonce = Nonce.Coinbase
            };
            Result<Customer> customerResult = gateway.Customer.Create(request);
            Assert.IsTrue(customerResult.IsSuccess());


            var customer = gateway.Customer.Find(customerResult.Target.Id);
            Assert.AreEqual(1, customer.CoinbaseAccounts.Length);

            CoinbaseAccount account = customer.CoinbaseAccounts[0];

            Assert.AreNotEqual("", account.UserEmail);
            Assert.IsNotNull(account.UserEmail);

            Assert.AreNotEqual("", account.UserName);
            Assert.IsNotNull(account.UserName);

            Assert.AreNotEqual("", account.UserId);
            Assert.IsNotNull(account.UserId);

            Assert.AreEqual(1, customer.PaymentMethods.Length);
            Assert.AreEqual(customer.PaymentMethods[0], customer.CoinbaseAccounts[0]);
        }
Esempio n. 3
0
        private void GetSavedPayMethodInfo(string paymentNonce, out string customerId, out string token, out string type) {
            using(var ctx = new Data.FitathonDataEntities()) {
                var user = Common.GetUserFromEmail(ctx, Context.User.Identity.Name);
                var sponsor = user.sponsors.SingleOrDefault();
                var evt = sponsor.participant.fitevent;

                var gateway = new Braintree.BraintreeGateway {
                    Environment = Braintree.Environment.SANDBOX,
                    MerchantId = evt.braintreeClientID,
                    PublicKey = evt.braintreePublicKey,
                    PrivateKey = evt.braintreePrivateKey
                };

                //create request with just the payment nonce (empty customer)
                var custRequest = new Braintree.CustomerRequest {
                    PaymentMethodNonce = paymentNonce
                };
                Braintree.Result<Braintree.Customer> custResult = gateway.Customer.Create(custRequest);

                if(custResult.IsSuccess()) {
                    Braintree.Customer customer = custResult.Target;
                    customerId = customer.Id;
                    token = customer.PaymentMethods[0].Token;
                    type = GetPMType(customer.PaymentMethods[0]);
                    return;
                }
            }
            customerId = null;
            token = null;
            type = null;
        }
Esempio n. 4
0
        public Customer UpdateCustomer(string firstName, string lastName, string id)
        {
            Braintree.CustomerRequest request = new Braintree.CustomerRequest();
            request.FirstName = firstName;
            request.LastName  = lastName;
            var result = gateway.Customer.Update(id, request);

            return(result.Target);
        }
        public async Task <Customer> UpdateCustomerAsync(string firstName, string lastName, string id)
        {
            Braintree.CustomerRequest request = new Braintree.CustomerRequest();
            request.FirstName = firstName;
            request.LastName  = lastName;
            var result = await gateway.Customer.UpdateAsync(id, request);

            return(result.Target);
        }
        public void ToXml_Includes_DeviceSessionId()
        {
            var request = new CustomerRequest()
            {
                CreditCard = new CreditCardRequest()
                {
                    DeviceSessionId = "my_dsid",
                    FraudMerchantId = "my_fmid"
                }
            };

            Assert.IsTrue(request.ToXml().Contains("my_dsid"));
            Assert.IsTrue(request.ToXml().Contains("my_fmid"));
        }
        public void ToXml_Includes_DeviceData()
        {
            var request = new CustomerRequest()
            {
                CreditCard = new CreditCardRequest()
                {
                    DeviceData = "{\"device_session_id\":\"my_dsid\", \"fraud_merchant_id\":\"my_fmid\"}"
                }
            };

            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 ActionResult Create(CustomerRequest customerRequest)
        {
            if (ModelState.IsValid)
            {
                var result = gateway.Customer.Create(customerRequest);
                if (result.IsSuccess())
                {
                    TempData["success"] = "New customer saved successfully";
                    return RedirectToAction("Index");
                }
                else
                {
                    TempData["error"] = "Failed to save new customer. Message: " + result.Message;
                }
            }

            return View(customerRequest);
        }
        public void Find_RaisesNotFoundErrorForCreditCardToken()
        {
            var createRequest = new CustomerRequest
            {
                CreditCard = new CreditCardRequest
                {
                    Number = "5105105105105100",
                    ExpirationDate = "05/12",
                    CVV = "123",
                }
            };

            Customer customer = gateway.Customer.Create(createRequest).Target;

            try {
                gateway.PayPalAccount.Find(customer.CreditCards[0].Token);
                Assert.Fail("Should throw NotFoundException");
            } catch (NotFoundException) {}
        }
Esempio n. 10
0
        // GET: Checkout
        public ActionResult Index()
        {
            CheckoutDetails details = new CheckoutDetails();
            Guid            cartId  = Guid.Parse(Request.Cookies["cartId"].Value);

            details.CurrentCart = db.Carts.Find(cartId);

            details.Addresses = new Braintree.Address[0];

            if (User.Identity.IsAuthenticated)
            {
                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"];
                Braintree.BraintreeGateway gateway = new Braintree.BraintreeGateway(environment, merchantId, publicKey, privateKey);

                var customerGateway = gateway.Customer;

                Braintree.CustomerSearchRequest query = new Braintree.CustomerSearchRequest();
                query.Email.Is(User.Identity.Name);
                var matchedCustomers        = customerGateway.Search(query);
                Braintree.Customer customer = null;
                if (matchedCustomers.Ids.Count == 0)
                {
                    Braintree.CustomerRequest newCustomer = new Braintree.CustomerRequest();
                    newCustomer.Email = User.Identity.Name;

                    var result = customerGateway.Create(newCustomer);
                    customer = result.Target;
                }
                else
                {
                    customer = matchedCustomers.FirstItem;
                }

                details.Addresses = customer.Addresses;
            }

            return(View(details));
        }
        public NewCustomerResultSM CreateCustomer(NewPaymentCustomerSM newCust)
        {
            var request = new CustomerRequest
            {
                Phone = newCust.Phone,
                Id = newCust.CustomerId
            };

            Result<Customer> result = _gateway.Customer.Create(request);

            var ret = new NewCustomerResultSM
            {
                IsSuccess = result.IsSuccess()
            };

            if (ret.IsSuccess)
            {
                ret.NewBraintreeCustomerId = result.Target.Id;
            }

            return ret;
        }
Esempio n. 12
0
        public async Task <string> GetCustomerId(string email, string phone, string firstName, string lastName)
        {
            Braintree.CustomerSearchRequest search = new Braintree.CustomerSearchRequest();
            search.Email.Is(email);
            var searchResult = await _braintreeGateway.Customer.SearchAsync(search);

            if (searchResult.Ids.Any())
            {
                return(searchResult.FirstItem.Id);
            }
            else
            {
                Braintree.CustomerRequest customer = new Braintree.CustomerRequest();
                customer.Email     = email;
                customer.Phone     = phone;
                customer.FirstName = firstName;
                customer.LastName  = lastName;

                var customerResult = await _braintreeGateway.Customer.CreateAsync(customer);

                return(customerResult.Target.Id);
            }
        }
Esempio n. 13
0
        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 = "5105105105105100",
                    ExpirationDate = "05/12"
                }
            };

            customer = gateway.Customer.Create(request).Target;
            creditCard = customer.CreditCards[0];
        }
Esempio n. 14
0
        public Braintree.Customer GetCustomer(string email)
        {
            var customerGateway = gateway.Customer;

            Braintree.CustomerSearchRequest query = new Braintree.CustomerSearchRequest();
            query.Email.Is(email);
            var matchedCustomers = customerGateway.Search(query);

            Braintree.Customer customer = null;
            if (matchedCustomers.Ids.Count == 0)
            {
                Braintree.CustomerRequest newCustomer = new Braintree.CustomerRequest();
                newCustomer.Email = email;

                var result = customerGateway.Create(newCustomer);
                customer = result.Target;
            }
            else
            {
                customer = matchedCustomers.FirstItem;
            }
            return(customer);
        }
Esempio n. 15
0
        public StoreCustomerResult UpdateCustomerWithCreditCard(PaymentCard card, Guid userId)
        {
            var request = new CustomerRequest
            {
                Id = userId.ToString(),
                FirstName = currentUser.FirstName,
                LastName = currentUser.LastName,
                Email = currentUser.Email,
                Phone = currentUser.MobilePhone,

                CreditCard = new CreditCardRequest
                {
                    CardholderName = card.Name,
                    Number = card.Number,
                    CVV = card.CVV,
                    ExpirationDate = card.ExpiryDate.ToString("MM/yyyy"),
                    Options = new CreditCardOptionsRequest
                    {
                        MakeDefault = true,
                        VerifyCard = true
                    }
                }
            };

            Result<Customer> result = Gateway.Customer.Update(userId.ToString(), request);

            if (result.IsSuccess())
            {
                Customer customer = result.Target;
                return new StoreCustomerResult { CustomerId = customer.Id, FirstName = customer.FirstName, LastName = customer.LastName };
            }
            else
            {
                foreach (ValidationError error in result.Errors.DeepAll())
                {
                    if (error.Code == ValidationErrorCode.CREDIT_CARD_NUMBER_IS_INVALID ||
                        error.Code == ValidationErrorCode.CREDIT_CARD_CREDIT_CARD_TYPE_IS_NOT_ACCEPTED)
                    {
                        return new StoreCustomerResult { ErrorMessage = ErrorMessage.CreditCardNumberInvalid };
                    }
                }
                return new StoreCustomerResult { ErrorMessage = result.Message };
            }
        }
Esempio n. 16
0
        public virtual async Task <Result <Customer> > CreateAsync(CustomerRequest request)
        {
            XmlNode customerXML = await service.PostAsync(service.MerchantPath() + "/customers", request).ConfigureAwait(false);

            return(new ResultImpl <Customer>(new NodeWrapper(customerXML), gateway));
        }
        public virtual Result<Customer> Create(CustomerRequest request)
        {
            XmlNode customerXML = service.Post(service.MerchantPath() + "/customers", request);

            return new ResultImpl<Customer>(new NodeWrapper(customerXML), gateway);
        }
        public void CardTypeIndicators()
        {
            String name = Guid.NewGuid().ToString("n");
            var createRequest = new CustomerRequest
            {
                CreditCard = new CreditCardRequest
                {
                    CardholderName = name,
                    Number = CreditCardNumbers.CardTypeIndicators.Unknown,
                    ExpirationDate = "05/12",
                    Options = new CreditCardOptionsRequest
                    {
                      VerifyCard = true
                    }
                }
            };

            gateway.Customer.Create(createRequest);

            CreditCardVerificationSearchRequest searchRequest = new CreditCardVerificationSearchRequest().
                CreditCardCardholderName.Is(name);

            ResourceCollection<CreditCardVerification> collection = gateway.CreditCardVerification.Search(searchRequest);

            CreditCardVerification verification = collection.FirstItem;

            Assert.AreEqual(verification.CreditCard.Prepaid, Braintree.CreditCardPrepaid.UNKNOWN);
            Assert.AreEqual(verification.CreditCard.Debit, Braintree.CreditCardDebit.UNKNOWN);
            Assert.AreEqual(verification.CreditCard.DurbinRegulated, Braintree.CreditCardDurbinRegulated.UNKNOWN);
            Assert.AreEqual(verification.CreditCard.Commercial, Braintree.CreditCardCommercial.UNKNOWN);
            Assert.AreEqual(verification.CreditCard.Healthcare, Braintree.CreditCardHealthcare.UNKNOWN);
            Assert.AreEqual(verification.CreditCard.Payroll, Braintree.CreditCardPayroll.UNKNOWN);

        }
Esempio n. 19
0
        public virtual Result <Customer> Create(CustomerRequest request)
        {
            XmlNode customerXML = service.Post(service.MerchantPath() + "/customers", request);

            return(new ResultImpl <Customer>(new NodeWrapper(customerXML), gateway));
        }
        public void Search_OnTextFields()
        {
            var createRequest = new CustomerRequest
            {
                Email = "*****@*****.**",
                CreditCard = new CreditCardRequest
                {
                    Number = "4111111111111111",
                    ExpirationDate = "05/12",
                    BillingAddress = new CreditCardAddressRequest
                    {
                        PostalCode = "44444"
                    },
                    Options = new CreditCardOptionsRequest
                    {
                        VerifyCard = true
                    }
                }
            };

            Result<Customer> result = gateway.Customer.Create(createRequest);
            String token = result.Target.CreditCards[0].Token;
            String postalCode = result.Target.CreditCards[0].BillingAddress.PostalCode;
            String customerId = result.Target.Id;
            String customerEmail = result.Target.Email;

            CreditCardVerificationSearchRequest searchRequest = new CreditCardVerificationSearchRequest().
                PaymentMethodToken.Is(token).
                BillingAddressDetailsPostalCode.Is(postalCode).
                CustomerId.Is(customerId).
                CustomerEmail.Is(customerEmail);

            ResourceCollection<CreditCardVerification> collection = gateway.CreditCardVerification.Search(searchRequest);
            CreditCardVerification verification = collection.FirstItem;

            Assert.AreEqual(1, collection.MaximumCount);
            Assert.AreEqual(token, verification.CreditCard.Token);
            Assert.AreEqual(postalCode, verification.BillingAddress.PostalCode);
        }
        public void Search_OnMultipleValueFields()
        {
            var createRequest = new CustomerRequest
            {
                CreditCard = new CreditCardRequest
                {
                    Number = CreditCardNumbers.FailsSandboxVerification.Visa,
                    ExpirationDate = "05/12",
                    Options = new CreditCardOptionsRequest
                    {
                      VerifyCard = true
                    }
                }
            };

            Result<Customer> result = gateway.Customer.Create(createRequest);
            CreditCardVerification verification1 = gateway.CreditCardVerification.Find(result.CreditCardVerification.Id);

            createRequest = new CustomerRequest
            {
                CreditCard = new CreditCardRequest
                {
                    Number = CreditCardNumbers.FailsSandboxVerification.MasterCard,
                    ExpirationDate = "05/12",
                    Options = new CreditCardOptionsRequest
                    {
                      VerifyCard = true
                    }
                }
            };

            result = gateway.Customer.Create(createRequest);
            CreditCardVerification verification2 = gateway.CreditCardVerification.Find(result.CreditCardVerification.Id);

            CreditCardVerificationSearchRequest searchRequest = new CreditCardVerificationSearchRequest().
                CreditCardCardType.IncludedIn(CreditCardCardType.VISA, CreditCardCardType.MASTER_CARD).
                Ids.IncludedIn(verification1.Id, verification2.Id).
                Status.IncludedIn(verification1.Status);

            ResourceCollection<CreditCardVerification> collection = gateway.CreditCardVerification.Search(searchRequest);

            Assert.AreEqual(2, collection.MaximumCount);
        }
        public ActionResult Edit(string id, CustomerRequest request)
        {
            try
            {
                var result = gateway.Customer.Update(id, request);

                if (result.IsSuccess())
                    TempData["success"] = "Customer updated successfully.";
                else
                    TempData["error"] = "Customer not updated. Error: " + result.Message;
            }
            catch (NotFoundException)
            {
                TempData["error"] = "No customer found with Id = " + id;
            }
            catch (Exception exc)
            {
                TempData["error"] = exc.Message;
            }

            return RedirectToAction("Edit", new { id });
        }
Esempio n. 23
0
        public virtual Result <Customer> Update(String Id, CustomerRequest request)
        {
            XmlNode customerXML = Service.Put("/customers/" + Id, request);

            return(new ResultImpl <Customer>(new NodeWrapper(customerXML), Service));
        }
Esempio n. 24
0
        public virtual Result <Customer> Create(CustomerRequest request)
        {
            XmlNode customerXML = Service.Post("/customers", request);

            return(new ResultImpl <Customer>(new NodeWrapper(customerXML), Service));
        }
        public void UpdateCustomerFromTransparentRedirect()
        {
            var createRequest = new CustomerRequest
            {
                FirstName = "Miranda",
                LastName = "Higgenbottom"
            };

            Customer createdCustomer = gateway.Customer.Create(createRequest).Target;

            CustomerRequest trParams = new CustomerRequest
            {
                CustomerId = createdCustomer.Id,
                FirstName = "Penelope"
            };

            CustomerRequest request = new CustomerRequest
            {
                LastName = "Lambert"
            };

            string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service);
            Result<Customer> result = gateway.TransparentRedirect.ConfirmCustomer(queryString);
            Assert.IsTrue(result.IsSuccess());
            Customer updatedCustomer = gateway.Customer.Find(createdCustomer.Id);

            Assert.AreEqual("Penelope", updatedCustomer.FirstName);
            Assert.AreEqual("Lambert", updatedCustomer.LastName);
        }
        public void CreateCustomerFromTransparentRedirect()
        {
            CustomerRequest trParams = new CustomerRequest
            {
                FirstName = "John"
            };

            CustomerRequest request = new CustomerRequest
            {
                LastName = "Doe"
            };

            string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service);
            Result<Customer> result = gateway.TransparentRedirect.ConfirmCustomer(queryString);
            Assert.IsTrue(result.IsSuccess());
            Customer customer = result.Target;

            Assert.AreEqual("John", customer.FirstName);
            Assert.AreEqual("Doe", customer.LastName);
        }
Esempio n. 27
0
        public virtual async Task <Result <Customer> > UpdateAsync(string Id, CustomerRequest request)
        {
            XmlNode customerXML = await service.PutAsync(service.MerchantPath() + "/customers/" + Id, request);

            return(new ResultImpl <Customer>(new NodeWrapper(customerXML), gateway));
        }
Esempio n. 28
0
        public virtual Result<Customer> Update(String Id, CustomerRequest request)
        {
            XmlNode customerXML = Service.Put("/customers/" + Id, request);

            return new Result<Customer>(new NodeWrapper(customerXML), Service);
        }
Esempio n. 29
0
        public ActionResult Signup(UserModel.User user, System.Web.Mvc.FormCollection collection)
        {
            if (ModelState.IsValid)
            {
                var PlanId = String.Empty;
                NewSubscription UserData = new NewSubscription();
                UserData.Email = user.BillingEmail;
                UserData.Username = user.BillingName;
                UserData.Password = user.BillingPassword;
                UserData.Plan = "Premium";
                PlanId = "d5jb";
                UserData.Company = user.Company;
                UserData.TOSCheck = Convert.ToInt32(user.TOSCheck);
                var regexItem = new Regex(@"\d");
                string email = user.BillingEmail;
                Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
                Match match = regex.Match(email);
                if (!match.Success)
                {
                    //Bad Email
                    ModelState.AddModelError("BillingEmail", "Invalid Email");
                }
                else if (user.IsEmailValid(email))
                {
                    //Email Taken
                    ModelState.AddModelError("BillingEmail", "Email already in use");
                }
                if (user.BillingName.Length < 5)
                {
                    //Bad Username
                    ModelState.AddModelError("BillingName", "Username must be a least 5 characters in length");
                }
                else if (user.DoesUsernameExist(user.BillingName))
                {
                    //Username already exists
                    ModelState.AddModelError("BillingName", "Username is already in use");
                }
                if (user.BillingPassword != user.BillingPasswordTwo)
                {
                    //Passwords Don't Match
                    ModelState.AddModelError("BillingPassword", "Passwords do not match");

                }
                else if (user.BillingPassword.Length < 6)
                {
                    //Passwords Too Short
                    ModelState.AddModelError("BillingPassword", "Password must be at least 6 characters in length");
                }
                else if (!regexItem.IsMatch(user.BillingPassword))
                {
                    //Passwords do not contain number
                    ModelState.AddModelError("BillingPassword", "Password must contain at least one number");
                }
                if (user.Company.Length < 1)
                {
                    //Invalid Company
                    ModelState.AddModelError("Company", "Invalid Company Name");
                }
                if (!user.TOSCheck)
                {
                    //Terms of Service not checked
                    ModelState.AddModelError("General", "You must agree to terms of service");
                }
                //Write to DB if all is good
                if (ModelState.IsValid)
                {
                    CustomerRequest request = new CustomerRequest
                    {
                        CreditCard = new CreditCardRequest
                        {
                            CardholderName = collection["name"],
                            Number = collection["number"],
                            ExpirationMonth = collection["month"],
                            ExpirationYear = collection["year"],
                            CVV = collection["cvv"]
                        }
                    };
                    Result<Customer> result = Gateway.BrainTreeGateway.Customer.Create(request);
                    if (result.IsSuccess())
                    {
                        //Successful add to Braintree
                        UserData.BillingID = result.Target.Id;
                        if (user.SaveNewUser(UserData))
                        {
                            //Successful write to DB
                            try
                            {
                                Customer customer = Gateway.BrainTreeGateway.Customer.Find(UserData.BillingID);
                                string paymentMethodToken = customer.CreditCards[0].Token;
                                SubscriptionRequest subscriptionRequest = new SubscriptionRequest
                                {
                                    PaymentMethodToken = paymentMethodToken,
                                    PlanId = PlanId
                                };
                                Result<Subscription> subscriptionResult = Gateway.BrainTreeGateway.Subscription.Create(subscriptionRequest);
                                user.UpdateSubscriptionId(user.BillingName, subscriptionResult.Target.Id);
                                return RedirectToAction("Index", "Home");
                            }
                            catch (Braintree.Exceptions.NotFoundException)
                            {
                                //No customer found
                                return RedirectToAction("Error", "User");
                            }
                        }
                        else
                        {
                            //failure writing customer to database
                            return RedirectToAction("Error", "User");
                        }
                    }
                    else
                    {
                        //failure adding customer to Braintree
                        ModelState.AddModelError("General", result.Message);
                    }
                }
            }
            return View(user);
        }
Esempio n. 30
0
        public void Create_WithPayPalAccount()
        {
            var customerRequest = new CustomerRequest
            {
                PaymentMethodNonce = Nonce.PayPalFuturePayment
            };
            var customer = gateway.Customer.Create(customerRequest).Target;

            TestPlan plan = PlanFixture.PLAN_WITHOUT_TRIAL;
            SubscriptionRequest request = new SubscriptionRequest
            {
                PaymentMethodToken = customer.PayPalAccounts[0].Token,
                PlanId = plan.Id,
            };

            Result<Subscription> result = gateway.Subscription.Create(request);
            Assert.IsTrue(result.IsSuccess());
            Assert.AreEqual(result.Target.PaymentMethodToken, customer.PayPalAccounts[0].Token);
        }
Esempio n. 31
0
        protected Braintree.Customer SearchOrCreateBTCustomer(Profile profile)
        {
            MembershipUser user = Membership.GetUser(profile.Name);

            //Inserimento del cliente nella banca dati
            var c = new CustomerRequest
            {
                Id = profile.Name,
                Company = profile.CompanyName,
                Email = user.Email,
                Phone = profile.Phone,
            };

            Braintree.Customer customer;
            Result<Braintree.Customer> customerResult;
            //Se la carta non è stata trovata ci sono 2 possibilità:
            //1. Non esiste il cliente in Braintree
            //2. Non esiste la carta
            try
            {
                //Cerco il cliente
                customer = Constants.Gateway.Customer.Find(profile.Name);
                customerResult = Constants.Gateway.Customer.Update(profile.Name, c);
            }
            catch (NotFoundException)
            {
                customerResult = Constants.Gateway.Customer.Create(c);
                //Cerco il cliente
                customer = Constants.Gateway.Customer.Find(profile.Name);
            }

            return customer;

        }
        public virtual Result<Customer> Update(string Id, CustomerRequest request)
        {
            XmlNode customerXML = service.Put(service.MerchantPath() + "/customers/" + Id, request);

            return new ResultImpl<Customer>(new NodeWrapper(customerXML), gateway);
        }
Esempio n. 33
0
        public ActionResult Pending(FormCollection collection)
        {
            var profile = profDataRep.GetSingle(this.CurrentUser.ToString());

            CustomerRequest request = new CustomerRequest
            {
                Company = profile.CompanyName,
                CreditCard = new CreditCardRequest
                {
                    BillingAddress = new CreditCardAddressRequest
                    {
                        Company = profile.CompanyName,
                        StreetAddress = profile.Base
                    },
                    Number = collection["number"],
                    ExpirationMonth = collection["month"],
                    ExpirationYear = collection["year"],
                    CVV = collection["cvv"]
                }
            };

            Result<Braintree.Customer> result = Constants.Gateway.Customer.Create(request);

            if (result.IsSuccess())
            {
                try
                {
                    Roles.RemoveUserFromRole(CurrentUser.ToString(), "Pending");
                    profile.BrianTreeCustomerId = result.Target.Id;
                }
                catch (Exception)
                {

                }

                Braintree.Customer customer = result.Target;
                ViewData["CustomerName"] = customer.FirstName + " " + customer.LastName;
                ViewData["Message"] = "";
            }
            else
            {
                ViewData["Message"] = result.Message;
            }

            return View("ResultPending");

        }
Esempio n. 34
0
        public void SnapshotPlanIdAddOnsAndDiscountsFromSubscription()
        {
            CustomerRequest customerRequest = new CustomerRequest
            {
                CreditCard = new CreditCardRequest
                {
                    CardholderName = "Fred Jones",
                    Number = "5105105105105100",
                    ExpirationDate = "05/12"
                }
            };

            CreditCard creditCard = gateway.Customer.Create(customerRequest).Target.CreditCards[0];

            SubscriptionRequest request = new SubscriptionRequest
            {
                PaymentMethodToken = creditCard.Token,
                PlanId = PlanFixture.PLAN_WITHOUT_TRIAL.Id,
                AddOns = new AddOnsRequest
                {
                    Add = new AddAddOnRequest[]
                    {
                        new AddAddOnRequest
                        {
                            InheritedFromId = "increase_10",
                            Amount = 11M,
                            NumberOfBillingCycles = 5,
                            Quantity = 2,
                        },
                        new AddAddOnRequest
                        {
                            InheritedFromId = "increase_20",
                            Amount = 21M,
                            NumberOfBillingCycles = 6,
                            Quantity = 3,
                        }
                    }
                },
                Discounts = new DiscountsRequest
                {
                    Add = new AddDiscountRequest[]
                    {
                        new AddDiscountRequest
                        {
                            InheritedFromId = "discount_7",
                            Amount = 7.50M,
                            Quantity = 2,
                            NeverExpires = true
                        },
                    }
                }
            };

            Transaction transaction = gateway.Subscription.Create(request).Target.Transactions[0];

            Assert.AreEqual(PlanFixture.PLAN_WITHOUT_TRIAL.Id, transaction.PlanId);

            List<AddOn> addOns = transaction.AddOns;
            addOns.Sort(TestHelper.CompareModificationsById);

            Assert.AreEqual(2, addOns.Count);

            Assert.AreEqual("increase_10", addOns[0].Id);
            Assert.AreEqual(11M, addOns[0].Amount);
            Assert.AreEqual(2, addOns[0].Quantity);
            Assert.IsFalse(addOns[0].NeverExpires.Value);
            Assert.AreEqual(5, addOns[0].NumberOfBillingCycles);

            Assert.AreEqual("increase_20", addOns[1].Id);
            Assert.AreEqual(21M, addOns[1].Amount);
            Assert.AreEqual(3, addOns[1].Quantity);
            Assert.IsFalse(addOns[1].NeverExpires.Value);
            Assert.AreEqual(6, addOns[1].NumberOfBillingCycles);

            List<Discount> discounts = transaction.Discounts;
            Assert.AreEqual(1, discounts.Count);

            Assert.AreEqual("discount_7", discounts[0].Id);
            Assert.AreEqual(7.50M, discounts[0].Amount);
            Assert.AreEqual(2, discounts[0].Quantity);
            Assert.IsTrue(discounts[0].NeverExpires.Value);
            Assert.IsNull(discounts[0].NumberOfBillingCycles);
        }
Esempio n. 35
0
        public void StoreCustomer(string userId)
        {
            var request = new CustomerRequest
            {
                Id = userId,
                FirstName = currentUser.FirstName,
                LastName = currentUser.LastName,
                Email = currentUser.Email,
                Phone = currentUser.MobilePhone
            };

            if (IsCustomerExists(userId))
            {
                Gateway.Customer.Update(userId, request);
            }
            else
            {
                Gateway.Customer.Create(request);
            }
        }
Esempio n. 36
0
        public virtual Result <Customer> Update(string Id, CustomerRequest request)
        {
            XmlNode customerXML = service.Put(service.MerchantPath() + "/customers/" + Id, request);

            return(new ResultImpl <Customer>(new NodeWrapper(customerXML), gateway));
        }
        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);

            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);
                Assert.Fail("Expected DownForMaintenanceException");
            } catch (Braintree.Exceptions.DownForMaintenanceException) {
                // expected
            }
        }
Esempio n. 38
0
        public virtual Result<Customer> Create(CustomerRequest request)
        {
            XmlNode customerXML = Service.Post("/customers", request);

            return new Result<Customer>(new NodeWrapper(customerXML), Service);
        }
        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);

            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);
                Assert.Fail("Expected AuthenticationException");
            } catch (Braintree.Exceptions.AuthenticationException) {
                // expected
            }
        }
Esempio n. 40
0
        public void CreateTransaction(BpiOrder order)
        {
            CustomerRequest request = new CustomerRequest()
            {
                FirstName = order.CardHolderFirstName,
                LastName = order.CardHolderLastName,
                CreditCard = new CreditCardRequest()
                {
                    BillingAddress = new CreditCardAddressRequest{
                        PostalCode = order.CardholderPostalCode
                    },
                    Number = order.CreditCardNumber,
                    ExpirationMonth = order.ExpirationMonth,
                    ExpirationYear = order.ExpirationYear,
                    CVV = order.Cvv,
                    CardholderName = order.CardHolderFirstName
                }
            };

            Result<Customer> result = BraintreeConstants.Gateway.Customer.Create(request);

            //TransactionRequest request = new TransactionRequest
            //{
            //    Amount = order.Amount,
            //    CreditCard = new TransactionCreditCardRequest
            //    {
            //        Number = order.CreditCardNumber,
            //        CVV = order.Cvv,
            //        ExpirationMonth = order.ExpirationMonth,
            //        ExpirationYear = order.ExpirationYear
            //    },
            //    Options = new TransactionOptionsRequest
            //    {
            //        SubmitForSettlement = true
            //    }
            //};

            //Result<Transaction> result = BraintreeConstants.Gateway.Transaction.Sale(request);

            if (result.IsSuccess())
            {
                var customer = result.Target;
                order.GatewayCustomerId = customer.Id;

                string paymentMethodToken = customer.CreditCards[0].Token;

                SubscriptionRequest subRequest = new SubscriptionRequest()
                {
                    PaymentMethodToken = paymentMethodToken,
                    PlanId = order.PlanName
                };

                Result<Subscription> subResult = BraintreeConstants.Gateway.Subscription.Create(subRequest);

                order.GatewaySubscriptionId = subRequest.Id;
                //order.Message = subResult.Target.Status.ToString();
            }
            else {

            }
        }
Esempio n. 41
0
 public ActionResult SaveBillingCardInfo(UserModel.User user, System.Web.Mvc.FormCollection collection)
 {
     var billingID = user.GetBillingID(User.Identity.Name);
     if (billingID != String.Empty)
     {
         Customer customer = Gateway.BrainTreeGateway.Customer.Find(billingID);
         string token = customer.CreditCards[0].Token;
         var request = new CustomerRequest
         {
             CreditCard = new CreditCardRequest
             {
                 CardholderName = collection["name"],
                 Number = collection["number"],
                 ExpirationMonth = collection["month"],
                 ExpirationYear = collection["year"],
                 CVV = collection["cvv"],
                 Options = new CreditCardOptionsRequest
                 {
                     UpdateExistingToken = token
                 }
             }
         };
         Result<Customer> updateResult = Gateway.BrainTreeGateway.Customer.Update(billingID, request);
         if (updateResult.IsSuccess())
         {
             var mongo = new Mongo();
             var config = mongo.GetUserConfiguration(User.Identity.Name);
             if (config.AccountInfoNotification)
             {
                 MailgunAgent.SendChangeEmail(user.GetCurrentEmail(User.Identity.Name), "Your Queue View credit card has been changed.");
             }
             return RedirectToAction("AccountDashboard", "User", new { ADCC = "ChangeCard" });
         }
         else
         {
             //Fail to update with Braintree
             return RedirectToAction("AccountDashboard", "User", new { ADCCFAIL = updateResult.Message });
         }
     }
     else
     {
         //Fail to retrieve Billing ID
         return RedirectToAction("Error", "User");
     }
 }