Exemple #1
0
        public ActionResult Charge(string stripeToken, string stripeEmail)
        {
            T_Members m = new T_Members();



            StripeConfiguration.ApiKey = "sk_test_LxFXRsxnoaNeykNC7ucJ3ztg006XowH6fy";



            var myCharge = new ChargeCreateOptions();
            {
                // always set these properties


                myCharge.Amount = (int)Session["total"];

                myCharge.Currency     = "INR";
                myCharge.ReceiptEmail = stripeEmail;
                myCharge.Description  = "Sample Charge";
                myCharge.Source       = stripeToken;
                myCharge.Capture      = true;


                myCharge.Metadata = new Dictionary <string, string>
                {
                    { "MemberId", "6735" },
                };
            }

            var    chargeService = new Stripe.ChargeService();
            Charge stripeCharge  = chargeService.Create(myCharge);

            return(View());
        }
Exemple #2
0
        static void Main(string[] args)
        {
            RepoDb.SqlServerBootstrap.Initialize();

            var repo = new PaymentIntentRepository();

            var data = repo.GetAll(0, 3000);

            StripeConfiguration.ApiKey = ConfigurationManager.AppSettings["Cashier:Stripe:Secret"];

            var chargeApi = new Stripe.ChargeService();
            var charges   = chargeApi.List(new ChargeListOptions
            {
                Limit = 5000
            });

            foreach (var item in data)
            {
                var paymentMethodApi = new Stripe.PaymentMethodService();
                var paymentIntentApi = new Stripe.PaymentIntentService();
                var invoiceApi       = new Stripe.InvoiceService();
                if (item.ExternalReference?.StartsWith("pi_") ?? true)
                {
                    continue;
                }

                var payment = charges.FirstOrDefault(p => p.PaymentMethod == item.ExternalReference);

                if (payment != null && !string.IsNullOrEmpty(payment.PaymentIntentId))
                {
                    item.ExternalReference = payment.PaymentIntentId;
                    repo.SavePaymentIntent(item);
                }
            }
        }
Exemple #3
0
        public async Task <Charge> Charge(ChargeDTO charge)
        {
            var idClaim = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

            if (!long.TryParse(idClaim, out var ownerId))
            {
                throw new UnauthorizedAccessException();
            }

            var ownerUser = await _userRepository.GetByIdAsync(ownerId);

            var customers = new CustomerService();
            var charges   = new Stripe.ChargeService();

            var customer = await customers.CreateAsync(new CustomerCreateOptions
            {
                Email       = ownerUser.Email,
                SourceToken = charge.Token
            });

            var newCharge = await charges.CreateAsync(new ChargeCreateOptions
            {
                Amount      = charge.Value,
                Description = "Test charge",
                Currency    = charge.Currency,
                CustomerId  = customer.Id
            });

            return(newCharge);
        }
        public async Task <List <string> > GetPayoutTransactionsAsync(string accountId, string payoutId)
        {
            var result = new List <string>();

            var balanceTransactionService = new BalanceTransactionService();
            var chargeService             = new Stripe.ChargeService();
            var transferService           = new Stripe.TransferService();

            var requestOptions = new RequestOptions {
                StripeAccount = accountId
            };

            var transactions = await balanceTransactionService.ListAsync(new BalanceTransactionListOptions { Payout = payoutId, Type = "payment", Limit = 100 }, requestOptions);

            foreach (var transaction in transactions)
            {
                var payment = await chargeService.GetAsync(transaction.SourceId, null, requestOptions);

                var transfer = await transferService.GetAsync(payment.SourceTransferId);

                result.Add(transfer.SourceTransactionId);
            }

            return(result);
        }
Exemple #5
0
        public ActionResult Charge(string stripeEmail, string stripeToken)
        {
            //string secretKey = ConfigurationManager.AppSettings["Stripe:secretKey"];
            string secretKey = "sk_test_e3ssfSIQhhvg7DtlMpHLxMKm";

            StripeConfiguration.SetApiKey(secretKey);

            Stripe.CustomerCreateOptions myCustomer = new Stripe.CustomerCreateOptions();
            myCustomer.Email  = stripeEmail;
            myCustomer.Source = stripeToken;
            var customerService = new Stripe.CustomerService();

            Stripe.Customer stripeCustomer = customerService.Create(myCustomer);

            var options = new Stripe.ChargeCreateOptions
            {
                Amount       = 1000,
                Currency     = "USD",
                Description  = "Buying 10 rubber ducks",
                Source       = stripeToken,
                ReceiptEmail = stripeEmail
            };
            //and Create Method of this object is doing the payment execution.
            var service = new Stripe.ChargeService();

            //Stripe.Charge charge = service.Create(options);

            return(RedirectToAction(nameof(Index)));
        }
        public IActionResult Payment(string stripeToken)
        {
            // retriever order from session
            var order = HttpContext.Session.GetObject <Models.Order>("Order");

            // 1. create Stripe customer
            var customerService = new Stripe.CustomerService();
            var charges         = new Stripe.ChargeService();

            StripeConfiguration.ApiKey = _iconfiguration["Stripe:SecretKey"];
            Stripe.Customer customer = customerService.Create(new Stripe.CustomerCreateOptions
            {
                Source = stripeToken,
                Email  = User.Identity.Name
            });

            // 2. create Stripe charge
            var charge = charges.Create(new Stripe.ChargeCreateOptions
            {
                Amount      = Convert.ToInt32(order.Total * 100),
                Description = "COMP2084 Beer Store Purchase",
                Currency    = "cad",
                Customer    = customer.Id
            });

            // 3. save a new order to our db
            _context.Orders.Add(order);
            _context.SaveChanges();

            // 4. save the cart items as new OrderDetails to our db
            var cartItems = _context.Carts.Where(c => c.CustomerId == HttpContext.Session.GetString("CartUsername"));

            foreach (var item in cartItems)
            {
                var orderDetail = new OrderDetail
                {
                    OrderId   = order.Id,
                    ProductId = item.ProductId,
                    Quantity  = item.Quantity,
                    Cost      = item.Price
                };

                _context.OrderDetails.Add(orderDetail);
            }

            _context.SaveChanges();

            // 5. delete the cart items from this order
            foreach (var item in cartItems)
            {
                _context.Carts.Remove(item);
            }

            _context.SaveChanges();

            // 6. load an order confirmation page
            return(RedirectToAction("Details", "Orders", new { @id = order.Id }));
        }
