Inheritance: Stripe.StripeService
Example #1
0
        public bool SaveCustomerByToken(string email, string stripeToken)
        {
            try
            {
                var customer = new StripeCustomerCreateOptions();
                customer.Email = email;
                //customer.Description = "Johnny Tenderloin ([email protected])";
                customer.TokenId = stripeToken;
                //customer.PlanId = *planId*;                          // only if you have a plan
                //customer.Coupon = *couponId*;                        // only if you have a coupon
                //customer.TrialEnd = DateTime.UtcNow.AddMonths(1);    // when the customers trial ends (overrides the plan if applicable)
                //customer.Quantity = 1;                               // optional, defaults to 1
                var customerService = new StripeCustomerService(Cohort.Site.Stripe.SecretKey);
                var stripeCustomer = customerService.Create(customer);
                // Create linkage between signup and customer for later charging

                return true;
            }
            catch (Exception)
            {
                // log 

                return false;
            }
        }
Example #2
0
        private async Task<string> ProcessSubscription(StripeChargeModel model)
        {
            //TODO
            if (model.Amount == 0)
            {
                model.Amount = 399;
            }

            var planId = "Up100PerMo";
            var secretKey = ConfigurationManager.AppSettings["StripeApiKey"];
            model.Card.TokenId = model.Id;

            return await Task.Run(() =>
            {
                var stripeCustomerCreateOptions = new StripeCustomerCreateOptions
                {
                    Email = model.Email,
                    PlanId = planId,
                    Card = model.Card,
                    Description = "Charged £3.99 for monthly up to 100",
                };
                var customerService = new StripeCustomerService(secretKey);
                var stripeCustomer = customerService.Create(stripeCustomerCreateOptions);

                return stripeCustomer.Id;
            });
        }
        // GET: Test
        public ActionResult Index()
        {
            var customerList = new StripeCustomerService().List();
            StripeCustomer firstcustomer = customerList.First();
            //  var invoice = new StripeInvoice();

            StripeInvoice firstCusomterInvoice =
                new StripeInvoiceService().List().FirstOrDefault(x => x.CustomerId == firstcustomer.Id);

            return View(firstCusomterInvoice);
        }
        public ActionResult Custom(CustomViewModel customViewModel)
        {
            customViewModel.PaymentFormHidden = false;
            var chargeOptions = new StripeChargeCreateOptions()
            {
                //required
                Amount = 3900,
                Currency = "usd",
                Source = new StripeSourceOptions() { TokenId = customViewModel.StripeToken },
                //optional
                Description = string.Format("JavaScript Framework Guide Ebook for {0}", customViewModel.StripeEmail),
                ReceiptEmail = customViewModel.StripeEmail
            };

            var chargeService = new StripeChargeService();

            try
            {
                StripeCharge stripeCharge = chargeService.Create(chargeOptions);

                //Validate charge
                chargeService.Capture(stripeCharge.Id);

                if (stripeCharge.Status == "succeeded")
                {
                    //creating the customer and add it to stripe
                    var newCustomer = new StripeCustomerService().Create(
                        new StripeCustomerCreateOptions
                        {
                            Email = customViewModel.StripeEmail
                        }
                        );
                    // CREATE NEW INVOICE
                    // var invoiceService = new StripeInvoiceService();
                    // StripeInvoice response = invoiceService.Create(newCustomer.Id); // optional StripeInvoiceCreateOptions
                    //var response = invoiceService.Upcoming(newCustomer.Id);
                    // stripeCharge.InvoiceId = response.Id;

                    //SEND THE CONFIRMATION
                    var emailService = new EmailService();
                    emailService.SendPaymentReceivedFromChargeEmail(stripeCharge);

                }
            }
            catch (StripeException stripeException)
            {
                Debug.WriteLine(stripeException.Message);
                ModelState.AddModelError(string.Empty, stripeException.Message);
                return View(customViewModel);
            }

            return RedirectToAction("Confirmation");
        }
        SubscriptionDetails ISubscriptionService.GetCustomerSubscription(string customerBillingId)
        {
            SubscriptionDetails subscription = null;

            try
            {
                var customerService = new StripeCustomerService();
                StripeCustomer stripeCustomer = customerService.Get(customerBillingId);
                Coupon coupon = null;
                Discount discount = null;
                if (stripeCustomer.StripeDiscount != null && stripeCustomer.StripeDiscount.StripeCoupon != null)
                {
                    coupon = new Coupon
                    {
                        AmountOff = stripeCustomer.StripeDiscount.StripeCoupon.AmountOff,
                        Duration = stripeCustomer.StripeDiscount.StripeCoupon.Duration,
                        DurationInMonths = stripeCustomer.StripeDiscount.StripeCoupon.DurationInMonths,
                        Id = stripeCustomer.StripeDiscount.StripeCoupon.Id,
                        PercentOff = stripeCustomer.StripeDiscount.StripeCoupon.PercentOff,
                        RedeemBy = stripeCustomer.StripeDiscount.StripeCoupon.RedeemBy
                    };
                    discount = new Discount
                    {
                        Coupon = coupon,
                        End = stripeCustomer.StripeDiscount.End,
                        Id = stripeCustomer.StripeDiscount.Id,
                        Start = stripeCustomer.StripeDiscount.Start
                    };
                }

                subscription = new SubscriptionDetails
                {
                    Created = stripeCustomer.Created,
                    Deleted = stripeCustomer.Deleted,
                    CanceledAt = stripeCustomer.StripeSubscription != null? stripeCustomer.StripeSubscription.CanceledAt : null,
                    CustomerId = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.CustomerId: null,
                    EndedAt = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.EndedAt: null,
                    PeriodEnd = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.PeriodEnd: null,
                    PeriodStart = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.PeriodStart: null,
                    Start = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.Start: null,
                    TrialEnd = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.TrialEnd: null,
                    TrialStart = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.TrialStart: null,
                    Status = stripeCustomer.StripeSubscription != null? stripeCustomer.StripeSubscription.Status: null,
                    Plan = stripeCustomer.StripeSubscription != null ? stripeCustomer.StripeSubscription.StripePlan.Name : null,
                    Discount = discount
                };
            }
            catch { }

            return subscription;
        }
        public ActionResult About()
        {
            StripeConfiguration.SetApiKey("sk_test_JRb9hXgh80838IRQQTUHwJPP");

            var myCustomer = new StripeCustomerCreateOptions();

            // set these properties if it makes you happy
            myCustomer.Email = "*****@*****.**";
            myCustomer.Description = "teste stripe.net";



            // setting up the card
            myCustomer.Source = new StripeSourceOptions()
            {
                // set this property if using a token
                // TokenId = *tokenId *,

                Object = "card",
                // set these properties if passing full card details (do not
                // set these properties if you set TokenId)
                Number = "4242424242424242",
                ExpirationYear = "2022",
                ExpirationMonth = "10",
                AddressCountry = "IE",                // optional
                AddressLine1 = "24 Beef Flank St",    // optional
                AddressLine2 = "Apt 24",              // optional
                AddressCity = "Biggie Smalls",        // optional
                AddressState = "NC",                  // optional
                AddressZip = "27617",                 // optional
                Name = "Mateus Meatballs",               // optional
                Cvc = "1223",


            };

            myCustomer.PlanId = "2";                          // only if you have a plan
                                                              // myCustomer.TaxPercent = 20;                            // only if you are passing a plan, this tax percent will be added to the price.
                                                              //myCustomer.Coupon = *couponId *;                        // only if you have a coupon
                                                              //myCustomer.TrialEnd = DateTime.UtcNow.AddMonths(1);    // when the customers trial ends (overrides the plan if applicable)
            myCustomer.Quantity = 1;                         // optional, defaults to 1



            var customerService = new StripeCustomerService();

            StripeCustomer stripeCustomer = customerService.Create(myCustomer);


            return View();
        }
        // GET: Invoices
        public ActionResult Index()
        {
            //CUS ID For Testing
            //cus_75PYlPJEmsQb9X

            var customerList = new StripeCustomerService().List();
            StripeCustomer firstcustomer = customerList.First();
            //  var invoice = new StripeInvoice();

            StripeInvoice firstCusomterInvoice =
                new StripeInvoiceService().List().FirstOrDefault(x => x.CustomerId == firstcustomer.Id);

            return View(firstCusomterInvoice);
        }
