A class for building requests to manipulate Transaction records in the vault.
Inheritance: Braintree.Request
Esempio n. 1
0
        public string AuthorizeCard(string email, decimal total, decimal tax, string trackingNumber, string addressId, string cardholderName, string cvv, string cardNumber, string expirationMonth, string expirationYear)
        {
            var customer = GetCustomer(email);

            Braintree.TransactionRequest transaction = new Braintree.TransactionRequest();
            //transaction.Amount = 1m;    //I can hard-code a dollar amount for now to test everything else
            transaction.Amount            = total;
            transaction.TaxAmount         = tax;
            transaction.OrderId           = trackingNumber;
            transaction.CustomerId        = customer.Id;
            transaction.ShippingAddressId = addressId;
            //https://developers.braintreepayments.com/reference/general/testing/ruby
            transaction.CreditCard = new Braintree.TransactionCreditCardRequest
            {
                CardholderName  = cardholderName,
                CVV             = cvv,
                Number          = cardNumber,
                ExpirationYear  = expirationYear,
                ExpirationMonth = expirationMonth
            };

            var result = gateway.Transaction.Sale(transaction);

            return(result.Message);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var gateway = new BraintreeGateway
            {
                Environment = Braintree.Environment.SANDBOX,
                MerchantId = "78c2hsmmg73s6sdg",
                PublicKey = "jsyrqbxq2fqv456k",
                PrivateKey = "004b6691b796db322c57c71343ecf592"
            };

            if (!IsPostBack)
            {
                var clientToken = gateway.ClientToken.generate();
                String clientTK = clientToken;
                cTK.Value = clientToken;
            }
            else
            {
                var nonceFromTheClient = Request.Form["payment_method_nonce"];

                var request = new TransactionRequest
                {
                    Amount = 100.00M,
                    PaymentMethodNonce = nonceFromTheClient
                };

                Result<Transaction> result = gateway.Transaction.Sale(request);
                var id = result.Transaction.Id;
                var amount = result.Transaction.Amount;
                var date = result.Transaction.UpdatedAt;
                var status = result.Transaction.ProcessorResponseCode;
            }
        }
        public PaymentResult ProcessPayment(ViewModels.CheckoutViewModel model)
        {
            var request = new TransactionRequest()
            {
                Amount = model.Total,
                CreditCard = new TransactionCreditCardRequest()
                {
                    Number = model.CardNumber,
                    CVV = model.Cvv,
                    ExpirationMonth = model.Month,
                    ExpirationYear = model.Year
                },
                Options = new TransactionOptionsRequest()
                {
                    SubmitForSettlement = true
                }
            };

            var result = _gateway.Transaction.Sale(request);

            if (result.IsSuccess())
            {
                return new PaymentResult(result.Target.Id, true, null);
            }

            return new PaymentResult(null, false, result.Message);
        }
        public virtual Result<Transaction> Credit(TransactionRequest request)
        {
            request.Type = TransactionType.CREDIT;
            XmlNode response = service.Post(service.MerchantPath() + "/transactions", request);

            return new ResultImpl<Transaction>(new NodeWrapper(response), gateway);
        }
        public void ToXml_Includes_FraudMerchantId()
        {
            TransactionRequest request = new TransactionRequest();
            request.FraudMerchantId = "my_fmid";

            Assert.IsTrue(request.ToXml().Contains("my_fmid"));
        }
        public virtual Result<Transaction> Sale(TransactionRequest request)
        {
            request.Type = TransactionType.SALE;
            XmlNode response = Service.Post("/transactions", request);

            return new Result<Transaction>(new NodeWrapper(response), Service);
        }
        public BraintreeResponse MakePaymentPaypal(string nonce)
        {
            BraintreeGateway braintreeGateway = GetGateway();
            TransactionRequest request = new TransactionRequest
            {
                Amount = _cartModel.TotalToPay,
                PaymentMethodNonce = nonce,
                BillingAddress = GetBillingAddress(),
                Options = new TransactionOptionsRequest
                {
                    SubmitForSettlement = true
                }
            };

            Result<Transaction> result = braintreeGateway.Transaction.Sale(request);

            if (result.IsSuccess())
            {
                Order order = _orderPlacementService.PlaceOrder(_cartModel,
                    o =>
                    {
                        o.PaymentStatus = PaymentStatus.Paid;
                        o.CaptureTransactionId = result.Target.Id;
                    });
                return new BraintreeResponse { Success = true, Order = order };
            }
            return new BraintreeResponse
            {
                Success = false,
                Errors = new List<string> { result.Message }
            };
        }
        public void Generate_ReturnsTransactionsSettledOnAGivenDay()
        {
            TransactionRequest request = new TransactionRequest
            {
                Amount = 1000M,
                CreditCard = new TransactionCreditCardRequest
                {
                    Number = "4111111111111111",
                    ExpirationDate = "05/2012",
                    CardholderName = "Tom Smith",
                },
                Options = new TransactionOptionsRequest
                {
                    SubmitForSettlement = true
                },
            };

            Transaction transaction = gateway.Transaction.Sale(request).Target;
            Transaction settlementResult = gateway.TestTransaction.Settle(transaction.Id);
            var settlementDate = settlementResult.SettlementBatchId.Substring(0,10);
            transaction = gateway.Transaction.Find(transaction.Id);
            var result = gateway.SettlementBatchSummary.Generate(System.DateTime.Parse(settlementDate));
            var visas = new List<IDictionary<string,string>>();
            foreach (var row in result.Target.Records)
            {
                if (Braintree.CreditCardCardType.VISA.ToString().Equals(row["card_type"]))
                {
                    visas.Add(row);

                }
            }

            Assert.AreEqual(1, visas.Count);
        }
        public ActionResult CreateTransaction(FormCollection collection)
        {
            TransactionRequest request = new TransactionRequest
            {
                Amount = 1000.0M,
                CreditCard = new TransactionCreditCardRequest
                {
                    Number = collection["number"],
                    CVV = collection["cvv"],
                    ExpirationMonth = collection["month"],
                    ExpirationYear = collection["year"]
                },
                Options = new TransactionOptionsRequest
                {
                    SubmitForSettlement = true
                }
            };

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

            if (result.IsSuccess())
            {
                Transaction transaction = result.Target;
                ViewData["TransactionId"] = transaction.Id;
            }
            else
            {
                ViewData["Message"] = result.Message;
            }

            return View();
        }
        public void ToXml_InludesPaymentMethodNonce()
        {
            TransactionRequest request = new TransactionRequest();
            request.PaymentMethodNonce = "1232131232";

            Assert.IsTrue(request.ToXml().Contains("1232131232"));
        }
        public void ToXml_Includes_DeviceSessionId()
        {
            TransactionRequest request = new TransactionRequest();
            request.DeviceSessionId = "my_dsid";

            Assert.IsTrue(request.ToXml().Contains("my_dsid"));
        }
        public virtual Result<Transaction> HoldInEscrow(string id)
        {
            var request = new TransactionRequest();

            XmlNode response = service.Put(service.MerchantPath() + "/transactions/" + id + "/hold_in_escrow", request);

            return new ResultImpl<Transaction>(new NodeWrapper(response), gateway);
        }
        public virtual Result<Transaction> CancelRelease(string id)
        {
            var request = new TransactionRequest();

            XmlNode response = service.Put(service.MerchantPath() + "/transactions/" + id + "/cancel_release", request);

            return new ResultImpl<Transaction>(new NodeWrapper(response), gateway);
        }