Exemple #7
0
        public IActionResult Payment(string stripeEmail, string stripeToken)
        {
            //get secret key from configuration and pass to stripe API
            StripeConfiguration.ApiKey = _iconfiguration.GetSection("Stripe")["SecretKey"];
            var cartUsername = User.Identity.Name;
            var cartItems    = _context.Carts.Where(c => c.Username == cartUsername).ToList();
            var order        = HttpContext.Session.GetObject <Orders>("Order");

            //invoke stripe payment attempt
            var customerService = new Stripe.CustomerService();
            var charges         = new Stripe.ChargeService();

            Stripe.Customer customer = customerService.Create(new Stripe.CustomerCreateOptions
            {
                Source = stripeToken,
                Email  = stripeEmail
            });

            var charge = charges.Create(new Stripe.ChargeCreateOptions
            {
                Amount      = Convert.ToInt32(order.Total * 100),
                Description = "Sample Charge",
                Currency    = "cad",
                Customer    = customer.Id
            });

            //save the order
            _context.Orders.Add(order);
            _context.SaveChanges();

            //save the order details
            foreach (var item in cartItems)
            {
                var orderDetail = new OrderDetails
                {
                    OrderId   = order.OrderId,
                    ProductId = item.ProductId,
                    Quantity  = item.Quantity,
                    Price     = item.Price
                };

                _context.OrderDetails.Add(orderDetail);
            }

            _context.SaveChanges();

            //empty the cart
            foreach (var item in cartItems)
            {
                _context.Carts.Remove(item);
            }

            _context.SaveChanges();


            return(RedirectToAction("Details", "Orders", new { id = order.OrderId }));
        }
        public async Task <Charge> CreateCaptureAsync(string chargeId, decimal amount, decimal applicationFeeAmount)
        {
            var options = new Stripe.ChargeCaptureOptions
            {
                Amount = (long)(amount * 100),
                ApplicationFeeAmount = (long)(applicationFeeAmount * 100)
            };

            var service = new Stripe.ChargeService();

            return(await service.CaptureAsync(chargeId, options));
        }
        public ActionResult Charge(string stripeToken, string stripeEmail)
        {
            try
            {
                ApplicationDbContext db = new ApplicationDbContext();
                if (Request["OrderId"] != null)
                {
                    int           orderId = int.Parse(Request["orderId"].ToString()); //it requests an order Id from the front
                    CustomerOrder o       = db.Orders.Find(orderId);                  //the order is found in the database by its Id

                    //the orders properties are adjusted appropriately
                    o.Payment = true;// the order is set to 'Paid'
                    o.Pay(o.Id);
                    //the next block finds each product in the order and adjusts their stock levels
                    o.BasketItems = o.GetItems(o.Id);
                    foreach (Basket b in o.BasketItems)
                    {
                        b.GetProduct();
                        int stock = b.Product.Stock - b.Quantity;

                        o.SetStock(b.Product.Id, stock);
                    }

                    //to follow are all the properties of a strip payment

                    Stripe.StripeConfiguration.SetApiKey("pk_test_veUj82xPax3gnKyiqk9losrd00QfIrd1o2");
                    Stripe.StripeConfiguration.ApiKey = "sk_test_wHoSwq3TOM5ZJkaKQrG9GWjo00uhPcOhUa";

                    var myCharge = new Stripe.ChargeCreateOptions();
                    // always set these properties
                    myCharge.Amount       = (long.Parse(Request["Total"].ToString())); //the total is requested from the front
                    myCharge.Currency     = "gbp";                                     //currency
                    myCharge.ReceiptEmail = stripeEmail;
                    myCharge.Description  = "Sample Charge";
                    myCharge.Source       = stripeToken;
                    myCharge.Capture      = true;
                    var    chargeService = new Stripe.ChargeService();
                    Charge stripeCharge  = chargeService.Create(myCharge);
                    return(View());
                }
                //this will redirect to the ViewBasket page if the order id is not found for any reason
                else
                {
                    return(RedirectToAction("ViewBasket, User"));
                }
            }
            //this is a failsafe to send users to their order page if the abouv code doesnt execute properly
            catch
            {
                return(RedirectToAction("SeeOrders, Order"));
            }
        }
Exemple #10
0
        public static stripe.Charge CreateCapture(this CapturePaymentRequest capturePaymentRequest, StripePaymentSettings stripePaymentSettings, Store store)
        {
            var chargesService = new stripe.ChargeService(stripePaymentSettings.GetStripeClient());

            var chargeId = capturePaymentRequest.Order.AuthorizationTransactionId;

            stripe.Charge charge = chargesService.Capture(chargeId, new stripe.ChargeCaptureOptions()
            {
                StatementDescriptor = $"{store.Name.ToStripeDescriptor()}"
            });

            return(charge);
        }
        public ActionResult Charge(string stripeEmail, string stripeToken, int?Id)
        {
            StripeConfiguration.ApiKey = "sk_test_uOveI2SFAXbU4XnnSunDN8kN00Q2y172o5";
            var            deals    = db.Deals;
            List <Vehicle> vehicles = db.Vehicles.ToList();

            foreach (var d in deals)
            {
                var     v      = d.VehicleId;
                Vehicle vozilo = vehicles.Where(ve => ve.Id == v).First(); //izbereno vozilo
                var     total  = vozilo.Price * (d.DateTo.DayOfYear - d.DateFrom.DayOfYear);
            }

            var customers = new Stripe.CustomerService();
            var charges   = new Stripe.ChargeService();

            var customer = customers.Create(new Stripe.CustomerCreateOptions
            {
                Email  = stripeEmail,
                Source = stripeToken
            });
            Deal deal = new Deal();

            int  ivona = Convert.ToInt32(Id);
            Deal deal1 = db.Deals.Where(de => de.Id == Id).First();

            Session["price"] = deal1.TotalPrice;
            long totalStripes = Convert.ToInt64(Session["price"]);

            deal1.plateno = true;
            db.SaveChanges();
            deal.plateno = true;

            var charge = charges.Create(new Stripe.ChargeCreateOptions
            {
                Amount       = totalStripes * 100,
                Description  = "Description for Stripe implmentation",
                Currency     = "mkd",
                Customer     = customer.Id,
                ReceiptEmail = stripeEmail,
                Metadata     = new Dictionary <string, string>
                {
                    { "OrderID", deal.Id.ToString() },
                    { "PostCode", "2300" }
                }
            });

            return(View());
        }
