Пример #1
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)));
        }
Пример #2
0
        public Subscription Subscribe(string email, string name, string source, string monthlyPlanId, string overagePlanId)
        {
            var customerService = new Stripe.CustomerService();
            var customer        = customerService.Create(new CustomerCreateOptions
            {
                Email       = email,
                Description = name,
                Source      = source
            });

            var subscriptionService = new Stripe.SubscriptionService();

            var items = new List <SubscriptionItemOptions> {
                new SubscriptionItemOptions {
                    Plan = monthlyPlanId
                },
                new SubscriptionItemOptions {
                    Plan = overagePlanId
                }
            };

            var subscription = subscriptionService.Create(new SubscriptionCreateOptions
            {
                Customer = customer.Id,
                Items    = items,
            });

            return(subscription);
        }
Пример #3
0
 public StripeCustomerGateway(IBillingConfig config)
 {
     customerService      = new Stripe.CustomerService();
     subscriptionService  = new Stripe.SubscriptionService();
     paymentMethodService = new Stripe.PaymentMethodService();
     this.config          = config;
 }
Пример #4
0
        public Stripe.Customer GetCustomer(string customerId)
        {
            var customerService = new Stripe.CustomerService(PrivateKey);

            Stripe.Customer stripeCustomer = customerService.Get(customerId);

            return(stripeCustomer);
        }
        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 }));
        }
Пример #6
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 }));
        }
Пример #7
0
 public async Task AddPaymentOption(PaymentOption paymentOption)
 {
     // update token - card
     var customerService = new CustomerService();
     await customerService.UpdateAsync(paymentOption.CustomerId, new CustomerUpdateOptions()
     {
         Source = paymentOption.Token
     });
 }
Пример #8
0
 public static stripe.Customer GetOrCreateCustomer(this stripe.CustomerService customerService, Core.Domain.Customers.Customer customer, string stripeCustomerId, StripePaymentSettings paymentSettings)
 {
     if (!string.IsNullOrEmpty(stripeCustomerId))
     {
         return(customerService.Get(stripeCustomerId));
     }
     else
     {
         return(customerService.Create(customer.CreateCustomerOptions(paymentSettings)));
     }
 }
Пример #9
0
 public static bool TryConnect(this StripePaymentSettings stripePaymentSettings)
 {
     try
     {
         var stripeService = new stripe.CustomerService(stripePaymentSettings.GetStripeClient());
         return(stripeService.List() != null);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
Пример #10
0
        async public Task <string> CreateCustomer(Users user)
        {
            CustomerCreateOptions customerOpts = new CustomerCreateOptions
            {
                Email = user.Email
            };

            Stripe.CustomerService customerService = new Stripe.CustomerService();
            Stripe.Customer        newCustomer     = await customerService.CreateAsync(customerOpts);

            return(newCustomer.Id);
        }
Пример #11
0
        public async Task <Customer> CreateCustomerAsync(string name, string email, string phone)
        {
            var options = new CustomerCreateOptions
            {
                Name  = name,
                Email = email,
                Phone = phone
            };

            var service = new Stripe.CustomerService();

            return(await service.CreateAsync(options));
        }
Пример #12
0
        public static stripe.Customer GetOrCreateCustomer(this stripe.CustomerService customerService, Core.Domain.Customers.Customer customer, IGenericAttributeService genericAttributeService, StripePaymentSettings paymentSettings)
        {
            string stripeCustomerId = genericAttributeService.GetAttribute <string>(customer, paymentSettings.GetCustomerIdKey());

            stripe.Customer result = customerService.GetOrCreateCustomer(customer, stripeCustomerId, paymentSettings);

            if (string.IsNullOrEmpty(stripeCustomerId))
            {
                genericAttributeService.SaveAttribute(customer, paymentSettings.GetCustomerIdKey(), result.Id);
            }

            return(result);
        }
Пример #13
0
        public ActionResult <Subscription> CreateSubscription([FromBody]  CreateSubscriptionRequest req)
        {
            // Attach payment method
            var options = new PaymentMethodAttachOptions
            {
                Customer = req.Customer,
            };
            var service       = new PaymentMethodService();
            var paymentMethod = service.Attach(req.PaymentMethod, options);

            // Update customer's default invoice payment method
            var customerOptions = new CustomerUpdateOptions
            {
                InvoiceSettings = new CustomerInvoiceSettingsOptions
                {
                    DefaultPaymentMethod = paymentMethod.Id,
                },
            };
            var customerService = new CustomerService();

            customerService.Update(req.Customer, customerOptions);

            // Create subscription
            var subscriptionOptions = new SubscriptionCreateOptions
            {
                Customer = req.Customer,
                Items    = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Price = Environment.GetEnvironmentVariable(req.Price),
                    },
                },
            };

            subscriptionOptions.AddExpand("latest_invoice.payment_intent");
            var subscriptionService = new SubscriptionService();

            try
            {
                Subscription subscription = subscriptionService.Create(subscriptionOptions);
                return(subscription);
            }
            catch (StripeException e)
            {
                Console.WriteLine($"Failed to create subscription.{e}");
                return(BadRequest());
            }
        }
        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());
        }