Esempio n. 14
0
        public void ToXML_EscapesGeneratedXMLForString()
        {
            TransactionRequest request = new TransactionRequest
            {
                OrderId = "<>&\"'"
            };

            TestHelper.AssertIncludes("<order-id>&lt;&gt;&amp;&quot;&apos;</order-id>", request.ToXml());
        }
 public virtual Result<Transaction> Refund(String id, Decimal amount)
 {
     TransactionRequest request = new TransactionRequest
     {
         Amount = amount
     };
     XmlNode response = Service.Post("/transactions/" + id + "/refund", request);
     return new Result<Transaction>(new NodeWrapper(response), Service);
 }
        public void ToXml_Includes_DeviceData()
        {
            TransactionRequest request = new TransactionRequest();
            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"));
        }
Esempio n. 17
0
        public void ToXML_EscapesGeneratedXMLForNestedSearchCriteria()
        {
            TransactionRequest request = new TransactionRequest
            {
                Customer = new CustomerRequest
                {
                    FirstName = "<John>"
                }
            };

            TestHelper.AssertIncludes("<first-name>&lt;John&gt;</first-name>", request.ToXml());
        }
        public Result<Transaction> Sale(string token, TransactionRequest transactionRequest)
        {
            if (transactionRequest.Options == null) {
                transactionRequest.Options = new TransactionOptionsRequest
                {
                    SubmitForSettlement = true
                };
            }

            transactionRequest.PaymentMethodToken = token;
            return gateway.Transaction.Sale(transactionRequest);
        }
        public ActionResult Create(decimal amount, string payment_method_nonce, bool savePaymentMethod = false)
        {
            if (amount > 0)
            {
                TempData["info"] = payment_method_nonce;

                var request = new TransactionRequest
                {
                    Amount = amount,
                    PaymentMethodNonce = payment_method_nonce
                };

                if (savePaymentMethod)
                {
                    // grab this data from the user object normally
                    request.Customer = new CustomerRequest
                    {
                        Id = "3rfybedfwny4su9f",
                        FirstName = "Fred",
                        LastName = "Mbogo",
                        Email = "*****@*****.**"
                    };

                    request.CustomFields.Add("listing_type", "Directory Profile");
                    request.CustomFields.Add("listing_id", "142484");

                    request.Options = new TransactionOptionsRequest
                    {
                        StoreInVaultOnSuccess = true
                    };
                }

                var result = Common.GetGateway().Transaction.Sale(request);
                if (result.IsSuccess())
                {
                    TempData["success"] = "Sale completed";
                }
                else
                {
                    TempData["error"] = result.Message;
                }

                return RedirectToAction("Index");
            }

            return View(amount);
        }
        public void SettlementPending()
        {
            var request = new TransactionRequest
            {
                Amount = 100M,
                PaymentMethodNonce = Nonce.Transactable,
                Options = new TransactionOptionsRequest
                {
                    SubmitForSettlement = true
                }
            };

            var transactionResult = gateway.Transaction.Sale(request);
            Transaction transaction = gateway.TestTransaction.SettlementPending(transactionResult.Target.Id);

            Assert.AreEqual(TransactionStatus.SETTLEMENT_PENDING, transaction.Status);
        }