Exemple #12
0
        public static stripe.Charge CreateCharge(this ProcessPaymentRequest processPaymentRequest, StripePaymentSettings stripePaymentSettings, CurrencySettings currencySettings, Store store,
                                                 ICustomerService customerService, ICurrencyService currencyService, IGenericAttributeService genericAttributeService)
        {
            int substep = 0;

            try
            {
                var customer = customerService.GetCustomerById(processPaymentRequest.CustomerId);
                if (customer == null)
                {
                    throw new NopException("Customer cannot be loaded");
                }
                substep = 1;
                var currency = currencyService.GetCurrencyById(currencySettings.PrimaryStoreCurrencyId);
                if (currency == null)
                {
                    throw new NopException("Primary store currency cannot be loaded");
                }
                substep = 2;
                if (!Enum.TryParse(currency.CurrencyCode, out StripeCurrency stripeCurrency))
                {
                    throw new NopException($"The {currency.CurrencyCode} currency is not supported by Stripe");
                }
                substep = 3;

                var stripeCustomerService = new stripe.CustomerService(stripePaymentSettings.GetStripeClient());
                var chargeService         = new stripe.ChargeService(stripePaymentSettings.GetStripeClient());
                var tokenService          = new stripe.TokenService(stripePaymentSettings.GetStripeClient());
                substep = 4;
                var stripeCustomer = stripeCustomerService.GetOrCreateCustomer(customer, genericAttributeService, stripePaymentSettings);
                substep = 5;
                var tokenOptions = processPaymentRequest.CreateTokenOptions(customer, stripeCurrency);
                substep = 6;
                var token = tokenService.Create(tokenOptions);
                substep = 7;
                var chargeOptions = processPaymentRequest.CreateChargeOptions(store, token, stripePaymentSettings.TransactionMode, stripeCurrency);
                substep = 8;

                var charge = chargeService.Create(chargeOptions);
                substep = 9;
                return(charge);
            }
            catch (Exception ex)
            {
                throw new Exception($"Failed at substep {substep}", ex);
            }
        }
Exemple #13
0
        public static stripe.Charge CreateCharge(this ProcessPaymentRequest processPaymentRequest,
                                                 StripePaymentSettings stripePaymentSettings,
                                                 CurrencySettings currencySettings,
                                                 Store store,
                                                 ICustomerService customerService,
                                                 IStateProvinceService stateProvinceService,
                                                 ICountryService countryService,
                                                 ICurrencyService currencyService,
                                                 IGenericAttributeService genericAttributeService)
        {
            var customer = customerService.GetCustomerById(processPaymentRequest.CustomerId);

            if (customer == null)
            {
                throw new NopException("Customer cannot be loaded");
            }

            var currency = currencyService.GetCurrencyById(currencySettings.PrimaryStoreCurrencyId);

            if (currency == null)
            {
                throw new NopException("Primary store currency cannot be loaded");
            }

            if (!Enum.TryParse(currency.CurrencyCode, out StripeCurrency stripeCurrency))
            {
                throw new NopException($"The {currency.CurrencyCode} currency is not supported by Stripe");
            }


            var stripeCustomerService = new stripe.CustomerService(stripePaymentSettings.GetStripeClient());
            var chargeService         = new stripe.ChargeService(stripePaymentSettings.GetStripeClient());
            var tokenService          = new stripe.TokenService(stripePaymentSettings.GetStripeClient());

            var stripeCustomer = stripeCustomerService.GetOrCreateCustomer(customer, genericAttributeService, stripePaymentSettings);

            var tokenOptions  = processPaymentRequest.CreateTokenOptions(customerService, stateProvinceService, countryService, stripeCurrency);
            var token         = tokenService.Create(tokenOptions);
            var chargeOptions = processPaymentRequest.CreateChargeOptions(store, token, stripePaymentSettings.TransactionMode, stripeCurrency);

            var charge = chargeService.Create(chargeOptions);

            return(charge);
        }
Exemple #14
0
        public ActionResult Charge(string stripeToken, string stripeEmail)
        {
            Stripe.StripeConfiguration.SetApiKey("pk_test_51IBkDtCJuzxdYhOtyq9CXeZq4YYCXwlntkpwWloLKsmRJ9RiTKMW0UWriwsfbk1mFIK7IklimZQuDDkQTc2fvfdr00jHEdU28M");
            Stripe.StripeConfiguration.ApiKey = "sk_test_51IBkDtCJuzxdYhOtnAcKUjVmnkHNrG9BvNTd666CsYqe8wm4H4D9VtttOSPb0sst5X6vJhCz2NWpTWSccloeFlfp00zpv1gwFX";

            var myCharge = new Stripe.ChargeCreateOptions();

            // always set these properties
            myCharge.Amount       = 500;
            myCharge.Currency     = "USD";
            myCharge.ReceiptEmail = stripeEmail;
            myCharge.Description  = "Sample Charge";
            myCharge.Source       = stripeToken;
            myCharge.Capture      = true;
            var    chargeService = new Stripe.ChargeService();
            Charge stripeCharge  = chargeService.Create(myCharge);

            return(View());
        }
        public ActionResult Charge(string stripeEmail, string stripeToken, decimal amount, string orderId)
        {
            var customers = new CustomerService();
            var charges   = new Stripe.ChargeService();

            amount = (long)amount;

            var             userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
            ApplicationUser user        = userManager.FindByNameAsync(User.Identity.Name).Result;

            var customer = customers.Create(options: new Stripe.CustomerCreateOptions
            {
                Email  = stripeEmail,
                Source = stripeToken,
                Name   = user.UserName
            });

            var charge = charges.Create(new Stripe.ChargeCreateOptions
            {
                Amount      = (long)amount,//charge in cents
                Description = "Sample Charge",
                Currency    = "usd",
                Customer    = customer.Id
            });

            if (charge.Status == "succeeded" && charge.Paid == true)
            {
                if (ModelState.IsValid)
                {
                    var order = HttpContext.GetOwinContext().Get <ApplicationDbContext>().Orders.Find(orderId);
                    order.PaymentStatus = PaymentStatusEnum.Paid;
                    HttpContext.GetOwinContext().Get <ApplicationDbContext>().Entry(order).State = EntityState.Modified;
                    HttpContext.GetOwinContext().Get <ApplicationDbContext>().SaveChanges();

                    ViewBag.Message = order;
                    ViewBag.Msg     = "Payment is successful!";
                    return(View("~/Views/Checkout/StripeCharge.cshtml"));
                }
            }

            ViewBag.Msg = "Payment is not successful!";
            return(View("~/Views/Checkout/StripeCharge.cshtml"));
        }
        public static Charge StripePaymentsForm(string Email, string stripeToken, string Price)
        {
            var customerService = new Stripe.CustomerService();
            var chargeService   = new Stripe.ChargeService();
            var priceConverted  = decimal.Parse(Price) * 100;
            var customer        = customerService.Create(new Stripe.CustomerCreateOptions
            {
                Email  = Email,
                Source = stripeToken,
            });

            return(chargeService.Create(new Stripe.ChargeCreateOptions
            {
                Amount = (long)priceConverted,
                Description = "Spartan Boosting",
                Currency = "EUR",
                Customer = customer.Id
            }));
        }