Example #8
0
        public CreateCustomerResponse CreateCustomer(CreateCustomerRequest req)
        {
            var response = new CreateCustomerResponse();

            try
            {
                var myCustomer = new StripeCustomerCreateOptions();

                myCustomer.Email = req.Email;
                myCustomer.Description = req.Name;

                // set these properties if using a card
                myCustomer.CardNumber = req.CreditCard.CardNumber;
                myCustomer.CardExpirationYear = req.CreditCard.ExpirationYear.ToString();
                myCustomer.CardExpirationMonth = req.CreditCard.ExpirationMonth.ToString();
                myCustomer.CardAddressCountry = "US";                 // optional
                //myCustomer.CardAddressLine1 = "24 Beef Flank St";   // optional
                //myCustomer.CardAddressLine2 = "Apt 24";             // optional
                //myCustomer.CardAddressState = "NC";                 // optional
                myCustomer.CardAddressZip = req.PostalCode; //        // optional
                myCustomer.CardName = req.CreditCard.CardHolderName;  // optional
                if (req.CreditCard.SecurityCode.Length > 0)
                {
                    myCustomer.CardCvc = req.CreditCard.SecurityCode;
                }

                myCustomer.PlanId = req.PlanId;

                var customerService = new StripeCustomerService();
                StripeCustomer stripeCustomer = customerService.Create(myCustomer);

                if (stripeCustomer.Id.Length > 0)
                {
                    response.NewCustomerId = stripeCustomer.Id;
                    response.Success = true;                    
                }
                else
                {
                    response.Success = false;
                    response.Message = "Unable to get new customer Id";
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            
            return response;
        }
 public void CleanCustomers()
 {
     try
     {
         StripeCustomerService stripeService = new StripeCustomerService("sk_0JDG46M1ff0yZRqZjz9CNKtW2Aj14");
         var options = new StripeCustomerListOptions();
         options.Limit = 10000;
         var customers = stripeService.List(options);
         foreach (var customer in customers)
         {
             stripeService.Delete(customer.Id);
         }
     }
     catch
     {
     }
 }
        private void createCustomer()
        {
            string token = "" + Request.Form["stripeToken"];
            var myCustomer = new StripeCustomerCreateOptions();

            myCustomer.Email = "";
            myCustomer.Description = "";

            //Setting up card
            myCustomer.Source = new StripeSourceOptions()
            {
                TokenId = token
            };

            var customerService = new StripeCustomerService();
            StripeCustomer stripeCustomer = customerService.Create(myCustomer);


            //Add to DB
            DbConn.dBWrite("EXEC CreateStripeID '" + stripeCustomer.Id + "', " + Session["ID"]);
        }
 public SubscriptionService(ApplicationUserManager userManager, StripeCustomerService customerService, StripeSubscriptionService subscriptionService)
 {
     this.userManager = userManager;
     this.customerService = customerService;
     this.subscriptionService = subscriptionService;
 }
        public JsonResult ChangePlan(string organizationId, string planId, string stripeToken, string last4) {
            if (String.IsNullOrEmpty(organizationId) || !User.CanAccessOrganization(organizationId))
                throw new ArgumentException("Invalid organization id.", "organizationId"); // TODO: These should probably throw http Response exceptions.

            if (!Settings.Current.EnableBilling)
                return Json(new { Success = false, Message = "Plans cannot be changed while billing is disabled." });

            Organization organization = _repository.GetById(organizationId);
            if (organization == null)
                return Json(new { Success = false, Message = "Invalid OrganizationId." });

            BillingPlan plan = _billingManager.GetBillingPlan(planId);
            if (plan == null)
                return Json(new { Success = false, Message = "Invalid PlanId." });

            if (String.Equals(organization.PlanId, plan.Id) && String.Equals(BillingManager.FreePlan.Id, plan.Id))
                return Json(new { Success = true, Message = "Your plan was not changed as you were already on the free plan." });

            // Only see if they can downgrade a plan if the plans are different.
            string message;
            if (!String.Equals(organization.PlanId, plan.Id) && !_billingManager.CanDownGrade(organization, plan, User.UserEntity, out message))
                return Json(new { Success = false, Message = message });

            var customerService = new StripeCustomerService();

            try {
                // If they are on a paid plan and then downgrade to a free plan then cancel their stripe subscription.
                if (!String.Equals(organization.PlanId, BillingManager.FreePlan.Id) && String.Equals(plan.Id, BillingManager.FreePlan.Id)) {
                    if (!String.IsNullOrEmpty(organization.StripeCustomerId))
                        customerService.CancelSubscription(organization.StripeCustomerId);

                    organization.BillingStatus = BillingStatus.Trialing;
                    organization.RemoveSuspension();
                } else if (String.IsNullOrEmpty(organization.StripeCustomerId)) {
                    if (String.IsNullOrEmpty(stripeToken))
                        return Json(new { Success = false, Message = "Billing information was not set." });

                    organization.SubscribeDate = DateTime.Now;

                    StripeCustomer customer = customerService.Create(new StripeCustomerCreateOptions {
                        TokenId = stripeToken,
                        PlanId = planId,
                        Description = organization.Name
                    });

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                    organization.StripeCustomerId = customer.Id;
                    if (customer.StripeCardList.StripeCards.Count > 0)
                        organization.CardLast4 = customer.StripeCardList.StripeCards[0].Last4;
                } else {
                    var update = new StripeCustomerUpdateSubscriptionOptions {
                        PlanId = planId
                    };
                    bool cardUpdated = false;

                    if (!String.IsNullOrEmpty(stripeToken)) {
                        update.TokenId = stripeToken;
                        cardUpdated = true;
                    }

                    customerService.UpdateSubscription(organization.StripeCustomerId, update);
                    if (cardUpdated)
                        organization.CardLast4 = last4;

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                }

                _billingManager.ApplyBillingPlan(organization, plan, User.UserEntity);
                _repository.Update(organization);

                _notificationSender.PlanChanged(organization.Id);
            } catch (Exception e) {
                Log.Error().Exception(e).Message("An error occurred while trying to update your billing plan: " + e.Message).Report(r => r.MarkAsCritical()).Write();
                return Json(new { Success = false, Message = e.Message });
            }

            return Json(new { Success = true });
        }
        public async Task<ActionResult> DowngradePlan()
        {
            await Task.Run(() =>
            {
                var cust = getCustomer();

                if (cust != null) // downgrade
                {
                    // retrieve customer
                    var customerService = new StripeCustomerService();
                    StripeCustomer currentCustomer = customerService.Get(cust.StripeCustomerID);

                    // change plan
                    StripeSubscriptionService subService = new StripeSubscriptionService();
                    StripeSubscriptionUpdateOptions updateOptions = new StripeSubscriptionUpdateOptions();
                    updateOptions.PlanId = "standard";
                    updateOptions.TrialEnd = currentTime; // no free days allowed when downgrading

                    var myUpdateSuscription = subService.Update(currentCustomer.Id, cust.StripeSubscriptionID, updateOptions);

                    // record changes in db
                    StripeCustomers newRecord = new StripeCustomers();

                    newRecord.StripeCustomerID = myUpdateSuscription.CustomerId;
                    newRecord.CustomerName = User.Identity.Name;
                    newRecord.StripeSubscriptionID = cust.StripeSubscriptionID;
                    newRecord.SubscriptionType = "standard";
                    newRecord.TrialValidUntil = currentTime;
                    newRecord.HasSubscription = true;
                    newRecord.StartDate = currentTime;
                    newRecord.Interval = "Monthly";

                    db.StripeCustomers.Add(newRecord);
                    db.StripeCustomers.Remove(cust);
                    db.SaveChanges();
                }
            });
            return RedirectToAction("Index", "Home");
        }
        public async Task<ActionResult> CancelSubscription()
        {          
            await Task.Run(() =>
            {
                var hasSubscription = getCustomer().HasSubscription;
                if(hasSubscription == true)
                {
                    var uStripeCustomer = getCustomer();
                    var stripeCustomerID = uStripeCustomer.StripeCustomerID;
                    var subscriptionID = uStripeCustomer.StripeSubscriptionID;                    
                  
                    if (uStripeCustomer.SubscriptionType == "ultimate")
                    {
                        // cancel subscription in stripe.com
                        var subscriptionService = new StripeSubscriptionService();
                        subscriptionService.Cancel(stripeCustomerID, subscriptionID);

                        // delete stripe customer as well
                        var customerService = new StripeCustomerService();
                        StripeCustomer customerToDelete = customerService.Get(stripeCustomerID);
                        customerService.Delete(customerToDelete.Id);

                        db.StripeCustomers.Remove(uStripeCustomer); //db
                    }
                    else if (uStripeCustomer.SubscriptionType == "standard")
                    {
                        // cancel subscription in stripe.com
                        var subscriptionService = new StripeSubscriptionService();
                        subscriptionService.Cancel(stripeCustomerID, subscriptionID);

                        // delete stripe customer as well
                        var customerService = new StripeCustomerService();
                        StripeCustomer customerToDelete = customerService.Get(stripeCustomerID);
                        customerService.Delete(customerToDelete.Id);

                        uStripeCustomer.HasSubscription = false; //db
                    }
                    db.SaveChanges();                  
                }
            });
         
            return RedirectToAction("Index", "Home");
        }
Example #15
0
        private StripeCustomer GetCustomer(NewDonationModel model, StripePlan plan)
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var currentUser = manager.FindById(User.Identity.GetUserId());
            string userEmail = currentUser.Email;
            var myCustomer = new StripeCustomerCreateOptions
            {
                Email = userEmail,
                Description = currentUser.FirstName + currentUser.LastName,
                Source = new StripeSourceOptions()
                {
                    TokenId = model.Token
                }
            };

            myCustomer.PlanId = plan.Id;

            var customerService = new StripeCustomerService("sk_test_yPi2XADkAP3wiS1i6tkjErxZ");
            return customerService.Create(myCustomer);
        }
        public ActionResult AccountOptions()
        {
            TempData["SelectedMenu"] = "Account";
            TempData["SelectedSubMenu"] = "Options";
            User userObj = (User)Session["user"];
            Account accountObj = (Account)Session["account"];

            if (userObj.PrimaryUser == false)
                return RedirectToAction("Index", "Admin");

            AccountInfomationViewModel accountinfor = new AccountInfomationViewModel();

            //get time zone
            System.Collections.ObjectModel.ReadOnlyCollection<TimeZoneInfo> tz;
            tz = TimeZoneInfo.GetSystemTimeZones();
            List<TimeZoneViewModel> tzList = new List<TimeZoneViewModel>();

            foreach (var t in tz)
            {
                TimeZoneViewModel tzvmodel = new TimeZoneViewModel();
                tzvmodel.DisplayName = t.DisplayName;
                tzvmodel.ID = t.Id;
                tzList.Add(tzvmodel);
            }

            accountinfor.TimeZoneList = tzList;

            if (userObj != null)
            {
                var account = accountRepo.Accounts.Where(aid => aid.ID == userObj.AccountID).FirstOrDefault();
                accountinfor.AccountName = account.AccountName;
                accountinfor.ContactName = userObj.FullName;
                accountinfor.EmailAddress = userObj.Email;
                accountinfor.TimeZone = account.TimeZone;
                accountinfor.BillingAddress = account.BusinessAddress;

                //get numberof connection
                int planid = account.PlanID;
                int planLevel = planid * 10;

                //get billing plan
                var billingPlan = planRepository.Plans.Where(pid => pid.ID == planid).FirstOrDefault();
                accountinfor.BillingPlan = billingPlan.Name;

                // get saved quantity
                var accDetails = accountRepo.Accounts.Where(aguid => aguid.AccountGUID == accountObj.AccountGUID).FirstOrDefault();
                var planLeval = planRepository.Plans.Where(pid => pid.ID == accDetails.PlanID).FirstOrDefault().PlanLevel;

                var featureQuality = featureRepository.Features.Where(pid => pid.PlanLevel == planLeval & pid.Type == "Max Items per Folder").FirstOrDefault();
                    var savedQuality = purchRepository.Purchases.Where(fid => fid.FeatureID == featureQuality.ID && fid.AccountGUID == accountObj.AccountGUID).FirstOrDefault();

                    if (savedQuality != null)
                    {
                        var quantitySaved = (savedQuality.Quantity) / (featureQuality.Quantity);
                        accountinfor.NoOfConnection = quantitySaved * 5;

                    }
                    else
                    {
                        accountinfor.NoOfConnection = 0;
                    }

                accountinfor.ListofUsers = new List<Domain.Entities.User>();
                accountinfor.ListofUsers = userRepository.Users.Where(u => u.AccountID == userObj.AccountID).ToList();

                //var errorLogsObj = CCErrorLogRepository.CCErrorLogs.Where(guid => guid.AccountGUID == accountObj.AccountGUID & (guid.ErrorType == "Exchange Connection" | guid.ErrorType == "Sync")).Take(100).ToList();
                accountinfor.ErrorLogList = new List<CCErrorLog>();
                //accountinfor.ErrorLogList = errorLogsObj;

                var plans = planRepository.Plans.ToList();
                // plans.RemoveAll(pname => pname.Name == "Free");
                accountinfor.Plans = plans;

                // get selected plan
                var planID = accountRepo.Accounts.FirstOrDefault(aguid => aguid.AccountGUID == accountObj.AccountGUID).PlanID;
                accountinfor.PlanID = planID;

                // get selected plan details
                var selectedPlanDetails = plans.FirstOrDefault(pid => pid.ID == planID);
                selectedPlanDetails.Price = selectedPlanDetails.Price;
                //packageViewModel.SelectedPlanDetails = selectedPlanDetails;

                // get card details from stripe
                var stripeCustomerID = accountRepo.Accounts.FirstOrDefault(aguid => aguid.AccountGUID == accountObj.AccountGUID).StripeCustomerID;

                if (stripeCustomerID != null)
                {
                    // default card details
                    var customer = new StripeCustomerService();
               //         customer.ApiKey = "sk_test_4Xusc3Meo8gniONh6dDRZvlp";
                    var cusRes = customer.Get(stripeCustomerID);
                    var defaultCardID = cusRes.StripeDefaultCardId;
                    //packageViewModel.DefaultCardID = defaultCardID;

                    // get saved quantity
                    featureQuality = featureRepository.Features.FirstOrDefault(pid => pid.PlanLevel == selectedPlanDetails.PlanLevel & pid.Type == "Max Items per Folder");
                    savedQuality = purchRepository.Purchases.FirstOrDefault(fid => fid.FeatureID == featureQuality.ID && fid.AccountGUID == accountObj.AccountGUID);

                    if (savedQuality != null)
                    {
                        var quantitySaved = (savedQuality.Quantity) / (featureQuality.Quantity);
                        accountinfor.QuantitySaved = quantitySaved;

                    }
                    else
                    {
                        accountinfor.QuantitySaved = 1;
                    }

                    var cards = new StripeCardService();
                //    cards.ApiKey = "sk_test_4Xusc3Meo8gniONh6dDRZvlp";
                    var objCard = cards.List(stripeCustomerID, null);
                    List<CardViewModel> allCardDetails = new List<CardViewModel>();

                    foreach (var card in objCard)
                    {
                        CardViewModel objcard = new CardViewModel();
                        objcard.CardID = card.Id;
                        objcard.Name = card.Name;
                        objcard.Number = "**** " + card.Last4;
                        objcard.Type = card.Brand;
                        objcard.ExpireDate = card.ExpirationYear + "/" + card.ExpirationMonth;

                        allCardDetails.Add(objcard);
                    }
                    //packageViewModel.CardDetails = allCardDetails;
                }
                else
                {
                    //packageViewModel.CardDetails = null;
                }

            }

            return View(accountinfor);
        }
Example #17
0
        /// <summary>
        /// Creates a new customer record in Stripe for the given user
        /// NOTE: Save changes on the underlying context for the model after calling this method
        /// </summary>
        /// <param name="user"></param>
        public static void CreateCustomer(IStripeUser user, string paymentToken = null)
        {
            // Do not overwrite the user, ever
            if (user.HasPaymentInfo())
                return;

            var newCustomer = new StripeCustomerCreateOptions();

            newCustomer.Email = user.Email;

            if (paymentToken != null)
                newCustomer.Card = new StripeCreditCardOptions() { TokenId = paymentToken };

            var customerService = new StripeCustomerService();
            StripeCustomer stripeCustomer = customerService.Create(newCustomer);

            // Set the accounting info
            user.PaymentSystemId = stripeCustomer.Id;

            System.Diagnostics.Trace.TraceInformation("Created customer in stripe: '{0}' with id '{1}", user.Email, user.PaymentSystemId);
        }
        CustomerPayment ISubscriptionService.SaveCustomer(string id, ApplicationModel.Billing.CustomerPayment payment)
        {
            //Save Subscription Need to check first active vs new here
            var organization = this.organizationRepository.Find(payment.OrganizationId, null, null);
            var customerService = new StripeCustomerService();
            if (id != null && id != "null")
            {
                var myCustomer = InitializeUpdateCustomerOptions(payment);
                StripeCustomer stripeCustomer = customerService.Update(id, myCustomer);
            }
            else
            {
                var myCustomer = InitializeCreateSubscriptionOptions(payment);
                StripeCustomer stripeCustomer = customerService.Create(myCustomer);
                id = stripeCustomer.StripeSubscription.CustomerId;
                payment.CustomerId = id;
            }

            organization.Subscription.Status = SubscriptionStatus.ACTIVE;
            organization.Subscription.CustomerBillingId = id;
            if (!String.IsNullOrEmpty(payment.CardNumber))
            {
                organization.Subscription.ExpirationDate = payment.CardExpirationMonth + "/" + payment.CardExpirationYear;
                organization.Subscription.Last4Digits = payment.CardNumber.Substring(payment.CardNumber.Length - 4, 4);
            }
            organization.Subscription.HasTrialed = true;

            var svc = (ISubscriptionService)this;
            svc.SaveSubscription(organization);
            return payment;
        }
Example #19
0
 /// <summary>
 /// Retrieves the StripeCustomer associated with the given IStripeUser instance
 /// </summary>
 /// <param name="user"></param>
 /// <returns></returns>
 public static StripeCustomer RetrieveCustomer(IStripeUser user)
 {
     var customerService = new StripeCustomerService();
     StripeCustomer stripeCustomer = customerService.Get(user.PaymentSystemId);
     return stripeCustomer;
 }
Example #20
0
 public bool CancelSubscription(string customerId)
 {
     try
     {
         var customerService = new StripeCustomerService();
         var response = customerService.CancelSubscription(customerId);
         return true;
     }
     catch (StripeException stripeEx)
     {
         EventLog.LogEvent(stripeEx);
         return false;
     }
     catch (Exception ex)
     {
         EventLog.LogEvent(ex);
         return false;
     }
 }
Example #21
0
        public GetCustomerResponse GetCustomerInformation(string customerId)
        {
            var response = new GetCustomerResponse();

            var customerService = new StripeCustomerService();
            try
            {
                StripeCustomer stripeCustomer = customerService.Get(customerId);
                MapStripeCustomerTo(stripeCustomer, response);
                response.Success = true;
            }
            catch (StripeException ex)
            {
                response.Success = false;
                response.Message = ex.Message;
                return response;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }

            return response;
        }
		//static bool IsExistingCustomer(StripeCustomer customer)
		//{
		//    var customerListService = new StripeCustomerService();
		//    var customerList = customerListService.List();

		//    return customerList.Any(currentCustomer => customer.Email == currentCustomer.Email);
		//}

		static StripeCustomer GetCustomer(String email)
		{
			var customerListService = new StripeCustomerService();
			var customerList = customerListService.List();
			return customerList.FirstOrDefault(currentCustomer => email == currentCustomer.Email);
		}
		static bool IsExistingCustomer(String email)
		{
			var customerListService = new StripeCustomerService();
			var customerList = customerListService.List();

			return customerList.Any(currentCustomer => email == currentCustomer.Email);
		}
        public HttpResponseMessage Delete(string id, int organizationId, CancelReason cancelReason, string cancelText)
        {
            OrganizationId = organizationId;
            try
            {
                if (UserIsAdminOfOrganization)
                {

                    var customerService = new StripeCustomerService();
                    StripeSubscription stripeSubscription = customerService.CancelSubscription(id);    // you can optionally pass cancelAtPeriodEnd instead of immediately cancelling 

                    var organization = this.organizationService.Get(organizationId);
                    organization.Subscription.Status = SubscriptionStatus.INACTIVE;
                    organization.Subscription.CustomerBillingId = id;
                    organization.Subscription.CancelReason = cancelReason;

                    this.subscriptionService.SaveSubscription(organization);
                    emailHelper.SendCancelNotice(id, organizationId, System.Enum.GetName(typeof(CancelReason), cancelReason), cancelText);
                    return Request.CreateResponse(HttpStatusCode.Accepted);
                }
            }
            catch (StripeException ex)
            {
                emailHelper.SendStripeError(ex);
            }
            catch (Exception e)
            {
                emailHelper.SendErrorEmail(e);
            }
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
        private async Task CreateCustomer(StripeModel model)
        {
            await Task.Run(() =>
            {
                // create customer based on validated token from stripe.js 
                var myCustomer = new StripeCustomerCreateOptions();

                // assign token to a credit card option for a user
                myCustomer.Card = new StripeCreditCardOptions()
                {
                    TokenId = model.Token
                };

                myCustomer.Email = User.Identity.Name;
                myCustomer.Description = User.Identity.Name;
                myCustomer.PlanId = model.SubscriptionType.ToString();
                myCustomer.Quantity = 1;
                
                // create customer in stripe service
                var customerService = new StripeCustomerService();
                StripeCustomer stripeCustomer = customerService.Create(myCustomer);

                // get subscription Id from created user
                var subscriptionID = stripeCustomer.StripeSubscriptionList.StripeSubscriptions.FirstOrDefault().Id;              
                       
             // save credit card optional details 
                StripeCustomerService customerServic = new StripeCustomerService();
                stripeCustomer = customerService.Get(stripeCustomer.Id);
                var cardId = stripeCustomer.StripeDefaultCardId; // get card id
                var myCard = new StripeCardUpdateOptions();

                myCard.Name = model.CardHolderName;
                myCard.AddressLine1 = model.AddressLine1;
                myCard.AddressLine2 = model.AddressLine2;
                myCard.AddressCity = model.AddressCity;
                myCard.AddressZip = model.AddressPostcode;
                myCard.AddressCountry = model.AddressCountry;

                var cardService = new StripeCardService();
                StripeCard stripeCard = cardService.Update(stripeCustomer.Id, cardId, myCard);
            //........................
                
                // record customer in database
                var cust = getCustomer();
                if(cust == null) // new users
                {
                    // get values to create a new record in StripeCustomer table
                    StripeCustomers customer = new StripeCustomers();
                
                    customer.CustomerName = User.Identity.Name;
                    customer.StripeCustomerID = stripeCustomer.Id;
                    customer.StripeSubscriptionID = subscriptionID;
                    customer.SubscriptionType = model.SubscriptionType.ToString();
                    customer.HasSubscription = true;
                    customer.Interval = "Monthly";
                    customer.StartDate = TimeConverter.ConvertToLocalTime(DateTime.Now, "GMT Standard Time");
                    if (model.SubscriptionType.ToString() == "standard")
                    {
                        customer.TrialValidUntil = currentTime.AddDays(30);
                    }
                    db.StripeCustomers.Add(customer);
                    }
                    else // user with db records
                    {
                        StripeCustomers newRecord = new StripeCustomers();

                        // take the data from current user
                        newRecord.StripeCustomerID = stripeCustomer.Id;
                        newRecord.CustomerName = User.Identity.Name;
                        newRecord.StripeSubscriptionID = subscriptionID;
                        newRecord.SubscriptionType = model.SubscriptionType.ToString();
                        newRecord.HasSubscription = true;
                        newRecord.Interval = "Monthly";
                        newRecord.StartDate = currentTime;
                        if (model.SubscriptionType.ToString() == "standard")
                        {
                            newRecord.TrialValidUntil = currentTime.AddDays(30);
                        }
                        db.StripeCustomers.Add(newRecord);

                        // delete customer's old record in database
                        db.StripeCustomers.Remove(cust);
                    }
                db.SaveChanges();
            });
        }
Example #26
0
        /// <summary>
        /// Updates a customer record, using the given payment token
        /// NOTE: Save changes on the underlying context for the model after calling this method
        /// </summary>
        /// <param name="user"></param>
        /// <param name="paymentToken"></param>
        public static void UpdateCustomer(IStripeUser user, string paymentToken = null)
        {
            var customerUpdate = new StripeCustomerUpdateOptions() { Email = user.Email };

            // Create a token for this payment token
            customerUpdate.Card = new StripeCreditCardOptions() { TokenId = paymentToken };

            var customerService = new StripeCustomerService();
            StripeCustomer stripeCustomer = customerService.Update(user.PaymentSystemId, customerUpdate);

            System.Diagnostics.Trace.TraceInformation("Updated customer in stripe: '{0}' with id '{1}", user.Email, user.PaymentSystemId);
        }
Example #27
0
        public UpdateCustomerResponse UpdateSubscription(UpdateCustomerRequest req)
        {
            var response = new UpdateCustomerResponse();

            try
            {
                    // Update Customer
                    var myCustomer = new StripeCustomerUpdateSubscriptionOptions();

                    if (req.CreditCard.CardNumber.Trim().Length > 0)
                    {
                        myCustomer.CardNumber = req.CreditCard.CardNumber;
                        myCustomer.CardExpirationYear = req.CreditCard.ExpirationYear.ToString();
                        myCustomer.CardExpirationMonth = req.CreditCard.ExpirationMonth.ToString();
                        myCustomer.CardAddressCountry = "US";                 // optional
                        //myCustomer.CardAddressLine1 = "24 Beef Flank St";   // optional
                        //myCustomer.CardAddressLine2 = "Apt 24";             // optional
                        //myCustomer.CardAddressState = "NC";                 // optional
                        myCustomer.CardAddressZip = req.PostalCode; //        // optional
                        myCustomer.CardName = req.CreditCard.CardHolderName;  // optional
                        if (req.CreditCard.SecurityCode.Length > 0)
                        {
                            myCustomer.CardCvc = req.CreditCard.SecurityCode;
                        }
                    }

                    myCustomer.PlanId = req.PlanId;

                    var customerService = new StripeCustomerService();
                    StripeSubscription result = customerService.UpdateSubscription(req.CustomerId, myCustomer);
                    
                    response.Success = true;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = "Unable to update subscription: " + ex.Message;
            }

            return response;
        }
 public StripeBillingCustomerService(string apiKey, IMapper mapper)
 {
     _service = new StripeCustomerService(apiKey);
     _mapper = mapper;
 }
        public static bool ChargeFailed(StripeEvent se, string json)
        {
            try
            {

                var dc = new ManagementContext();
                RDN.Library.DataModels.PaymentGateway.Stripe.StripeEventDb even = new RDN.Library.DataModels.PaymentGateway.Stripe.StripeEventDb();
                even.CreatedStripeDate = se.Created.GetValueOrDefault();
                even.StripeId = se.Id;
                even.LiveMode = se.LiveMode.GetValueOrDefault();
                if (se.Data != null)
                {
                    //StripeCharge inv = (StripeCharge)se.Data.Object;
                    StripeCharge inv = Stripe.Mapper<StripeCharge>.MapFromJson(se.Data.Object.ToString());
                    StripeChargeDb nnv = new StripeChargeDb();
                    even.StripeEventTypeEnum = (byte)StripeEventTypeEnum.charge_failed;
                    nnv.AmountInCents = inv.AmountInCents;
                    nnv.AmountInCentsRefunded = inv.AmountInCentsRefunded;
                    nnv.Currency = inv.Currency;
                    nnv.Customer = dc.StripeCustomers.Where(x => x.Id == inv.CustomerId).FirstOrDefault();
                    nnv.Description = inv.Description;
                    nnv.FailureMessage = inv.FailureMessage;

                    nnv.FeeInCents = inv.FeeInCents;
                    nnv.Id = inv.Id;
                    nnv.Invoice = dc.StripeInvoices.Where(x => x.Id == inv.InvoiceId).FirstOrDefault();
                    nnv.LiveMode = inv.LiveMode;
                    nnv.Paid = inv.Paid;
                    nnv.Refunded = inv.Refunded;
                    if (inv.StripeCard != null)
                    {
                        nnv.StripeCard = dc.StripeCards.Where(x => x.AddressLine1 == inv.StripeCard.AddressLine1).Where(x => x.Last4 == inv.StripeCard.Last4).FirstOrDefault();
                        if (nnv.StripeCard == null)
                        {
                            nnv.StripeCard = CreateStripeCard(inv.StripeCard, json);
                            dc.StripeCards.Add(nnv.StripeCard);
                        }
                    }
                    even.Charge = nnv;
                    dc.StripeCharges.Add(nnv);

                    var invoice = (from xx in dc.Invoices
                                   where xx.PaymentProviderCustomerId == inv.CustomerId
                                   where xx.InvoicePaid == false
                                   select xx).OrderByDescending(x => x.Created).FirstOrDefault();
                    if (invoice == null)
                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "STRIPE: Invoice Not Found, Can't Be Confirmed, CHARGE FAILED", inv.CustomerId + " " + inv.ToString() + json);
                    else
                    {
                        if (invoice.InvoiceStatus == (byte)InvoiceStatus.Subscription_Should_Be_Updated_On_Charge)
                        {
                            //update league subscription
                            //League.League.UpdateLeagueSubscriptionPeriod(invoice.Subscription.ValidUntil, true, invoice.Subscription.InternalObject);
                            //EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "STRIPE: Subscription Updated!!", invoice.InvoiceId + " Amount:" + inv.AmountInCents + ":" + inv.ToString() + json);
                        }

                        invoice.InvoicePaid = false;
                        if (nnv.FailureMessage == null)
                        {
                            invoice.InvoiceStatus = (byte)InvoiceStatus.Failed;
                            nnv.FailureMessage = "Payment Declined, Please contact RDNation @ [email protected].";
                        }
                        else if (nnv.FailureMessage.Contains("Your card number is incorrect"))
                            invoice.InvoiceStatus = (byte)InvoiceStatus.Card_Was_Declined;
                        else
                            invoice.InvoiceStatus = (byte)InvoiceStatus.Failed;

                        invoice.InvoiceStatusUpdated = DateTime.UtcNow;
                        invoice.Merchant = invoice.Merchant;

                        var customerService = new StripeCustomerService();
                        StripeSubscription subscription = customerService.CancelSubscription(inv.CustomerId, true);

                        EmailLeagueAboutCardDeclinedSubscription(invoice.Subscription.InternalObject, invoice.InvoiceId, nnv.FailureMessage, ServerConfig.LEAGUE_SUBSCRIPTION_UPDATESUBSUBSCRIBE + invoice.Subscription.InternalObject.ToString().Replace("-", ""), ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN);
                    }

                }
                dc.StripeEvents.Add(even);
                dc.SaveChanges();

                return true;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: json);
            }
            return false;
        }