Esempio n. 21
0
        public bool PostTransaction(string nonce_data, decimal amount, string transactionData)
        {
            var request = new TransactionRequest
            {
                Amount = amount,
                MerchantAccountId="TTP",
                PaymentMethodNonce = nonce_data,
                CustomerId = "36428238",
                ServiceFeeAmount= 1.0M,

                Options = new TransactionOptionsRequest
                {
                    SubmitForSettlement = true,
                    StoreInVault = true
                }

            };

            Result<Transaction> result = gateway.Transaction.Sale(request);
            return result.IsSuccess();
        }
Esempio n. 22
0
        public void TransactionCreate()
        {
            TransactionRequest request = new TransactionRequest
            {
                Amount = SandboxValues.TransactionAmount.AUTHORIZE,
                PaymentMethodNonce = Nonce.Coinbase
            };
            Result<Transaction> result = gateway.Transaction.Sale(request);
            Assert.IsTrue(result.IsSuccess());

            CoinbaseDetails details = result.Target.CoinbaseDetails;
            Assert.IsNotNull(details);

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

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

            Assert.AreNotEqual("", details.UserId);
            Assert.IsNotNull(details.UserId);
        }
        public PaymentResponse Purchase([FromBody] PaymentRequest request)
        {
            var transaction = new TransactionRequest
            {
                Amount = request.Amount * request.Price,
                Descriptor = new DescriptorRequest
                {
                    Name = "techent*subscription",
                    Phone = "(0888)123456",
                    Url = "google.com"
                },
                Options = new TransactionOptionsRequest
                {
                    SubmitForSettlement = true,
                    StoreInVault = true
                },
                PaymentMethodNonce = request.Nonce
            };

            var id = this.GetCustomerId(request.Email);
            if (id == null)
            {
                transaction.Customer = new CustomerRequest
                {
                    Email = request.Email
                };
            }
            else
            {
                transaction.CustomerId = id;
            }

            var result = this.gateway.Value.Transaction.Sale(transaction);
            return new PaymentResponse
            {
                IsSuccess = result.IsSuccess(),
                Errors = result.Errors?.DeepAll()?.Select(e => e.Message)
            };
        }
        public ActionResult Charge(string id, string token, decimal amount)
        {
            var request = new TransactionRequest
            {
                Amount = amount,
                PaymentMethodToken = token,
                CustomerId = id,
                Options = new TransactionOptionsRequest
                {
                    SubmitForSettlement = true
                }
            };

            var result = gateway.Transaction.Sale(request);

            if (result.IsSuccess())
                TempData["success"] = string.Format("Charge completed for {0:c}", amount);
            else
                TempData["error"] = "There was a problem completing the transaction. Error: " + result.Message;

            return RedirectToAction("Details", new { id });
        }
Esempio n. 25
0
        public void ToXML_EnsuresUSLocaleForDecimals()
        {
            System.Globalization.CultureInfo existingCulture = System.Globalization.CultureInfo.CurrentCulture;

            try
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("it-IT");

                TransactionRequest transactionRequest = new TransactionRequest
                {
                    Amount = 100.0M
                };

                SubscriptionRequest subscriptionRequest = new SubscriptionRequest
                {
                    Price = 200.0M,
                };

                SubscriptionTransactionRequest subscriptionTransactionRequest = new SubscriptionTransactionRequest
                {
                    Amount = 300.0M
                };

                ModificationRequest modificationRequest = new ModificationRequest
                {
                    Amount = 400.0M
                };

                TestHelper.AssertIncludes("<amount>100.0</amount>", transactionRequest.ToXml());
                TestHelper.AssertIncludes("<price>200.0</price>", subscriptionRequest.ToXml());
                TestHelper.AssertIncludes("<amount>300.0</amount>", subscriptionTransactionRequest.ToXml());
                TestHelper.AssertIncludes("<amount>400.0</amount>", modificationRequest.ToXml("root"));
            }
            finally
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = existingCulture;
            }
        }
        public async Task <string> AuthorizeCard(string email, decimal total, decimal tax, string trackingNumber, string addressId, string cardholderName, string cvv, string cardNumber, string expirationMonth, string expirationYear)
        {
            var customer = await GetCustomerAsync(email);

            Braintree.TransactionRequest transaction = new Braintree.TransactionRequest();
            transaction.Amount            = total;
            transaction.TaxAmount         = tax;
            transaction.OrderId           = trackingNumber;
            transaction.CustomerId        = customer.Id;
            transaction.ShippingAddressId = addressId;
            //https://developers.braintreepayments.com/reference/general/testing/ruby
            transaction.CreditCard = new Braintree.TransactionCreditCardRequest
            {
                CardholderName  = cardholderName,
                CVV             = cvv,
                Number          = cardNumber,
                ExpirationYear  = expirationYear,
                ExpirationMonth = expirationMonth
            };

            var result = await gateway.Transaction.SaleAsync(transaction);

            return(result.Message);
        }
        public void CreateTransactionFromTransparentRedirect()
        {
            TransactionRequest trParams = new TransactionRequest
            {
                Type = TransactionType.SALE
            };

            TransactionRequest request = new TransactionRequest
            {
                Amount = SandboxValues.TransactionAmount.AUTHORIZE,
                CreditCard = new TransactionCreditCardRequest
                {
                    Number = SandboxValues.CreditCardNumber.VISA,
                    ExpirationDate = "05/2009",
                }
            };

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

            Assert.AreEqual(1000.00, transaction.Amount);
            Assert.AreEqual(TransactionType.SALE, transaction.Type);
            Assert.AreEqual(TransactionStatus.AUTHORIZED, transaction.Status);
            Assert.AreEqual(DateTime.Now.Year, transaction.CreatedAt.Value.Year);
            Assert.AreEqual(DateTime.Now.Year, transaction.UpdatedAt.Value.Year);

            CreditCard creditCard = transaction.CreditCard;
            Assert.AreEqual("411111", creditCard.Bin);
            Assert.AreEqual("1111", creditCard.LastFour);
            Assert.AreEqual("05", creditCard.ExpirationMonth);
            Assert.AreEqual("2009", creditCard.ExpirationYear);
            Assert.AreEqual("05/2009", creditCard.ExpirationDate);

        }