Exemple #17
0
        public ActionResult Charge(string stripeToken, string stripeEmail)
        {
            Stripe.StripeConfiguration.SetApiKey("pk_test_51ITYUZKuxtPIEeD5qxXEmosvcdrfrhZNcUJzOb6DzZ5WxX6j5a3KaJ1BzTEvyfovHw7La921Z8gAkm1w7haPXIYb00pl5lcmuV");
            Stripe.StripeConfiguration.ApiKey = "sk_test_51ITYUZKuxtPIEeD5lsPmKh2sG7jhzhhOpuBjXgXg4PL8cdjL79dL038v5SXcR32Ro9yIRxpfX6KfPQrQSxmR1h1p00xID5MdR4";


            var myCharge = new Stripe.ChargeCreateOptions();

            // always set these properties
            myCharge.Amount       = 500;
            myCharge.Currency     = "USD";
            myCharge.ReceiptEmail = stripeEmail;
            myCharge.Description  = "Sample Charge";
            myCharge.Source       = stripeToken;
            myCharge.Capture      = true;
            var    chargeService = new Stripe.ChargeService();
            Charge stripeCharge  = chargeService.Create(myCharge);

            return(View());
        }
Exemple #18
0
        public ActionResult Charge(string stripeToken, string stripeEmail)
        {
            Stripe.StripeConfiguration.SetApiKey("stripePublishableKey");
            Stripe.StripeConfiguration.ApiKey = "stripeSecretKey";

            AppointmentFormViewModel GetProductPrice = new AppointmentFormViewModel();

            var myCharge = new Stripe.ChargeCreateOptions();

            // always set these properties
            myCharge.Amount       = 100 * (long)context.Products.SingleOrDefault(p => p.Id == GetProductPrice.Product).Price;
            myCharge.Currency     = "eur";
            myCharge.ReceiptEmail = stripeEmail;
            myCharge.Description  = GetProductPrice.Product.ToString();
            myCharge.Source       = stripeToken;
            myCharge.Capture      = true;
            var    chargeService = new Stripe.ChargeService();
            Charge stripeCharge  = chargeService.Create(myCharge);

            return(View());
        }
        public async Task <Charge> CreateChargeAsync(string customerId, string source, string destination, string description, decimal totalAmount, decimal applicationFeeAmount, Dictionary <string, string> metadata)
        {
            var options = new ChargeCreateOptions
            {
                Customer             = customerId,
                Source               = source,
                Description          = description,
                Amount               = (long)(totalAmount * 100),
                ApplicationFeeAmount = (long)(applicationFeeAmount * 100),
                TransferData         = new ChargeTransferDataOptions {
                    Destination = destination
                },
                Currency = "usd",
                Capture  = false,
                Metadata = metadata
            };

            var service = new Stripe.ChargeService();

            return(await service.CreateAsync(options));
        }
        public ActionResult Custom(CustomViewModel customViewModel)
        {
            customViewModel.PaymentForHidden = false;
            var chargeOptions = new Stripe.ChargeCreateOptions()
            {
                //required
                Amount   = 3900,
                Currency = "usd",
                //Source = new StripeSourceOptions() { TokenId = customViewModel.StripeToken },


                //SourceTokenOrExistingSourceId = customViewModel.StripeToken,
                //optional
                Description  = string.Format("JavaScript Framework Guide Ebook for {0}", customViewModel.StripeEmail),
                ReceiptEmail = customViewModel.StripeEmail
            };

            var chargeService = new Stripe.ChargeService();

            try
            {
                var stripeCharge = chargeService.Create(chargeOptions);
            }
            catch (StripeException stripeException)
            {
                Debug.WriteLine(stripeException.Message);
                ModelState.AddModelError(string.Empty, stripeException.Message);
                return(View(customViewModel));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                ModelState.AddModelError(string.Empty, ex.Message);
                return(View(customViewModel));
            }

            //LOG stripeCharge log Id property in to the DB to refrence the transaction later

            return(RedirectToAction("Confirmation"));
        }
 public StripeService()
 {
     _stripeChargeService = new Stripe.ChargeService();
 }
