Exemple #1
0
        public CustomerServiceTest(
            StripeMockFixture stripeMockFixture,
            MockHttpClientFixture mockHttpClientFixture)
            : base(stripeMockFixture, mockHttpClientFixture)
        {
            this.service = new CustomerService(this.StripeClient);

            this.createOptions = new CustomerCreateOptions
            {
                Email  = "*****@*****.**",
                Source = "tok_123",
            };

            this.updateOptions = new CustomerUpdateOptions
            {
                Metadata = new Dictionary <string, string>
                {
                    { "key", "value" },
                },
            };

            this.listOptions = new CustomerListOptions
            {
                Limit = 1,
            };
        }
Exemple #2
0
        //[HttpPost("create-customer")]
        private ActionResult <Customer> CreateNewCustomer()
        {
            var options = new CustomerCreateOptions
            {
                Name    = "Ramin Sadat",
                Email   = "*****@*****.**",
                Phone   = "+15717996452",
                Address = new AddressOptions
                {
                    Line1      = "8617 Wales Ct",
                    City       = "Gainesville",
                    State      = "VA",
                    PostalCode = "20155",
                    Country    = "USA",
                },
                Description = "Future Payments",
            };
            var service = new CustomerService(_client);

            try
            {
                var customer = service.Create(options);
                //return Json(customer); Only if returning data to to

                return(customer);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        public async Task <string> CreateStripeCustomer(UserDTO userDTO)
        {
            //Crear customer en Quick Order Stripe Account
            StripeConfiguration.ApiKey = this._configuration.GetSection("Stripe")["SecretKey"];

            //Informacion del customer o user en stripe
            var optionsCustomers = new CustomerCreateOptions
            {
                Description = "New Customer From Quick Order",
                Name        = userDTO.Name,
                Email       = userDTO.Email,
                Phone       = userDTO.Phone,
                Address     = new AddressOptions()
                {
                    Line1 = userDTO.Address
                }
            };

            //Mando un api call de crear un customer
            var customerservice = new CustomerService();
            var customertoken   = await customerservice.CreateAsync(optionsCustomers);


            //Verificamos que el id hay sido creado de manera correcta
            if (!string.IsNullOrEmpty(customertoken.Id))
            {
                // Retornamos el valor id del customer.
                return(customertoken.Id);
            }
            else
            {
                return(string.Empty);
            }
        }
        public IActionResult Processing(string stripeToken, string stripeEmail)
        {
            var optionsCust = new CustomerCreateOptions
            {
                Email = stripeEmail,
                Name  = "Robert",
                Phone = "04-234567"
            };
            var      serviceCust   = new CustomerService();
            Customer customer      = serviceCust.Create(optionsCust);
            var      optionsCharge = new ChargeCreateOptions
            {
                /*Amount = HttpContext.Session.GetLong("Amount")*/
                Amount       = Convert.ToInt64(TempData["TotalAmount"]),
                Currency     = "USD",
                Description  = "Buying Flowers",
                Source       = stripeToken,
                ReceiptEmail = stripeEmail,
            };
            var    service = new ChargeService();
            Charge charge  = service.Create(optionsCharge);

            if (charge.Status == "succeeded")
            {
                string BalanceTransactionId = charge.BalanceTransactionId;
                ViewBag.AmountPaid  = Convert.ToDecimal(charge.Amount) % 100 / 100 + (charge.Amount) / 100;
                ViewBag.BalanceTxId = BalanceTransactionId;
                ViewBag.Customer    = customer.Name;
                //return View();
            }

            return(View());
        }
Exemple #5
0
        public async Task <ActionResult <User> > PostUser(User user)
        {
            if (ModelState.IsValid)
            {
                if (_context.User.Any(r => r.Email.Equals(user.Email)))
                {
                    return(Ok("Email already in use"));
                }
                else
                {
                    StripeConfiguration.ApiKey = "sk_test_pYh0rfomNeq3KvqXyIaDCGWO00XMbINsnF";
                    var options1 = new CustomerCreateOptions
                    {
                        Description = "My First Test Customer (created for API docs)",
                    };
                    var      service = new CustomerService();
                    Customer c       = service.Create(options1);

                    user.StripeId = c.Id;
                    string salt          = Crypto.generateSalt();
                    string hasedPassword = Crypto.computeHash(user.Password, salt);
                    user.Salt     = salt;
                    user.Password = hasedPassword;
                    _context.User.Add(user);
                    await _context.SaveChangesAsync();
                }
            }
            else
            {
                return(BadRequest(ModelState));
            }

            return(Ok("success"));
        }
        public async Task <SetupIntent> CreateSetupIntent()
        {
            // Here we create a customer, then create a SetupIntent.
            // The SetupIntent is the object that keeps track of the
            // Customer's intent to allow saving their card details
            // so they can be charged later when the customer is no longer
            // on your site.

            // Create a customer
            var options  = new CustomerCreateOptions();
            var service  = new CustomerService();
            var customer = await service.CreateAsync(options);

            // Create a setup intent, and return the setup intent.
            var setupIntentOptions = new SetupIntentCreateOptions
            {
                Customer = customer.Id,
            };
            var setupIntentService = new SetupIntentService();

            // We're returning the full SetupIntent object here, but you could
            // also just return the ClientSecret for the newly created
            // SetupIntent as that's the only required data to confirm the
            // SetupIntent on the front end with Stripe.js.
            return(await setupIntentService.CreateAsync(setupIntentOptions));
        }
        public async Task <CreateCustomerResult> Handle(CreateCustomerRequest request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            _validator.ValidateAndThrow(request.Model);

            var options = new CustomerCreateOptions
            {
                Name  = request.Model.Name,
                Email = request.Model.Email
            };

            var customer = await _customerService.CreateAsync(options, null, cancellationToken);

            _logger.LogInformation("Customer is created with ID: " + customer.Id);
            GetCustomerModel model = new GetCustomerModel
            {
                Id    = customer.Id,
                Name  = customer.Name,
                Email = customer.Email
            };

            CreateCustomerResult result = new CreateCustomerResult(model);

            return(result);
        }
Exemple #8
0
        public IActionResult Create(CustomerViewModel model)
        {
            try
            {
                var options = new CustomerCreateOptions
                {
                    Description = model.FullName,
                    Email       = model.Email,
                    Source      = model.CreditCardToken,
                    Metadata    = new Dictionary <string, string>
                    {
                        { "Phone Number", model.Phone }
                    }
                };
                var service  = new CustomerService();
                var customer = service.Create(options);

                var res = new CustomerDetailsModel
                {
                    Id      = customer.Id,
                    Details = JsonConvert.SerializeObject(customer, Formatting.Indented)
                };

                return(View("CustomerStatus", res));
            }
            catch (Exception ex)
            {
                ViewData["ErrorMessage"] = ex.Message;
                return(View("Create"));
            }
        }
        private bool CreateCustomer_Stripe(User newUser)
        {
            StripeConfiguration.ApiKey = "sk_test_51HcZiyF6EVrg0l22KUHmhtN6fxfGQvV1yG2vk2My3Dnq6N4zTg3CASy3OKzArWvWij8CL7BwnqGDPY8xke0Hsmq100FLmHAkYc";

            var firebaseIDData = new Dictionary <string, string>();

            firebaseIDData.Add("FirebaseID", newUser.userID);
            var options = new CustomerCreateOptions
            {
                Email       = newUser.email,
                Description = "FirebaseID: " + newUser.userID,
                Metadata    = firebaseIDData
            };
            var      service  = new CustomerService();
            Customer customer = service.Create(options);

            if (customer != null)
            {
                var payload = new Dictionary <string, string>
                {
                    { "stripeID", customer.Id },
                };

                Global.db.WriteToDB("Users/" + newUser.userID + "/", payload);
                Global.db.WriteToDB("Usage/" + Session["userKey"].ToString() + "/", payload);
                return(true);
            }

            return(false);
        }
Exemple #10
0
        public IActionResult Processing(string stripeToken, string stripeEmail)
        {
            decimal amountPaid   = 0;
            string  customerName = "";
            var     optionsCust  = new CustomerCreateOptions {
                Email = stripeEmail,
                Name  = "Jerome",
                Phone = "04-234567"
            };
            var      serviceCust   = new CustomerService();
            Customer customer      = serviceCust.Create(optionsCust);
            var      optionsCharge = new ChargeCreateOptions {
                Amount       = Convert.ToInt64(TotalAmount),
                Currency     = "USD",
                Description  = "Selling Flowers",
                Source       = stripeToken,
                ReceiptEmail = stripeEmail
            };
            var    serviceCharge = new ChargeService();
            Charge charge        = serviceCharge.Create(optionsCharge);

            if (charge.Status == "succeeded")
            {
                amountPaid   = Convert.ToDecimal(charge.Amount) % 100 / 100 + (charge.Amount) / 100;
                customerName = customer.Name;
            }

            return(Ok());
        }
        /// <summary>
        /// Adds a new customer with account id
        /// </summary>
        /// <param name="id"></param>
        /// <param name="email"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <returns></returns>
        public async Task <dynamic> PostCustomer(string id, string email, string firstName, string lastName)
        {
            try
            {
                StripeConfiguration.ApiKey = key;

                var options = new CustomerCreateOptions
                {
                    Email    = email,
                    Name     = firstName + " " + lastName,
                    Metadata = new Dictionary <string, string>
                    {
                        { "UserId", id },
                    }
                };
                var             service  = new CustomerService();
                Stripe.Customer customer = await service.CreateAsync(options);

                return(customer);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #12
0
        public Customer createStripeCustomer(string stripeToken, string stripeEmail)
        {
            try
            {
                string stripeCustId = string.Empty;
                //fetch stripeCustId from DB using email if found then
                //demo customer ID : "cus_IN8KSF6jWoAF4U"
                //var service = new CustomerService();
                //service.Get("cus_IN8KSF6jWoAF4U");

                Customer customer = new Customer();
                if (string.IsNullOrEmpty(stripeCustId))
                {
                    //Create customer on stripe
                    var customerOptions = new CustomerCreateOptions
                    {
                        Email  = stripeEmail,
                        Source = stripeToken,
                    };
                    var customerService = new CustomerService();
                    customer = customerService.Create(customerOptions);
                }
                else
                {
                    //Fetch customer from stripe
                    var service = new CustomerService();
                    customer = service.Get(stripeCustId);
                }
                return(customer);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        public ActionResult <CreateCustomerResponse> CreateCustomer([FromBody] CreateCustomerRequest req)
        {
            if (!ModelState.IsValid)
            {
                return(this.FailWithMessage("invalid params"));
            }
            var options = new CustomerCreateOptions
            {
                Email = req.Email,
            };
            var      service = new CustomerService();
            Customer customer;

            try
            {
                customer = service.Create(options);
            }
            catch (StripeException e)
            {
                return(this.FailWithMessage($"Failed to create customer: {e}"));
            }
            return(new CreateCustomerResponse
            {
                Customer = customer,
            });
        }
        public CreditCardProcess(string cardNumber, string cardExpMonth, string cardExpYear, string cardCVC)
        {
            InitializeComponent();
            StripeConfiguration.SetApiKey("pk_live_HTl5JEEmjEbq772AbJ3N6Ahl");

            var tokenOptions = new Stripe.TokenCreateOptions()
            {
                Card = new Stripe.CreditCardOptions()
                {
                    Number   = cardNumber,
                    ExpYear  = long.Parse(cardExpYear),
                    ExpMonth = long.Parse(cardExpMonth),
                    Cvc      = cardCVC
                }
            };

            var tokenService = new Stripe.TokenService();

            Stripe.Token stripeToken = tokenService.Create(tokenOptions);

            var customerOptions = new CustomerCreateOptions();
            var customerService = new CustomerService();

            customerOptions.SourceToken = stripeToken.Id;
            customerOptions.Email       = App.newUser.eMailAddress;
            Customer newCustomer = customerService.Create(customerOptions);

            Console.WriteLine(newCustomer.Id);

            //Console.WriteLine("Token is"+stripeToken.Id);
        }
Exemple #15
0
        public void registerUser(string username, string email, string pwd, string accType)
        {
            byte[] IV = null;
            Tuple <string, string> pwdAndSalt = Auth.hash(pwd);
            RijndaelManaged        cipher     = new RijndaelManaged();

            cipher.GenerateIV();
            IV = cipher.IV;

            StripeConfiguration.ApiKey = "sk_test_51Hnjg6K2AIXSM7wrvlwz0S8eQSrtxjb7irpnIhvWGSKSsbWJzUymiC3tHbwxYQCumbmK5gC06kRIw7wr1eHEpj6D00CDgHmOpO";
            Customer              cust    = new Customer();
            CustomerService       serv    = new CustomerService();
            CustomerCreateOptions options = new CustomerCreateOptions
            {
                Description = username,
                Balance     = 5000
            };

            cust = serv.Create(options);

            User user = new User(username, email, pwdAndSalt.Item1, pwdAndSalt.Item2, "", accType, Convert.ToBase64String(IV), Auth.encrypt(cust.Id, IV));

            user.AddUser();
            Session["success"] = "Registered successfully";
            Response.Redirect("~/Views/auth/login.aspx");
        }
        public async Task <IActionResult> CreateAndSave()
        {
            //Step 2
            var options = new CustomerCreateOptions {
            };

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

            //Step 3
            var optionss = new PaymentIntentCreateOptions
            {
                Amount   = 1099,
                Currency = "usd",
                Customer = customer.Id //"{{CUSTOMER_ID}}",
            };

            var servicee      = new PaymentIntentService();
            var paymentIntent = servicee.Create(optionss);

            return(Ok(new SaveCustomerDetailsCommandResult()
            {
                ClientSecret = paymentIntent.ClientSecret
            }));
        }
        public string GetCustomerId(string tokenId, string email, string fullname, string buisnessname)
        {
            string message = "";

            StripeConfiguration.ApiKey = "sk_test_NBBwzubTNLQUD0hen0RGqpZy00Jf1PT0gS";
            try
            {
                // Create a Customer:
                var customerOptions = new CustomerCreateOptions
                {
                    Source = tokenId,
                    Email  = email,
                    Name   = fullname + " ," + buisnessname
                };
                var      customerService = new CustomerService();
                Customer customer        = customerService.Create(customerOptions);
                message = customer.Id;
            }
            catch (StripeException ex)
            {
                message = ex.Message;
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return(message);
        }
Exemple #18
0
        public IActionResult AddCustomer(string email, string name)
        {
            StripeConfiguration.ApiKey = API_KEY;

            var options = new CustomerCreateOptions
            {
                Email = email,
                Name  = name,
            };
            var      service  = new CustomerService();
            Customer customer = service.Create(options);

            var subOptions = new SubscriptionCreateOptions
            {
                Customer = customer.Id,
                Items    = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Price = "price_1IFcjaHVInnZqCxxolFGevVP",
                    },
                },
            };
            var subService = new SubscriptionService();

            subService.Create(subOptions);
            return(Ok());
        }
    protected void btnRequestPayment_Click(object sender, EventArgs e)
    {
        //login for Stripe is [email protected]
        //pw careycole
        txtAmount.Text += "00"; //must add this because stripe payment formatting is wacky!

        StripeConfiguration.ApiKey = "sk_test_18Gn9oGB42sHsUO89q2zx0Cp00aZRNckFV";

        // `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/cards/collecting/web#create-token

        var customer = new CustomerCreateOptions
        {
            Email       = "*****@*****.**",
            Description = "Charge for Griffin Cosgrove",
            Name        = "Griffin Cosgrove",
        };
        var service2 = new CustomerService();

        service2.Create(customer);

        var charge = new ChargeCreateOptions
        {
            Amount      = Convert.ToInt32(txtAmount.Text), // amount from amount textbox
            Currency    = "usd",                           //could change depending on the currency selected but we could just keep it as is
            Source      = "tok_visa",                      //4242 4242 4242 4242 ---i think we can just keep
            Description = txtDescription.Text,             //add maybe their email for the descri
        };
        var service = new ChargeService();

        service.Create(charge);
    }
        static void Main(string[] args)
        {
            //Set this to a valid test API key.
            StripeConfiguration.ApiKey = "sk_test_XXX";
            Console.WriteLine("Versioning in .NET!");
            Console.WriteLine("The .NET library is using API Version: " + StripeConfiguration.ApiVersion);

            //Create and print a customer to see what the response from library's pinned version looks like.
            var customerOptions = new CustomerCreateOptions
            {
                Email       = "*****@*****.**",
                Description = "Customer created with API version pinned to library",
            };
            var customerService = new CustomerService();
            var customer        = customerService.Create(customerOptions);

            Console.WriteLine("Customer created:");
            Console.WriteLine(customer);

            // Retrieve the customer.created event
            // or look at it in the Dashboard: https://dashboard.stripe.com/test/events
            // The customer object in the event payload will be based off of the version your
            // account is set to.
            var eventOptions = new EventListOptions {
                Limit = 1
            };
            var eventService          = new EventService();
            StripeList <Event> events = eventService.List(eventOptions);

            Console.WriteLine("customer.created event:");
            Console.WriteLine(events.Data[0]);

            //Create a webhook endpoint and set it's API version.

            var endpointOptions = new WebhookEndpointCreateOptions
            {
                ApiVersion    = StripeConfiguration.ApiVersion,
                Url           = "https://example.com/my/webhook/endpoint",
                EnabledEvents = new List <String>
                {
                    "customer.created",
                },
            };
            var endpointService = new WebhookEndpointService();

            endpointService.Create(endpointOptions);

            customerOptions.Email       = "*****@*****.**";
            customerOptions.Description = "Customer created using version set on for webhook endpoint";
            customer = customerService.Create(customerOptions);

            // Visit the Dashboard page for the endpoint you just created:
            // https://dashboard.stripe.com/test/webhooks/we_XXX
            // Under "Webhook Attempts" you'll see the event data Stripe has sent to the endpoint
            // for the customer that was just created.
            // Since we created the endpoint using the 2020-08-27 API version, the customer object
            // in the payload is using that version.
            Console.WriteLine("All done, visit https://dashboard.stripe.com/test/webhooks to see what was sent to the endpoint");
        }
        public virtual async Task <Customer> Create(CustomerCreateOptions createOptions)
        {
            var url = this.ApplyAllParameters(createOptions, Urls.Customers, false);

            var response = await Requestor.Post(url);

            return(Mapper <Customer> .MapFromJson(response));
        }
Exemple #22
0
        private Customer CreateStripeCustomer(CustomerCreateOptions options)
        {
            StripeConfiguration.ApiKey = _appKeys.StripeApiKey;

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

            return(customer);
        }
        public IActionResult Charge(string Token, string Amount, string Email, string list)
        {
            var customerOptions = new CustomerCreateOptions
            {
                Email  = Email,
                Source = Token
            };
            var      customerService = new CustomerService();
            Customer customer        = customerService.Create(customerOptions);

            var chargeOptions = new ChargeCreateOptions
            {
                Customer = customer.Id,
                Amount   = Convert.ToInt32(Amount) * 100,
                Currency = "usd",
            };
            var    chargeService = new ChargeService();
            Charge charge        = chargeService.Create(chargeOptions);

            if (charge.Status == "succeeded")
            {
                int userid = (int)HttpContext.Session.GetInt32("id");

                AddressModel address = GetApiResult <AddressModel>("/address/getaddress/" + userid);


                while (list.Contains("-"))
                {
                    try {
                        string value = list.Substring(0, list.IndexOf("-"));

                        var bill = new JObject();
                        bill.Add("UserId", userid);
                        bill.Add("ProductId", value);
                        bill.Add("Address", address.FullAddress);
                        bill.Add("Price", GetApiResult <ProductModel>("/product/get/" + value).Price);
                        bill.Add("Quentity", 1);

                        bool control = PostApiResult <JObject>("/bill/addbill", bill);
                        bool ctr     = GetApiResult <bool>("/basket/removeproduct/" + value + "&" + userid);
                        list = list.Substring(list.IndexOf("-") + 1);
                    }
                    catch
                    {
                        continue;
                    }
                }

                return(RedirectToAction("MyBasket"));
            }
            else
            {
                return(RedirectToAction("HomePageWithUser"));
            }
        }
Exemple #24
0
        public string createACustomer()
        {
            StripeConfiguration.ApiKey = "sk_test_51H4bEIAVJDEhYcbP8AniC54IhmNxi8AOAkQpTgSCdwJjXwd8eoYEZmpBdZPOn7mpkBhQWkuzYYIFUv1y8Y3ncnKO008t1vsMSK";

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

            return(customer.Id);
        }
Exemple #25
0
        public SubscriptionResult Create(User user, string email, string paymentToken, string planId)
        {
            var paymentMethodCreate = new PaymentMethodCreateOptions {
                Card = new PaymentMethodCardCreateOptions {
                    Token = paymentToken
                },
                Type = "card"
            };

            var pmService     = new PaymentMethodService();
            var paymentMethod = pmService.Create(paymentMethodCreate);

            Console.WriteLine("Payment method: " + paymentMethod.Id);

            var custOptions = new CustomerCreateOptions {
                Email           = email,
                PaymentMethod   = paymentMethod.Id,
                InvoiceSettings = new CustomerInvoiceSettingsOptions {
                    DefaultPaymentMethod = paymentMethod.Id,
                },
                Metadata = new Dictionary <string, string> {
                    { "userid", user.Id.ToString() }
                }
            };

            var custService = new CustomerService();
            var customer    = custService.Create(custOptions);

            Console.WriteLine("Customer: " + customer.Id);

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

            var subscriptionOptions = new SubscriptionCreateOptions {
                Customer        = customer.Id,
                Items           = items,
                TrialPeriodDays = 7
            };

            subscriptionOptions.AddExpand("latest_invoice.payment_intent");

            var subService = new SubscriptionService();

            var subscription = subService.Create(subscriptionOptions);

            Console.WriteLine("Subscription: " + subscription.Id);

            return(new SubscriptionResult(
                       customerId: customer.Id,
                       subscriptionId: subscription.Id));
        }
Exemple #26
0
        public async Task <Customer> CreateAsync(CustomerCreateOptions newCustomer)
        {
            _idCounter++;
            _stripeCustomers.Add(new Customer()
            {
                Id       = $"cus_id{_idCounter}",
                Metadata = newCustomer.Metadata,
            });

            return(_stripeCustomers.First(x => x.Id == $"cus_id{_idCounter}"));
        }
        public async Task <Customer> CreateAsync(CustomerCreateOptions newCustomer)
        {
            var customerCreateOptions = new CustomerCreateOptions
            {
                Email    = newCustomer.Email,
                Name     = newCustomer.Name,
                Metadata = newCustomer.Metadata,
            };

            return(await _customerService.CreateAsync(newCustomer));
        }
Exemple #28
0
        public async Task <Customer> CreateCustomerAsync(string emailAddress)
        {
            var options = new CustomerCreateOptions
            {
                Email = emailAddress
            };

            var customer = await _customerService.CreateAsync(options);

            return(customer);
        }
Exemple #29
0
        public Customer CreateCustomer(string email)
        {
            var options = new CustomerCreateOptions
            {
                Email = email,
            };
            var service  = new CustomerService();
            var customer = service.Create(options);

            return(customer);
        }
        private Customer createCust(string key)
        {
            StripeConfiguration.ApiKey = key;

            var options = new CustomerCreateOptions
            {
                Description = "My First Test Customer (created for API docs)",
            };
            var service = new CustomerService();

            return(service.Create(options));
        }