Esempio n. 28
0
        public void Search_OnProcessorDeclinedAt()
        {
            TransactionRequest request = new TransactionRequest
            {
                Amount = SandboxValues.TransactionAmount.DECLINE,
                CreditCard = new TransactionCreditCardRequest
                {
                    Number = SandboxValues.CreditCardNumber.VISA,
                    ExpirationDate = "05/2010"
                }
            };

            Transaction transaction = gateway.Transaction.Sale(request).Transaction;

            DateTime threeDaysEarlier = DateTime.Now.AddDays(-3);
            DateTime oneDayEarlier = DateTime.Now.AddDays(-1);
            DateTime oneDayLater = DateTime.Now.AddDays(1);

            TransactionSearchRequest searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                ProcessorDeclinedAt.Between(oneDayEarlier, oneDayLater);

            Assert.AreEqual(1, gateway.Transaction.Search(searchRequest).MaximumCount);

            searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                ProcessorDeclinedAt.GreaterThanOrEqualTo(oneDayEarlier);

            Assert.AreEqual(1, gateway.Transaction.Search(searchRequest).MaximumCount);

            searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                ProcessorDeclinedAt.LessThanOrEqualTo(oneDayLater);

            Assert.AreEqual(1, gateway.Transaction.Search(searchRequest).MaximumCount);

            searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                ProcessorDeclinedAt.Between(threeDaysEarlier, oneDayEarlier);

            Assert.AreEqual(0, gateway.Transaction.Search(searchRequest).MaximumCount);
        }
Esempio n. 29
0
        public void Search_OnGatewayRejectedAt()
        {
            BraintreeGateway processingRulesGateway = new BraintreeGateway
            {
                Environment = Environment.DEVELOPMENT,
                MerchantId = "processing_rules_merchant_id",
                PublicKey = "processing_rules_public_key",
                PrivateKey = "processing_rules_private_key"
            };

            TransactionRequest request = new TransactionRequest
            {
                Amount = SandboxValues.TransactionAmount.AUTHORIZE,
                CreditCard = new TransactionCreditCardRequest
                {
                    Number = SandboxValues.CreditCardNumber.VISA,
                    ExpirationDate = "05/2010",
                    CVV = "200"
                }
            };

            Transaction transaction = processingRulesGateway.Transaction.Sale(request).Transaction;

            DateTime threeDaysEarlier = DateTime.Now.AddDays(-3);
            DateTime oneDayEarlier = DateTime.Now.AddDays(-1);
            DateTime oneDayLater = DateTime.Now.AddDays(1);

            TransactionSearchRequest searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                GatewayRejectedAt.Between(oneDayEarlier, oneDayLater);

            Assert.AreEqual(1, processingRulesGateway.Transaction.Search(searchRequest).MaximumCount);

            searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                GatewayRejectedAt.GreaterThanOrEqualTo(oneDayEarlier);

            Assert.AreEqual(1, processingRulesGateway.Transaction.Search(searchRequest).MaximumCount);

            searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                GatewayRejectedAt.LessThanOrEqualTo(oneDayLater);

            Assert.AreEqual(1, processingRulesGateway.Transaction.Search(searchRequest).MaximumCount);

            searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                GatewayRejectedAt.Between(threeDaysEarlier, oneDayEarlier);

            Assert.AreEqual(0, processingRulesGateway.Transaction.Search(searchRequest).MaximumCount);
        }