Exemple #22
0
        public ActionResult Charge(StripeChargeModel model)
        { //    4242424242424242
            string errormessage  = "";
            bool   isvalidemail  = false;
            bool   isvalidamount = false;
            HttpResponseMessage responseMessage = new HttpResponseMessage();

            try
            {
                var  addr       = new System.Net.Mail.MailAddress(model.Email);
                bool emailvalid = (addr.Address == model.Email);
                isvalidemail = true;
            }
            catch
            {
                errormessage += "invalid email\r\n";
                isvalidemail  = false;
            }

            if (model.Amount == 0)
            {
                isvalidamount = false;
                errormessage += "invalid amount\r\n";
            }
            else
            {
                isvalidamount = true;
            }



            if (isvalidamount == true && isvalidemail == true)
            {
                try
                {
                    string Name            = model.CardHolderName;
                    string CardNumber      = model.CardNum;
                    long   ExpirationYear  = long.Parse(model.Expyear);
                    long   ExpirationMonth = long.Parse(model.ExpMonth);
                    string CVV2            = model.CVV;
                    string Buyer_Email     = model.Email;
                    int    amount          = (int)model.Amount;


                    Stripe.StripeConfiguration.SetApiKey("sk_test_KVelkjylnQQPOkrHSSu8gCft00dODAP1ie");

                    Stripe.CreditCardOptions card = new Stripe.CreditCardOptions();

                    card.Name = Name;

                    card.Number = CardNumber;

                    card.ExpYear = ExpirationYear;

                    card.ExpMonth       = ExpirationMonth;
                    card.AddressLine1   = model.AddressLine1;
                    card.AddressLine2   = model.AddressLine2;
                    card.AddressState   = model.AddressCity;
                    card.AddressCountry = model.AddressCountry;
                    card.AddressZip     = model.AddressPostcode;
                    card.Cvc            = CVV2;

                    // set card to token object and create token

                    Stripe.TokenCreateOptions tokenCreateOption = new Stripe.TokenCreateOptions();

                    tokenCreateOption.Card = card;

                    Stripe.TokenService tokenService = new Stripe.TokenService();

                    Stripe.Token token = tokenService.Create(tokenCreateOption);

                    //create customer object then register customer on Stripe

                    Stripe.CustomerCreateOptions customer = new Stripe.CustomerCreateOptions();

                    customer.Email = Buyer_Email;

                    var custService = new Stripe.CustomerService();

                    Stripe.Customer stpCustomer = custService.Create(customer);
                    //create credit card charge object with details of charge

                    var options = new Stripe.ChargeCreateOptions
                    {
                        Amount = (int)(amount * 100),

                        //                    Amount = (int)(model.Amount * 100),
                        //                    Currency = "gbp",
                        //                    Description = "Description for test charge",
                        //                    Source = model.Token
                        Currency = "gbp",

                        ReceiptEmail = Buyer_Email,

                        Source      = model.Token,
                        Description = "Description for test charge"
                    };

                    //and Create Method of this object is doing the payment execution.

                    var service = new Stripe.ChargeService();

                    Stripe.Charge charge = service.Create(options); // This will do the Payment            }
                    return(new HttpStatusCodeResult(HttpStatusCode.OK, "Success"));
                }
                catch
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "error :  " + errormessage));
                }
            }
            else
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "error :  " + errormessage));
            }
        }
        public async Task <IActionResult> SummaryPost(string stripeToken)
        {
            var claimsIdentity = (ClaimsIdentity)User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);


            detailCart.listCart = await _db.ShoppingCart.Where(c => c.ApplicationUserId == claim.Value).ToListAsync();

            detailCart.OrderHeader.PaymentStatus = SD.PaymentStatusPending;
            detailCart.OrderHeader.OrderDate     = DateTime.Now;
            detailCart.OrderHeader.UserId        = claim.Value;
            detailCart.OrderHeader.Status        = SD.PaymentStatusPending;
            detailCart.OrderHeader.PickUpTime    = Convert.ToDateTime(detailCart.OrderHeader.PickUpDate.ToShortDateString() + " " + detailCart.OrderHeader.PickUpTime.ToShortTimeString());

            List <OrderDetails> orderDetailsList = new List <OrderDetails>();

            _db.OrderHeader.Add(detailCart.OrderHeader);
            await _db.SaveChangesAsync();

            detailCart.OrderHeader.OrderTotalOriginal = 0;


            foreach (var item in detailCart.listCart)
            {
                item.MenuItem = await _db.MenuItem.FirstOrDefaultAsync(m => m.Id == item.MenuItemId);

                OrderDetails orderDetails = new OrderDetails
                {
                    MenuItemId  = item.MenuItemId,
                    OrderId     = detailCart.OrderHeader.Id,
                    Description = item.MenuItem.Description,
                    Name        = item.MenuItem.Name,
                    Price       = item.MenuItem.Price,
                    Count       = item.Count
                };
                detailCart.OrderHeader.OrderTotalOriginal += orderDetails.Count * orderDetails.Price;
                _db.OrderDetails.Add(orderDetails);
            }

            if (HttpContext.Session.GetString(SD.ssCouponCode) != null)
            {
                detailCart.OrderHeader.CouponCode = HttpContext.Session.GetString(SD.ssCouponCode);
                var couponFromDb = await _db.Coupon.Where(c => c.Name.ToLower() == detailCart.OrderHeader.CouponCode.ToLower()).FirstOrDefaultAsync();

                detailCart.OrderHeader.OrderTotal = SD.DiscountedPrice(couponFromDb, detailCart.OrderHeader.OrderTotalOriginal);
            }
            else
            {
                detailCart.OrderHeader.OrderTotal = detailCart.OrderHeader.OrderTotalOriginal;
            }
            detailCart.OrderHeader.CouponCodeDiscount = detailCart.OrderHeader.OrderTotalOriginal - detailCart.OrderHeader.OrderTotal;

            _db.ShoppingCart.RemoveRange(detailCart.listCart);
            HttpContext.Session.SetInt32(SD.ssShoppingCartCount, 0);
            await _db.SaveChangesAsync();

            var options = new ChargeCreateOptions
            {
                Amount      = Convert.ToInt32(detailCart.OrderHeader.OrderTotal * 100),
                Currency    = "usd",
                Description = "Order ID : " + detailCart.OrderHeader.Id,
                SourceId    = stripeToken,
            };
            var    service = new Stripe.ChargeService();
            Charge charge  = service.Create(options);

            if (charge.BalanceTransactionId == null)
            {
                detailCart.OrderHeader.PaymentStatus = SD.PaymentStatusRejected;
            }
            else
            {
                detailCart.OrderHeader.TransactionId = charge.BalanceTransactionId;
            }

            if (charge.Status.ToLower() == "succeeded")
            {
                detailCart.OrderHeader.PaymentStatus = SD.PaymentStatusApproved;
                detailCart.OrderHeader.Status        = SD.StatusSubmitted;
            }
            else
            {
                detailCart.OrderHeader.PaymentStatus = SD.PaymentStatusRejected;
            }

            await _db.SaveChangesAsync();

            return(RedirectToAction("Index", "Home"));
        }
        public ViewResult makePayment(PaymentInformation cardInfo)
        {
            try
            {
                Stripe.StripeConfiguration.SetApiKey("sk_test_51HqI05B1UsJ4lZg1agboQSE7i0fWn98619xc2FP5NhREH4igqo1AlKTQO8VWMfsQBUs1OlXNBzBkOqORRQP6ZlPf00E2l0QVhL");



                Stripe.CreditCardOptions card = new Stripe.CreditCardOptions();
                card.Name     = cardInfo.CardOwnerFirstName + " " + cardInfo.CardOwnerLastName;
                card.Number   = cardInfo.CardNumber;
                card.ExpYear  = cardInfo.ExpirationYear;
                card.ExpMonth = cardInfo.ExpirationMonth;
                card.Cvc      = cardInfo.CVV2;

                Console.WriteLine(TotalPrice.ToString());


                Stripe.TokenCreateOptions token = new Stripe.TokenCreateOptions();
                token.Card = card;
                Stripe.TokenService serviceToken = new Stripe.TokenService();
                Stripe.Token        newToken     = serviceToken.Create(token);

                Stripe.CustomerCreateOptions myCustomer = new Stripe.CustomerCreateOptions();
                myCustomer.Email       = cardInfo.Buyer_Email;
                myCustomer.SourceToken = newToken.Id;
                var             customerService = new Stripe.CustomerService();
                Stripe.Customer stripeCustomer  = customerService.Create(myCustomer);

                var t = TempData["totalCost"];


                int    t1 = (int)Math.Round(Convert.ToDouble(t)) - 1;
                string total;
                string input_decimal_number = t.ToString();

                var regex = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
                if (regex.IsMatch(input_decimal_number))
                {
                    string decimal_places = regex.Match(input_decimal_number).Value;
                    total = t1.ToString() + decimal_places;
                }
                else
                {
                    total = t1 + "00";
                }


                System.Diagnostics.Trace.WriteLine(t1.ToString());


                var options = new Stripe.ChargeCreateOptions
                {
                    Amount       = Convert.ToInt32(total),
                    Currency     = "USD",
                    ReceiptEmail = cardInfo.Buyer_Email,
                    CustomerId   = stripeCustomer.Id,
                };



                var           service = new Stripe.ChargeService();
                Stripe.Charge charge  = service.Create(options);


                return(View("Thanks"));
            }
            catch (StripeException e)
            {
                switch (e.StripeError.ErrorType)
                {
                case "card_error":

                    error = (" Error Message: " + e.StripeError.Message);
                    break;

                case "api_connection_error":
                    break;

                case "api_error":
                    break;

                case "authentication_error":
                    break;

                case "invalid_request_error":
                    break;

                case "rate_limit_error":
                    break;

                case "validation_error":
                    break;

                default:
                    // Unknown Error Type
                    break;
                }
                ViewBag.Greeting = error;
                return(View("Error"));
            }
        }
        private async void Button_Clicked(object sender, EventArgs e)
        {
            try
            {
                StripeConfiguration.SetApiKey("sk_test_51H7Lu7KJ3FKVwUnlPU8EUYuDPU0UMWNajFeHpVYzqwLkpKFRk9480iV54ZvAIPy4J0xYlKoN9IQaGMoyhhcaxOgl003Kz8FIdL");

                //This are the sample test data use MVVM bindings to send data to the ViewModel

                Stripe.CreditCardOptions stripcard = new Stripe.CreditCardOptions();
                stripcard.Number   = cardNumberEntry.Text;
                stripcard.ExpYear  = Convert.ToInt32(expiryDate.Text.Split('/')[1]);
                stripcard.ExpMonth = Convert.ToInt32(expiryDate.Text.Split('/')[0]);
                stripcard.Cvc      = cvvEntry.Text;


                //Step 1 : Assign Card to Token Object and create Token

                Stripe.TokenCreateOptions token = new Stripe.TokenCreateOptions();
                token.Card = stripcard;
                Stripe.TokenService serviceToken = new Stripe.TokenService();
                Stripe.Token        newToken     = serviceToken.Create(token);

                // Step 2 : Assign Token to the Source

                var options = new SourceCreateOptions
                {
                    Type     = SourceType.Card,
                    Currency = "usd",
                    Token    = newToken.Id
                };

                var    service = new SourceService();
                Source source  = service.Create(options);

                //Step 3 : Now generate the customer who is doing the payment

                Stripe.CustomerCreateOptions myCustomer = new Stripe.CustomerCreateOptions()
                {
                    Name        = nameEntry.Text,
                    Email       = emailEntry.Text,
                    Description = "Amare Payment",
                };

                var             customerService = new Stripe.CustomerService();
                Stripe.Customer stripeCustomer  = customerService.Create(myCustomer);

                mycustomer = stripeCustomer.Id; // Not needed

                //Step 4 : Now Create Charge Options for the customer.

                var chargeoptions = new Stripe.ChargeCreateOptions
                {
                    Amount       = 100,
                    Currency     = "USD",
                    ReceiptEmail = emailEntry.Text,
                    Customer     = stripeCustomer.Id,
                    Source       = source.Id
                };

                //Step 5 : Perform the payment by  Charging the customer with the payment.
                var           service1 = new Stripe.ChargeService();
                Stripe.Charge charge   = service1.Create(chargeoptions); // This will do the Payment

                getchargedID = charge.Id;                                // Not needed
                await DisplayAlert("Payment", "Payment Success", "Okay");

                await Navigation.PopAsync();
            }
            catch (Stripe.StripeException ex)
            {
                await DisplayAlert("Payment Error", ex.Message, "Okay");
            }
        }