Пример #15
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);
            }
        }
Пример #16
0
        private Stripe.Customer StripeCustomer([FromBody]  CustomerOrder order)
        {
            var options = new CustomerCreateOptions
            {
                Name             = order.customer.first_name + " " + order.customer.last_name,
                Email            = order.customer.email,
                Phone            = order.customer.contact_mobile,
                PreferredLocales = new List <string> {
                    "nb", "en"
                }
            };

            var service  = new CustomerService();
            var customer = service.Create(options);

            return(customer);
        }
Пример #17
0
        public async Task <IActionResult> getOrCreateCustomer()
        {
            PayModel paymodel    = getPayModel();
            var      service     = new CustomerService();
            var      listOptions = new CustomerListOptions
            {
                Limit = 1
            };

            listOptions.AddExtraParam("email", paymodel.Email);
            var customer = (await service.ListAsync(listOptions)).Data.FirstOrDefault();

            if (customer != null)
            {
                return(Ok(customer));
            }

            var options = new CustomerCreateOptions
            {
                Email   = paymodel.Email,
                Phone   = paymodel.Phone,
                Name    = paymodel.Name,
                Address = new AddressOptions()
                {
                    Line1      = paymodel.AddressLine1,
                    Line2      = paymodel.AddressLine2,
                    State      = paymodel.AddressState,
                    City       = paymodel.AddressCity,
                    Country    = paymodel.AddressCountry,
                    PostalCode = paymodel.AddressZip
                },
                Metadata = new Dictionary <string, string>()
                {
                    { "TrainingYears", "user.TrainingYears" },
                    { "GroupName", "user.GroupName" },
                    { "Level", "user.Level" }
                },
            };

            var result = await service.CreateAsync(options);

            var response = await Task.FromResult(result);

            return(Ok(response));
        }
Пример #18
0
        public async Task <Customer> UpdateCustomerAsync(string customerId, string name, string email)
        {
            var options = new CustomerUpdateOptions();

            if (!string.IsNullOrEmpty(name))
            {
                options.Name = name;
            }

            if (!string.IsNullOrEmpty(email))
            {
                options.Email = email;
            }

            var service = new Stripe.CustomerService();

            return(await service.UpdateAsync(customerId, options));
        }
Пример #19
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);
        }
Пример #20
0
        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
            }));
        }
Пример #21
0
        public async Task <IActionResult> CreateCustomerAsync()
        {
            PayModel paymodel = getPayModel();
            var      options  = new CustomerCreateOptions
            {
                Source = this.Token().Id,
                Name   = paymodel.Name,
                Email  = paymodel.Email,
                Phone  = paymodel.Phone
            };

            var service = new CustomerService();

            Stripe.Customer customer = await service.CreateAsync(options);

            var response = await Task.FromResult(customer);

            return(Ok(response));
        }
Пример #22
0
        public void Subscribe(StripeChargeRequest req, int userId)
        {
            // do a data provider call for AppUser GetById
            // that will give you the email address

            var plan = GetById(req.TenantId, req.SubscriptionLevel);

            var customers = new Stripe.CustomerService();
            var customer  = customers.Create(new CustomerCreateOptions
            {
                SourceToken = req.StripeToken,
                Email       = req.Email,
            });
            var items = new List <SubscriptionItemOption> {
                new SubscriptionItemOption {
                    PlanId = plan.StripePlanId
                }
            };
            var options = new SubscriptionCreateOptions
            {
                Items      = items,
                CustomerId = customer.Id
            };
            var          service      = new SubscriptionService();
            Subscription subscription = service.Create(options);

            dataProvider.ExecuteNonQuery(
                "Subscriptions_Insert",
                (parameters) =>
            {
                parameters.AddWithValue("@TenantId", req.TenantId);
                parameters.AddWithValue("@BusinessId", req.BusinessId);
                parameters.AddWithValue("@SubscriptionLevel", req.SubscriptionLevel);
                parameters.AddWithValue("@StripeToken", req.StripeToken);
                parameters.AddWithValue("@StripeCustomerId", subscription.CustomerId);
                parameters.AddWithValue("@StripeSubscriptionId", subscription.Id);
                parameters.AddWithValue("@StartDate", subscription.CurrentPeriodStart);
                parameters.AddWithValue("@EndDate", subscription.CurrentPeriodEnd);
                parameters.Add("@Id", SqlDbType.Int).Direction = ParameterDirection.Output;
            }
                );
        }