Esempio n. 30
0
        public void Search_OnAllTextFields()
        {
            string creditCardToken = string.Format("cc{0}", new Random().Next(1000000).ToString());
            string firstName = string.Format("Tim{0}", new Random().Next(1000000).ToString());

            TransactionRequest request = new TransactionRequest
            {
                Amount = 1000M,
                CreditCard = new TransactionCreditCardRequest
                {
                    Number = "4111111111111111",
                    ExpirationDate = "05/2012",
                    CardholderName = "Tom Smith",
                    Token = creditCardToken
                },
                BillingAddress = new AddressRequest
                {
                    Company = "Braintree",
                    CountryName = "United States of America",
                    ExtendedAddress = "Suite 123",
                    FirstName = firstName,
                    LastName = "Smith",
                    Locality = "Chicago",
                    PostalCode = "12345",
                    Region = "IL",
                    StreetAddress = "123 Main St"
                },
                Customer = new CustomerRequest
                {
                    Company = "Braintree",
                    Email = "*****@*****.**",
                    Fax = "5551231234",
                    FirstName = "Tom",
                    LastName = "Smith",
                    Phone = "5551231234",
                    Website = "http://example.com"
                },
                Options = new TransactionOptionsRequest
                {
                    StoreInVault = true,
                    SubmitForSettlement = true
                },
                OrderId = "myorder",
                ShippingAddress = new AddressRequest
                {
                    Company = "Braintree P.S.",
                    CountryName = "Mexico",
                    ExtendedAddress = "Apt 456",
                    FirstName = "Thomas",
                    LastName = "Smithy",
                    Locality = "Braintree",
                    PostalCode = "54321",
                    Region = "MA",
                    StreetAddress = "456 Road"
                }
            };

            Transaction transaction = gateway.Transaction.Sale(request).Target;
            TestHelper.Settle(service, transaction.Id);
            transaction = gateway.Transaction.Find(transaction.Id);

            TransactionSearchRequest searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                BillingCompany.Is("Braintree").
                BillingCountryName.Is("United States of America").
                BillingExtendedAddress.Is("Suite 123").
                BillingFirstName.Is(firstName).
                BillingLastName.Is("Smith").
                BillingLocality.Is("Chicago").
                BillingPostalCode.Is("12345").
                BillingRegion.Is("IL").
                BillingStreetAddress.Is("123 Main St").
                CreditCardCardholderName.Is("Tom Smith").
                CreditCardExpirationDate.Is("05/2012").
                CreditCardNumber.Is(SandboxValues.CreditCardNumber.VISA).
                Currency.Is("USD").
                CustomerCompany.Is("Braintree").
                CustomerEmail.Is("*****@*****.**").
                CustomerFax.Is("5551231234").
                CustomerFirstName.Is("Tom").
                CustomerId.Is(transaction.Customer.Id).
                CustomerLastName.Is("Smith").
                CustomerPhone.Is("5551231234").
                CustomerWebsite.Is("http://example.com").
                OrderId.Is("myorder").
                PaymentMethodToken.Is(creditCardToken).
                ProcessorAuthorizationCode.Is(transaction.ProcessorAuthorizationCode).
                SettlementBatchId.Is(transaction.SettlementBatchId).
                ShippingCompany.Is("Braintree P.S.").
                ShippingCountryName.Is("Mexico").
                ShippingExtendedAddress.Is("Apt 456").
                ShippingFirstName.Is("Thomas").
                ShippingLastName.Is("Smithy").
                ShippingLocality.Is("Braintree").
                ShippingPostalCode.Is("54321").
                ShippingRegion.Is("MA").
                ShippingStreetAddress.Is("456 Road").
                User.Is("integration_user_public_id").
                CreditCardUniqueIdentifier.Is(transaction.CreditCard.UniqueNumberIdentifier);

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

            Assert.AreEqual(1, collection.MaximumCount);
            Assert.AreEqual(transaction.Id, collection.FirstItem.Id);
        }
Esempio n. 31
0
        public void Search_OnCreatedAtUsingLocalTime()
        {
            TransactionRequest request = new TransactionRequest
            {
                Amount = SandboxValues.TransactionAmount.AUTHORIZE,
                CreditCard = new TransactionCreditCardRequest
                {
                    Number = SandboxValues.CreditCardNumber.VISA,
                    ExpirationDate = "05/2010"
                }
            };

            Transaction transaction = gateway.Transaction.Sale(request).Target;

            DateTime oneDayEarlier = DateTime.Now.AddDays(-1);
            DateTime oneDayLater = DateTime.Now.AddDays(1);

            TransactionSearchRequest searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                CreatedAt.Between(oneDayEarlier, oneDayLater);

            Assert.AreEqual(1, gateway.Transaction.Search(searchRequest).MaximumCount);
        }