Exemple #26
0
        public ActionResult Charge(FormCollection formCollection)
        {
            Stripe.StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["stripePublishableKey"]);
            Stripe.StripeConfiguration.ApiKey = ConfigurationManager.AppSettings["stripeSecretKey"];
            var myCharge = new Stripe.ChargeCreateOptions();

            // always set these properties
            myCharge.Amount   = long.Parse(formCollection[0]);
            myCharge.Currency = "VND";
            var    listVe         = context.Ves.ToList();
            string maVeCuoi       = listVe[listVe.Count - 1].MaVe;
            int    identity       = int.Parse(maVeCuoi.Substring(2));
            var    listHoaDon     = context.HoaDons.ToList();
            string maHoaDonCuoi   = listHoaDon[listHoaDon.Count - 1].MaHoaDon;
            int    identityHoaDon = int.Parse(maHoaDonCuoi.Substring(2));
            var    listKhachHang  = context.KhachHangs.ToList();

            if (Session["MaTaiKhoan"] == null)
            {
                if (Session["MaKhachHangVangLai"] != null)
                {
                    var hoaDon = new HoaDon()
                    {
                        MaHoaDon     = "HD" + (identityHoaDon + 1).ToString("00"),
                        MaKhachHang  = Session["MaKhachHangVangLai"].ToString(),
                        MaNhanVien   = "ADMIN",
                        ThoiGianXuat = DateTime.Now
                    };
                    context.HoaDons.Add(hoaDon);
                    string idTour = formCollection[1];
                    for (int i = 2; i < formCollection.Count - 3; i += 2)
                    {
                        int quantity = 0;
                        if (Int32.TryParse(formCollection[i + 1], out quantity))
                        {
                            for (int j = 0; j < int.Parse(formCollection[i + 1]); j++)
                            {
                                Ve ve = new Ve()
                                {
                                    MaVe     = "Ve" + (identity + 1).ToString("00"),
                                    MaTour   = idTour,
                                    MaLoaiVe = formCollection[i],
                                    MaHoaDon = hoaDon.MaHoaDon
                                };
                                context.Ves.Add(ve);
                                identity++;
                            }
                        }
                    }
                }
                else
                {
                    return(Content("Bạn chưa điền thông tin! Hãy đăng nhập hoặc điền thông tin trước khi đặt"));
                }
            }
            else
            {
                KhachHang khachHang = context.KhachHangs.Find(Session["MaTaiKhoan"]);
                var       hoaDon    = new HoaDon()
                {
                    MaHoaDon     = "HD" + (identityHoaDon + 1).ToString("00"),
                    MaKhachHang  = khachHang.MaKhachHang,
                    MaNhanVien   = "ADMIN",
                    ThoiGianXuat = DateTime.Now
                };
                context.HoaDons.Add(hoaDon);
                string idTour = formCollection[1];
                for (int i = 2; i < formCollection.Count - 3; i += 2)
                {
                    int soLuongVe = 0;
                    try
                    {
                        soLuongVe = int.Parse(formCollection[i + 1]);
                    }
                    catch (Exception e)
                    {
                        continue;
                    }
                    for (int j = 0; j < soLuongVe; j++)
                    {
                        Ve ve = new Ve()
                        {
                            MaVe     = "Ve" + (identity + 1).ToString("00"),
                            MaTour   = idTour,
                            MaLoaiVe = formCollection[i],
                            MaHoaDon = hoaDon.MaHoaDon
                        };
                        context.Ves.Add(ve);
                        identity++;
                    }
                }
            }

            myCharge.ReceiptEmail = formCollection[formCollection.Count - 1];
            myCharge.Source       = formCollection[formCollection.Count - 3];
            myCharge.Capture      = true;
            var chargeService = new Stripe.ChargeService();

            try
            {
                Charge stripeCharge = chargeService.Create(myCharge);
                context.SaveChanges();
                SumerizeRevenue();
                return(View("ThanhCong"));
            }
            catch (Exception e)
            {
                return(View("ThatBai"));
            }
        }
        public PaymentView(DateTime bookingDate, string centerName, string sportName, string courtName, string startingBookingTime, string endingBookingTime, double TotalPaymentAmount)
        {
            InitializeComponent();

            //startingBookingTime AND endingBookingTime  are TimeSpan not DateTime  ...... Done


            var uname = Preferences.Get("UserName", String.Empty);

            if (String.IsNullOrEmpty(uname))
            {
                username.Text = "Guest";
            }
            else
            {
                username.Text = uname;
            }

            centername.Text = centerName;

            courtname.Text = courtName;


            //bookingdate.Text = bookingDate.Date.ToString();
            cvm = new PaymentViewModel(bookingDate);
            this.BindingContext = cvm;

            bookingtime.Text = startingBookingTime.ToString() + " - " + endingBookingTime.ToString();

            double RoundedTotalPaymentAmount = Math.Round(TotalPaymentAmount, 1, MidpointRounding.ToEven);

            totalpaymentamount.Text = "RM " + RoundedTotalPaymentAmount.ToString();

            string totalp = totalpaymentamount.Text;

            DateTime s = Convert.ToDateTime(startingBookingTime);
            DateTime d = Convert.ToDateTime(endingBookingTime);


            NewEventHandler.Clicked += async(sender, args) =>
            {
                // if check payment from Moustafa is true, then add booking to firebase
                try
                {
                    //StripeConfiguration.SetApiKey("sk_test_51IpayhGP2IgUXM55te5JbGRu14MOp6AU6GORVFhqpOilEOp96ERDzKCi1VN9rDLrOmOEwNPqgOvQuIyaNg8YKfkL00Qoq8a7QX");
                    StripeConfiguration.SetApiKey("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");


                    //This are the sample test data use MVVM bindings to send data to the ViewModel

                    Stripe.TokenCardOptions stripcard = new Stripe.TokenCardOptions();

                    stripcard.Number   = cardnumber.Text;
                    stripcard.ExpYear  = Int64.Parse(expiryYear.Text);
                    stripcard.ExpMonth = Int64.Parse(expirymonth.Text);
                    stripcard.Cvc      = cvv.Text;
                    //stripcard.Cvc = Int64.Parse(cvv.Text);



                    //Step 1 : Assign Card to Token Object and create Token

                    Stripe.TokenCreateOptions token = new Stripe.TokenCreateOptions();
                    token.Card = stripcard;
                    Stripe.TokenService serviceToken = new Stripe.TokenService();
                    Stripe.Token        newToken     = serviceToken.Create(token);

                    // Step 2 : Assign Token to the Source

                    var options = new SourceCreateOptions
                    {
                        Type     = SourceType.Card,
                        Currency = "myr",
                        Token    = newToken.Id
                    };

                    var    service = new SourceService();
                    Source source  = service.Create(options);

                    //Step 3 : Now generate the customer who is doing the payment

                    Stripe.CustomerCreateOptions myCustomer = new Stripe.CustomerCreateOptions()
                    {
                        Name        = "Moustafa",
                        Email       = "*****@*****.**",
                        Description = "Customer for [email protected]",
                    };

                    var             customerService = new Stripe.CustomerService();
                    Stripe.Customer stripeCustomer  = customerService.Create(myCustomer);

                    mycustomer = stripeCustomer.Id; // Not needed

                    //Step 4 : Now Create Charge Options for the customer.

                    var chargeoptions = new Stripe.ChargeCreateOptions
                    {
                        //Amount = (Int64.Parse(RoundedTotalPaymentAmount)) * 100,
                        //(int(RoundedTotalPaymentAmount))
                        //Amount = Convert.ToInt32(RoundedTotalPaymentAmount) * 100,
                        //Amount = (long?)(double.Parse(RoundedTotalPaymentAmount) * 100),
                        Amount       = (long?)(double.Parse(totalp) * 100),
                        Currency     = "MYR",
                        ReceiptEmail = "*****@*****.**",
                        Customer     = stripeCustomer.Id,
                        Source       = source.Id
                    };

                    //Step 5 : Perform the payment by  Charging the customer with the payment.
                    var           service1 = new Stripe.ChargeService();
                    Stripe.Charge charge   = service1.Create(chargeoptions); // This will do the Payment


                    getchargedID = charge.Id; // Not needed
                }
                catch (Exception ex)
                {
                    UserDialogs.Instance.Alert(ex.Message, null, "ok");
                    Console.Write("error" + ex.Message);

                    //await Application.Current.MainPage.DisplayAlert("error ", ex.Message, "OK");
                }
                finally
                {
                    //if (getchargedID != null)
                    if (getchargedID != null)
                    {
                        var acd = new AddBookingData(sportName, courtName, username.Text, centerName, s, d, bookingDate, RoundedTotalPaymentAmount);
                        await acd.AddBookingDataAsync();


                        UserDialogs.Instance.Alert("Payment Successed", "Success", "Ok");
                        Xamarin.Forms.Application.Current.MainPage = new MainTabbedView();
                        //await Application.Current.MainPage.DisplayAlert("Payment Successed ", "Success", "OK");
                    }
                    else
                    {
                        UserDialogs.Instance.Alert("Something Wrong", "Faild", "OK");
                        //await Application.Current.MainPage.DisplayAlert("Payment Error ", "faild", "OK");
                    }
                }



                /*
                 * var acd = new AddBookingData(sportName, courtName, username.Text, centerName, s, d, bookingDate, RoundedTotalPaymentAmount);
                 * await acd.AddBookingDataAsync();
                 * /*
                 *
                 *
                 * //Application.Current.MainPage = new MainTabbedView();
                 *
                 * //await Navigation.PopModalAsync();
                 * //await Navigation.PopToRootAsync();
                 * /*
                 * Navigation.InsertPageBefore(new NewPage(), Navigation.NavigationStack[0]);
                 * await Navigation.PopToRootAsync();
                 */
            };

            /*
             * public void GetCustomerInformationID(object sender, EventArgs e)
             * {
             *  var service = new CustomerService();
             *  var customer = service.Get(mycustomer);
             *  var serializedCustomer = JsonConvert.SerializeObject(customer);
             *  //  var UserDetails = JsonConvert.DeserializeObject<CustomerRetriveModel>(serializedCustomer);
             *
             * }
             *
             *
             * public void GetAllCustomerInformation(object sender, EventArgs e)
             * {
             *  var service = new CustomerService();
             *  var options = new CustomerListOptions
             *  {
             *      Limit = 3,
             *  };
             *  var customers = service.List(options);
             *  var serializedCustomer = JsonConvert.SerializeObject(customers);
             * }
             *
             *
             * public void GetRefundForSpecificTransaction(object sender, EventArgs e)
             * {
             *  var refundService = new RefundService();
             *  var refundOptions = new RefundCreateOptions
             *  {
             *      Charge = getchargedID,
             *  };
             *  Refund refund = refundService.Create(refundOptions);
             *  refundID = refund.Id;
             * }
             *
             *
             * public void GetRefundInformation(object sender, EventArgs e)
             * {
             *  var service = new RefundService();
             *  var refund = service.Get(refundID);
             *  var serializedCustomer = JsonConvert.SerializeObject(refund);
             *
             * }
             */

            /*
             *
             * async Task NewEventHandler(object sender, EventArgs e)
             * {
             *  // if check payment from Moustafa is true, then
             *
             *  // add booking to firebase
             *
             *  var acd = new AddBookingData(sportName, courtName, username.Text, centerName, s, d, bookingDate, TotalPaymentAmount);
             *  await acd.AddBookingDataAsync();
             * }
             */
        }