Пример #23
0
        public bool CreateCreditCard(CreaditCardCreateViewModel model)
        {
            StripeConfiguration.SetApiKey(SETTING.Value.SecretStripe);


            var customerTMP = _customerRepository.Get(x => x.Deleted == false && x.Id == model.CustomerId);

            if (customerTMP.StripeId == null || customerTMP.StripeId == "")
            {
                var options = new CustomerCreateOptions
                {
                    Email       = customerTMP.Email,
                    Description = "Customer for " + customerTMP.FullName + " " + customerTMP.Email,
                    SourceToken = model.CardId
                };
                var             service  = new Stripe.CustomerService();
                Stripe.Customer customer = service.Create(options);
                customerTMP.StripeId = customer.Id;
                _customerRepository.Update(customerTMP);
                model.CardId    = customer.DefaultSourceId;
                model.Isdefault = true;
            }
            else
            {
                var optionsCard = new CardCreateOptions
                {
                    SourceToken = model.CardId
                };
                var serviceCard = new Stripe.CardService();
                var card        = serviceCard.Create(customerTMP.StripeId, optionsCard);
                model.CardId = card.Id;
            }
            model.Last4DigitsHash = encrypt(model.Last4DigitsHash);
            var creditCard = _mapper.Map <CreaditCardCreateViewModel, CreditCard>(model);

            _creditCardRepository.Add(creditCard);
            _unitOfWork.CommitChanges();
            return(true);
        }
Пример #24
0
        private async Task <Customer> getOrCreateCustomer(string email)
        {
            var service     = new Stripe.CustomerService();
            var listOptions = new Stripe.CustomerListOptions
            {
                Limit = 1
            };

            listOptions.AddExtraParam("email", email);
            var customer = (await service.ListAsync(listOptions)).Data.FirstOrDefault();

            if (customer != null)
            {
                return(customer);
            }

            var customerCreateOptions = new Stripe.CustomerCreateOptions
            {
                Email = email
            };

            return(await service.CreateAsync(customerCreateOptions));
        }
Пример #25
0
        public static Charge RequestCharge(Transactions transactionModel, decimal payAmount, string description, bool isCapture = true)
        {
            // Set your secret key: remember to change this to your live secret key in production
            // See your keys here: https://dashboard.stripe.com/account/apikeys
            StripeConfiguration.SetApiKey(SecretKey);

            // Create a Customer:
            var customerOptions = new CustomerCreateOptions
            {
                SourceToken = transactionModel.PaymentCardToken,
                //Email = "*****@*****.**",
            };
            var customerService = new Stripe.CustomerService();

            Stripe.Customer customer = customerService.Create(customerOptions);

            string PaidAmountString = ConvertDecimalAmountToZeroDecimal(payAmount);

            var options = new ChargeCreateOptions
            {
                Amount   = Convert.ToInt64(PaidAmountString),
                Currency = transactionModel.Currency,
                //SourceId = transactionModel.PaymentCardToken,
                Description = description,
                //ReceiptEmail = "*****@*****.**",
                CustomerId = customer.Id,
                Capture    = isCapture,
                Metadata   = new Dictionary <string, string>()
                {
                    { "order_id", transactionModel.OrderId },
                }
            };
            var    service = new ChargeService();
            Charge charge  = service.Create(options);

            return(charge);
        }
Пример #26
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"));
            }
        }
        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");
            }
        }
Пример #28
0
        public async Task <Customer> GetCustomerAsync(string customerId)
        {
            var service = new Stripe.CustomerService();

            return(await service.GetAsync(customerId));
        }
Пример #29
0
        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"));
            }
        }
Пример #30
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));
            }
        }