Esempio n. 32
0
        public async Task <ActionResult> Index(CheckoutModel model)
        {
            //Check if the model-state is valid -- this will catch anytime someone hacks your client-side validation
            if (ModelState.IsValid)
            {
                if (model.CustomerId == null)
                {
                    BraintreeService service = new BraintreeService(this._braintreeGateway);
                    model.CustomerId = await service.GetCustomerId(model.Email, model.Phone, model.FirstName, model.LastName);
                }
                if ((model.CardToken == "NewCard") || (model.CardToken == null))
                {
                    Braintree.CreditCardRequest card = new Braintree.CreditCardRequest();
                    card.Number          = model.CreditCardNumber;
                    card.CVV             = model.CreditCardVerificationValue;
                    card.ExpirationMonth = model.CreditCardExpirationMonth.ToString().PadLeft(2, '0');
                    card.ExpirationYear  = model.CreditCardExpirationYear.ToString();
                    card.CardholderName  = model.BillingFirstName + " " + model.BillingLastName;
                    card.CustomerId      = model.CustomerId;
                    var cardResult = await _braintreeGateway.CreditCard.CreateAsync(card);

                    model.CardToken = cardResult.Target.Token;
                }

                if ((model.BillingAddressId == "NewAddress") || (model.BillingAddressId == null))
                {
                    Braintree.AddressRequest address = new Braintree.AddressRequest();
                    address.StreetAddress = model.BillingAddressLine1 + " " + model.BillingAddressLine2;
                    address.CountryName   = model.BillingCountry;
                    address.Locality      = model.BillingCity;
                    address.PostalCode    = model.BillingPostalCode;
                    address.Region        = model.BillingState;

                    var addressResult = await _braintreeGateway.Address.CreateAsync(model.CustomerId, address);

                    model.BillingAddressId = addressResult.Target.Id;
                }
                if ((model.ShippingAddressId == "NewAddress") || (model.ShippingAddressId == null))
                {
                    if ((model.ShippingAddressLine1 == model.BillingAddressLine1) &&
                        (model.ShippingAddressLine2 == model.BillingAddressLine2) &&
                        (model.ShippingCity == model.BillingCity) &&
                        (model.ShippingPostalCode == model.BillingPostalCode) &&
                        (model.ShippingState == model.BillingState) &&
                        (model.ShippingCountry == model.BillingCountry))
                    {
                        model.ShippingAddressId = model.BillingAddressId;
                    }
                    else
                    {
                        Braintree.AddressRequest address = new Braintree.AddressRequest();
                        address.StreetAddress = model.ShippingAddressLine1 + " " + model.ShippingAddressLine2;
                        address.CountryName   = model.ShippingCountry;
                        address.Locality      = model.ShippingCity;
                        address.PostalCode    = model.ShippingPostalCode;
                        address.Region        = model.ShippingState;

                        var addressResult = await _braintreeGateway.Address.CreateAsync(model.CustomerId, address);

                        model.ShippingAddressId = addressResult.Target.Id;
                    }
                }


                Shipment s = new Shipment
                {
                    AddressLine1 = model.ShippingAddressLine1,
                    AddressLine2 = model.ShippingAddressLine2,
                    City         = model.ShippingCity,
                    State        = model.ShippingState,
                    PostalCode   = model.ShippingPostalCode,
                    Country      = model.ShippingCountry,
                    Modified     = DateTime.UtcNow,
                    Created      = DateTime.UtcNow
                };


                Purchase p = new Purchase
                {
                    SubmittedDate    = DateTime.UtcNow,
                    AspNetUserID     = User.Identity.IsAuthenticated ? db.AspNetUsers.First(x => x.UserName == User.Identity.Name).Id : null,
                    Created          = DateTime.UtcNow,
                    Modified         = DateTime.UtcNow,
                    OrderIdentifier  = Guid.NewGuid().ToString().Substring(0, 8),
                    PurchaseProducts = this.GetBasket(db).BasketProducts.Select(x => new Models.PurchaseProduct
                    {
                        ProductID    = x.ProductID,
                        Quantity     = x.Quantity,
                        Created      = DateTime.UtcNow,
                        Modified     = DateTime.UtcNow,
                        ProductName  = x.Product.Name,
                        ProductPrice = x.Product.Price,
                        Shipment     = s,
                    }).ToArray()
                };


                db.Purchases.Add(p);

                db.Baskets.Remove(this.GetBasket(db));
                db.SaveChanges();

                Braintree.TransactionRequest transaction = new Braintree.TransactionRequest();
                transaction.Amount              = this.GetBasket(db).BasketProducts.Sum(x => x.Quantity * (x.Product.Price ?? 0));
                transaction.CustomerId          = model.CustomerId;
                transaction.PaymentMethodToken  = model.CardToken;
                transaction.OrderId             = p.ID.ToString();
                transaction.PurchaseOrderNumber = p.OrderIdentifier;
                var transactionResult = await _braintreeGateway.Transaction.SaleAsync(transaction);

                await _emailService.SendAsync(new Microsoft.AspNet.Identity.IdentityMessage
                {
                    Subject     = string.Format("Your Coding Cookware Order {0}", p.OrderIdentifier),
                    Destination = model.Email,
                    Body        = CreateReceiptEmail(p)
                });

                if (!string.IsNullOrEmpty(model.Phone))
                {
                    await _smsService.SendAsync(new Microsoft.AspNet.Identity.IdentityMessage
                    {
                        Subject     = "",
                        Destination = model.Phone,
                        Body        = "You placed order " + p.OrderIdentifier
                    });
                }

                return(RedirectToAction("Index", "Receipt", new { id = p.OrderIdentifier }));
            }
            ;
            return(View());
        }