Exemple #28
0
        public Charge Create(ChargeCreateOptions options)
        {
            var service = new Stripe.ChargeService();

            return(service.Create(options));
        }
Exemple #29
0
        public ViewResult makePayment(PaymentInformation cardInfo)
        {
            try
            {
                Stripe.StripeConfiguration.SetApiKey("sk_test_51HqI05B1UsJ4lZg1agboQSE7i0fWn98619xc2FP5NhREH4igqo1AlKTQO8VWMfsQBUs1OlXNBzBkOqORRQP6ZlPf00E2l0QVhL");


                //Create Card Object to create Token
                Stripe.CreditCardOptions card = new Stripe.CreditCardOptions();
                card.Name     = cardInfo.CardOwnerFirstName + " " + cardInfo.CardOwnerLastName;
                card.Number   = cardInfo.CardNumber;
                card.ExpYear  = cardInfo.ExpirationYear;
                card.ExpMonth = cardInfo.ExpirationMonth;
                card.Cvc      = cardInfo.CVV2;

                //Assign Card to Token Object and create Token
                Stripe.TokenCreateOptions token = new Stripe.TokenCreateOptions();
                token.Card = card;
                Stripe.TokenService serviceToken = new Stripe.TokenService();
                Stripe.Token        newToken     = serviceToken.Create(token);

                Stripe.CustomerCreateOptions myCustomer = new Stripe.CustomerCreateOptions();
                myCustomer.Email       = cardInfo.Buyer_Email;
                myCustomer.SourceToken = newToken.Id;
                var             customerService = new Stripe.CustomerService();
                Stripe.Customer stripeCustomer  = customerService.Create(myCustomer);

                //Create Charge Object with details of Charge
                var options = new Stripe.ChargeCreateOptions
                {
                    Amount       = Convert.ToInt32(cardInfo.Amount),
                    Currency     = "USD",
                    ReceiptEmail = cardInfo.Buyer_Email,
                    CustomerId   = stripeCustomer.Id,
                };
                //and Create Method of this object is doing the payment execution.
                var           service = new Stripe.ChargeService();
                Stripe.Charge charge  = service.Create(options); // This will do the Payment


                return(View("Thanks"));
            }
            catch (StripeException e)
            {
                switch (e.StripeError.ErrorType)
                {
                case "card_error":
                    //error = ("Code: " + e.StripeError.Code + "; ");
                    error = (" Error Message: " + e.StripeError.Message);
                    break;

                case "api_connection_error":
                    break;

                case "api_error":
                    break;

                case "authentication_error":
                    break;

                case "invalid_request_error":
                    break;

                case "rate_limit_error":
                    break;

                case "validation_error":
                    break;

                default:
                    // Unknown Error Type
                    break;
                }
                ViewBag.Greeting = error;
                return(View("Error"));
            }
        }