Example #30
-1
        /// <summary>
        ///     Implements <see cref="IStripeService.CreateCustomer"/>
        /// </summary>
        public string CreateCustomer(User user)
        {
            var myCustomer = new StripeCustomerCreateOptions
            {
                Email = user.Email,
                Description = $"{user.FirstName} {user.LastName} ({user.Email})"
            };

            var customerService = new StripeCustomerService();

            try
            {
                StripeCustomer customer = customerService.Create(myCustomer);
                return customer.Id;
            }
            catch (StripeException ex)
            {
                string exceptionMessage;
                StripeExceptionType type;

                if (ex.HttpStatusCode >= HttpStatusCode.InternalServerError
                    || (int)ex.HttpStatusCode == 429 /* Too Many Requests */
                    || (int)ex.HttpStatusCode == 402 /* Request Failed */)
                {
                    type = StripeExceptionType.ServiceError;
                    exceptionMessage = 
                        "An error occured while creating a customer account for you. Please try again later.";
                }
                else if (ex.HttpStatusCode == HttpStatusCode.Unauthorized)
                {
                    // Note: We want to log this as it means we don't have a valid API key
                    Debug.WriteLine("Stripe API Key is Invalid");
                    Debug.WriteLine(ex.Message);

                    type = StripeExceptionType.ApiKeyError;
                    exceptionMessage = "An error occured while talking to one of our backends. Sorry!";
                }
                else
                {
                    // Note: Log unknown errors
                    Debug.WriteLine(ex.HttpStatusCode);
                    Debug.WriteLine($"Stripe Type: {ex.StripeError.ErrorType}");
                    Debug.WriteLine($"Stripe Message: {ex.StripeError.Message}");
                    Debug.WriteLine($"Stripe Code: {ex.StripeError.Code}");
                    Debug.WriteLine($"Stripe Param: {ex.StripeError.Parameter}");

                    type = StripeExceptionType.UnknownError;
                    exceptionMessage = 
                        "An unknown error occured while creating a customer account for you. Please try again later.";
                }

                throw new StripeServiceException(exceptionMessage, type, ex);
            }
        }