Esempio n. 33
0
        public virtual string CreditTrData(TransactionRequest trData, string redirectURL)
        {
            trData.Type = TransactionType.CREDIT;

            return(TrUtil.BuildTrData(trData, redirectURL, service));
        }
Esempio n. 34
0
        public void Search_OnSettledAt()
        {
            TransactionRequest request = new TransactionRequest
            {
                Amount = SandboxValues.TransactionAmount.AUTHORIZE,
                CreditCard = new TransactionCreditCardRequest
                {
                    Number = SandboxValues.CreditCardNumber.VISA,
                    ExpirationDate = "05/2010"
                },
                Options = new TransactionOptionsRequest
                {
                    SubmitForSettlement = true
                }
            };

            Transaction transaction = gateway.Transaction.Sale(request).Target;
            TestHelper.Settle(service, transaction.Id);
            transaction = gateway.Transaction.Find(transaction.Id);

            DateTime threeDaysEarlier = DateTime.Now.AddDays(-3);
            DateTime oneDayEarlier = DateTime.Now.AddDays(-1);
            DateTime oneDayLater = DateTime.Now.AddDays(1);

            TransactionSearchRequest searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                SettledAt.Between(oneDayEarlier, oneDayLater);

            Assert.AreEqual(1, gateway.Transaction.Search(searchRequest).MaximumCount);

            searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                SettledAt.GreaterThanOrEqualTo(oneDayEarlier);

            Assert.AreEqual(1, gateway.Transaction.Search(searchRequest).MaximumCount);

            searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                SettledAt.LessThanOrEqualTo(oneDayLater);

            Assert.AreEqual(1, gateway.Transaction.Search(searchRequest).MaximumCount);

            searchRequest = new TransactionSearchRequest().
                Id.Is(transaction.Id).
                SettledAt.Between(threeDaysEarlier, oneDayEarlier);

            Assert.AreEqual(0, gateway.Transaction.Search(searchRequest).MaximumCount);
        }
        public virtual Result <Transaction> UpdateDetails(string id, TransactionRequest request)
        {
            XmlNode response = service.Put(service.MerchantPath() + "/transactions/" + id + "/update_details", request);

            return(new ResultImpl <Transaction>(new NodeWrapper(response), gateway));
        }
        public virtual Result <Transaction> SubmitForPartialSettlement(string id, TransactionRequest request)
        {
            XmlNode response = service.Post(service.MerchantPath() + "/transactions/" + id + "/submit_for_partial_settlement", request);

            return(new ResultImpl <Transaction>(new NodeWrapper(response), gateway));
        }