Exemple #30
0
        public async Task <IActionResult> Create([FromBody] CreateOrderViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _db.Users.SingleAsync(x => x.UserName == HttpContext.User.Identity.Name);

            var order = new Data.Entities.Order
            {
                DeliveryAddress = new Data.Entities.Address
                {
                    FirstName = model.FirstName,
                    LastName  = model.LastName,
                    Address1  = model.Address1,
                    Address2  = model.Address2,
                    TownCity  = model.TownCity,
                    County    = model.County,
                    Postcode  = model.Postcode
                },
                Items = model.Items.Select(x => new Data.Entities.OrderItem
                {
                    ProductId = x.ProductId,
                    ColourId  = x.ColourId,
                    StorageId = x.StorageId,
                    Quantity  = x.Quantity
                }).ToList()
            };

            user.Orders.Add(order);
            await _db.SaveChangesAsync();

            var total = await _db.Orders
                        .Where(x => x.Id == order.Id)
                        .Select(x => Convert.ToInt32(x.Items.Sum(i =>
                                                                 i.ProductVariant.Price * i.Quantity) * 100))
                        .SingleAsync();

            var charges = new Stripe.ChargeService();
            var charge  = await charges.CreateAsync(new Stripe.ChargeCreateOptions
            {
                Amount      = total,
                Description = $"Order {order.Id} payment",
                Currency    = "GBP",
                Source      = model.StripeToken
            });

            if (string.IsNullOrEmpty(charge.FailureCode))
            {
                order.PaymentStatus = PaymentStatus.Paid;
            }
            else
            {
                order.PaymentStatus = PaymentStatus.Declined;
            }

            await _db.SaveChangesAsync();

            return(Ok(new CreateOrderResponseViewModel(order.Id, order.PaymentStatus)));
        }