Esempio n. 37
0
        public override string ProcessCard(int orderNumber, int customerID, Decimal orderTotal, bool useLiveTransactions, TransactionModeEnum transactionMode, Address useBillingAddress, string cardExtraCode, Address useShippingAddress, string cavv, string eci, string xid, out string avsResult, out string authorizationResult, out string authorizationCode, out string authorizationTransID, out string transactionCommandOut, out string transactionResponse)
        {
            var session = new CustomerSession(customerID);

            string result = AppLogic.ro_OK;

            authorizationCode                       =
                authorizationResult                 =
                    authorizationTransID            =
                        avsResult                   =
                            transactionCommandOut   =
                                transactionResponse = string.Empty;

            var threeDSecureEnabled = AppLogic.AppConfigBool("Braintree.3dSecureEnabled");

            //3dSecure is enabled and this customer hasn't yet been authed - send them to the 3dSecure form
            if (threeDSecureEnabled &&
                session[AppLogic.Braintree3dSecureKey].EqualsIgnoreCase("false") &&
                session[AppLogic.BraintreePaymentMethod].EqualsIgnoreCase("creditcard"))
            {
                session["3DSecure.OrderNumber"] = orderNumber.ToString();
                return(AppLogic.ro_3DSecure);
            }

            var nonce = session[AppLogic.BraintreeNonceKey];

            var gateway = CreateBraintreeGateway();

            var transactionRequest = new GWBraintree.TransactionRequest
            {
                OrderId            = orderNumber.ToString(),
                Amount             = Math.Round(orderTotal, 2),     //They only accept up to 2 decimal places
                PaymentMethodNonce = nonce,
                Options            = new GWBraintree.TransactionOptionsRequest
                {
                    SubmitForSettlement = AppLogic.TransactionModeIsAuthCapture(),
                    ThreeDSecure        = (threeDSecureEnabled && session[AppLogic.Braintree3dSecureKey] == "true")                 //Don't add this if the card wasn't enrolled
                                        ? new GWBraintree.TransactionOptionsThreeDSecureRequest()
                    {
                        Required = threeDSecureEnabled
                    }
                                        : null
                },
                //Add address info in case the merchant has turned on AVS settings in their Braintree account
                BillingAddress = new GWBraintree.AddressRequest
                {
                    FirstName       = useBillingAddress.FirstName,
                    LastName        = useBillingAddress.LastName,
                    StreetAddress   = useBillingAddress.Address1,
                    ExtendedAddress = useBillingAddress.Address2,
                    Locality        = useBillingAddress.City,
                    Region          = useBillingAddress.State,
                    PostalCode      = useBillingAddress.Zip,
                    CountryName     = useBillingAddress.Country
                },
                Channel = BN
            };

            var transactionResult = gateway.Transaction.Sale(transactionRequest);

            if (transactionResult.IsSuccess())
            {
                authorizationTransID = transactionResult.Target.Id;
                authorizationCode    = transactionResult.Target.ProcessorAuthorizationCode ?? string.Empty;
                authorizationResult  = transactionResult.Target.ProcessorResponseText ?? string.Empty;
                avsResult            = transactionResult.Target.AvsPostalCodeResponseCode ?? string.Empty;

                //We don't have any card details yet - fill some of that in with what Braintree gives us back.
                if (transactionResult.Target.PaymentInstrumentType == GWBraintree.PaymentInstrumentType.CREDIT_CARD)
                {
                    useBillingAddress.CardNumber          = transactionResult.Target.CreditCard.LastFour;
                    useBillingAddress.CardType            = transactionResult.Target.CreditCard.CardType.ToString().ToUpperInvariant();
                    useBillingAddress.CardExpirationMonth = transactionResult.Target.CreditCard.ExpirationMonth;
                    useBillingAddress.CardExpirationYear  = transactionResult.Target.CreditCard.ExpirationYear;
                    useBillingAddress.UpdateDB();
                }
            }
            else
            {
                result = transactionResult.Message;
            }

            return(result);
        }
        public TransactionResult Pay(
            string paymentMethodNonce,
            decimal amount,
            Dictionary <string, string> customFields)
        {
            var config = _orchardServices.WorkContext
                         .CurrentSite.As <BraintreeSiteSettingsPart>();
            string            merchant = config?.MerchantAccountId;
            TransactionResult result   = new TransactionResult();
            var request = new Bt.TransactionRequest {
                Amount             = amount,
                PaymentMethodNonce = paymentMethodNonce,
                MerchantAccountId  = merchant
            };

            if (customFields != null)
            {
                request.CustomFields = customFields;
            }
            var gateway = GetGateway();

            Bt.Result <Bt.Transaction> payResult = gateway.Transaction.Sale(request);
            Bt.Transaction             tran      = null;
            result.Success = payResult.IsSuccess();
            if (payResult.Target != null)
            {
                // caso success == true
                tran = payResult.Target;
            }
            else if (payResult.Transaction != null)
            {
                // caso success == false
                tran = payResult.Transaction;
            }
            if (tran != null)
            {
                result.Amount            = tran.Amount.Value;
                result.AuthorizationCode = tran.ProcessorAuthorizationCode;
                if (tran.BillingAddress != null)
                {
                    result.BillingAddress = string.Format("{0} - {1} {2} - {3} {4} - {5} {6} {7} - {8}",
                                                          tran.BillingAddress.Company,
                                                          tran.BillingAddress.FirstName,
                                                          tran.BillingAddress.LastName,
                                                          tran.BillingAddress.StreetAddress,
                                                          tran.BillingAddress.ExtendedAddress,
                                                          tran.BillingAddress.PostalCode,
                                                          tran.BillingAddress.Locality,
                                                          tran.BillingAddress.Region,
                                                          tran.BillingAddress.CountryName);
                }
                result.CurrencyIsoCode = tran.CurrencyIsoCode;
                if (tran.Customer != null)
                {
                    result.Customer = string.Format("{0} {1}, {2}, ({3})",
                                                    tran.Customer.FirstName,
                                                    tran.Customer.LastName,
                                                    tran.Customer.Company,
                                                    tran.Customer.Email);
                }
                result.MerchantAccountId   = tran.MerchantAccountId;
                result.OrderId             = tran.OrderId;
                result.PurchaseOrderNumber = tran.PurchaseOrderNumber;
                result.ResponseCode        = tran.ProcessorResponseCode;
                result.ResponseText        = tran.ProcessorResponseText;
                result.Status        = tran.Status.ToString();
                result.TransactionId = tran.Id;
                result.Type          = tran.Type.ToString();
            }
            result.Details = JsonConvert.SerializeObject(payResult);
            return(result);
        }
        public virtual async Task <Result <Transaction> > SubmitForSettlementAsync(string id, TransactionRequest request)
        {
            XmlNode response = await service.PutAsync(service.MerchantPath() + "/transactions/" + id + "/submit_for_settlement", request).ConfigureAwait(false);

            return(new ResultImpl <Transaction>(new NodeWrapper(response), gateway));
        }
Esempio n. 40
0
        public virtual String SaleTrData(TransactionRequest trData, String redirectURL)
        {
            trData.Type = TransactionType.SALE;

            return TrUtil.BuildTrData(trData, redirectURL, Service);
        }