Ejemplo n.º 1
0
        private bool CreateNewStripeCustomer(string email, string token, int quantity, UserInfo userInfo)
        {
            //create new customer
            var myCustomer = new StripeCustomerCreateOptions();

            myCustomer.Email    = email;
            myCustomer.TokenId  = token;
            myCustomer.PlanId   = Constants.StripeSubscriptionPlan;
            myCustomer.Quantity = quantity;

            var customerService = new StripeCustomerService();

            try
            {
                StripeCustomer stripeCustomer = customerService.Create(myCustomer);

                //save profile ID and profile status with user info
                userInfo.Subscribed            = true;
                userInfo.PaymentCustomerId     = stripeCustomer.Id;
                userInfo.PaymentCustomerStatus = stripeCustomer.StripeSubscription.Status;
                db.Entry(userInfo).State       = EntityState.Modified;
            }
            catch (Exception e)
            {
                Utilities.LogAppError("Create/Subscribe failed: " + e.Message);
                return(false);
            }

            return(true);
        }
        public async Task WhenStripeModeIsLive_ItShouldCreateACustomer()
        {
            this.apiKeyRepository.Setup(v => v.GetApiKey(UserType.StandardUser)).Returns(LiveKey);

            var expectedOptions = new StripeCustomerCreateOptions
            {
                Description = UserId.ToString(),
                Source      = new StripeSourceOptions
                {
                    TokenId = TokenId,
                }
            };

            var customer = new StripeCustomer {
                Id = CustomerId
            };

            this.stripeService.Setup(v => v.CreateCustomerAsync(
                                         It.Is <StripeCustomerCreateOptions>(
                                             x => JsonConvert.SerializeObject(x, Formatting.None) == JsonConvert.SerializeObject(expectedOptions, Formatting.None)),
                                         LiveKey))
            .ReturnsAsync(customer);

            var result = await this.target.ExecuteAsync(UserId, TokenId, UserType.StandardUser);

            Assert.AreEqual(CustomerId, result);
        }
Ejemplo n.º 3
0
        static void TestInvoices2(StripePayment payment)
        {
            StripeCustomer cust     = payment.GetCustomer("cus_ulcOcy5Seu2dpq");
            StripePlanInfo planInfo = new StripePlanInfo {
                Amount   = 1999,
                ID       = "testplan",
                Interval = StripePlanInterval.Month,
                Name     = "The Test Plan",
                //TrialPeriod = 7
            };
            //payment.DeletePlan (planInfo.ID);
            StripePlan             plan    = payment.CreatePlan(planInfo);
            StripeSubscriptionInfo subInfo = new StripeSubscriptionInfo {
                Card    = GetCC(),
                Plan    = planInfo.ID,
                Prorate = true
            };
            StripeSubscription sub = payment.Subscribe(cust.ID, subInfo);

            payment.CreateInvoiceItem(new StripeInvoiceItemInfo {
                CustomerID  = cust.ID,
                Amount      = 1337,
                Description = "Test single charge"
            });

            var           invoices = payment.GetInvoices(0, 10, cust.ID);
            StripeInvoice upcoming = payment.GetUpcomingInvoice(cust.ID);

            payment.Unsubscribe(cust.ID, true);
            payment.DeletePlan(planInfo.ID);
            foreach (StripeLineItem line in upcoming)
            {
                Console.WriteLine("{0} for type {1}", line.Amount, line.GetType());
            }
        }
Ejemplo n.º 4
0
        public ActionResult Index(string jsonCardInformation)
        {
            JObject jObject    = JObject.Parse(jsonCardInformation);
            string  key        = ConfigurationManager.AppSettings["StripeSecretKey"];
            var     myCustomer = new StripeCustomerCreateOptions();

            myCustomer.Email       = System.Web.HttpContext.Current.User.Identity.Name;
            myCustomer.Description = "Testing a Card";
            myCustomer.SourceToken = jObject["tokenId"].ToString();
            var customerService = new StripeCustomerService();
            StripeRequestOptions requestOption = new StripeRequestOptions()
            {
                ApiKey = key
            };
            StripeCustomer stripeCustomer = new StripeCustomer();

            stripeCustomer = customerService.Create(myCustomer, requestOption);
            CardInfo newCustomer = new CardInfo()
            {
                CustomerId = stripeCustomer.Id,
                Email      = System.Web.HttpContext.Current.User.Identity.Name,
                Name       = jObject["name"].ToString(),
                CardType   = jObject["cardBrand"].ToString(),
                LastFour   = jObject["lastFour"].ToString()
            };

            ctx.Cards.Add(newCustomer);
            ctx.SaveChanges();
            var x = ctx.Cards.Where(y => y.Email == System.Web.HttpContext.Current.User.Identity.Name);

            return(View(x));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Gets the default card associated with this customer
        /// </summary>
        /// <param name="customer"></param>
        /// <returns></returns>
        public static StripeCard GetDefaultCard(this StripeCustomer customer)
        {
            if (customer.StripeDefaultCard != null)
            {
                return(customer.StripeDefaultCard);
            }

            if (string.IsNullOrEmpty(customer.StripeDefaultCardId))
            {
                return(null);
            }

            if (customer.StripeCardList == null)
            {
                return(null);
            }

            foreach (StripeCard card in customer.StripeCardList.StripeCards)
            {
                if (card.Id == customer.StripeDefaultCardId)
                {
                    return(card);
                }
            }

            return(null);
        }
Ejemplo n.º 6
0
        public StripeCustomer CreateStripeCustomer(string sEmail, string sToken, string sInputDiscountCode)
        {
            try
            {
                StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["stripeApi_LiveKey"]);
                var customerService = new StripeCustomerService();

                string sDiscountCode = ConfigurationManager.AppSettings["discount_code"];

                var CustomerOptions = new StripeCustomerCreateOptions()
                {
                    Email          = sEmail,
                    Description    = "EmediCodes Basic Plan for " + sEmail,
                    AccountBalance = 0,
                    PlanId         = "1",
                    SourceToken    = sToken,
                    TrialEnd       = DateTime.Now + TimeSpan.FromDays(14)
                };

                if (sInputDiscountCode.Equals(sDiscountCode))
                {
                    CustomerOptions.CouponId = sDiscountCode;
                }

                StripeCustomer customer = customerService.Create(CustomerOptions);

                return(customer);
            }
            catch (Exception ex)
            {
                oLogger.LogData("METHOD: CreateStripeCustomer; ERROR: TRUE; EXCEPTION: " + ex.Message + "; INNER EXCEPTION: " + ex.InnerException + "; STACKTRACE: " + ex.StackTrace);
                throw;
            }
        }
Ejemplo n.º 7
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);
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                StripeCustomer current = GetCustomer();
                // int? days = getaTraildays();
                //if (days != null)
                //{
                int chargetotal = 500;//Convert.ToInt32((3.33*Convert.ToInt32(days)*100));
                var mycharge    = new StripeChargeCreateOptions();
                mycharge.Amount     = chargetotal;
                mycharge.Currency   = "USD";
                mycharge.CustomerId = current.Id;
                string       key           = "sk_test_5jzcBuYhyxAk08sB8mT7KL43";
                var          chargeservice = new StripeChargeService(key);
                StripeCharge currentcharge = chargeservice.Create(mycharge);
                error.Visible   = true;
                error.InnerText = "La transacción se realizo con éxito";
            }
            catch (StripeException ex)
            {
                error.Visible   = true;
                error.InnerText = ex.Message;
            }
            catch
            {
                error.Visible = true;

                error.InnerText = "Error en la transacción";
            }
            //}
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Gets the default card associated with this customer
        /// </summary>
        /// <param name="customer"></param>
        /// <returns></returns>
        public static StripeCard GetDefaultSource(this StripeCustomer customer)
        {
            if (customer.DefaultSource != null)
            {
                return(customer.DefaultSource);
            }

            if (string.IsNullOrEmpty(customer.DefaultSourceId))
            {
                return(null);
            }

            if (customer.SourceList == null || customer.SourceList.Data == null)
            {
                return(null);
            }

            foreach (StripeCard card in customer.SourceList.Data)
            {
                if (card.Id == customer.DefaultSourceId)
                {
                    return(card);
                }
            }

            return(null);
        }
Ejemplo n.º 10
0
        public string CreateCustomerObject(CustomerObjectRequest cardTokenRequest)
        {
            var customerCreateOptions = new StripeCustomerCreateOptions();

            customerCreateOptions.TokenId = cardTokenRequest.CardToken;

            //these are all optional
            customerCreateOptions.Email       = "*****@*****.**";
            customerCreateOptions.Description = "I am a tasty customer";
            var metaData = new Dictionary <string, string>();

            metaData.Add("opentableId", "123456");
            customerCreateOptions.Metadata = metaData;

            var customerService = new StripeCustomerService(ConfigurationManager.AppSettings["masterMerchantSecretkey"]);

            try
            {
                StripeCustomer createdCustomer = customerService.Create(customerCreateOptions);
                return(createdCustomer.Id);
            }
            catch (StripeException sx)
            {
                //do some logging
            }

            return("");
        }
        private StripeCustomer GetCustomerById(string customerId)
        {
            var            customerService = new StripeCustomerService();
            StripeCustomer stripeCustomer  = customerService.Get(customerId);

            return(stripeCustomer);
        }
        public ActionResult SubmitStripeSubscriptionForm(StripeSubscriptionCheckout model)
        {
            if (ModelState.IsValid)
            {
                var loggedOnMember = Members.GetCurrentMember();
                var memberService  = Services.MemberService;
                var member         = memberService.GetById(loggedOnMember.Id);

                var customer = new StripeCustomerCreateOptions();
                customer.Email       = member.Email;
                customer.Description = member.Name;

                customer.SourceToken = model.StripeToken;
                customer.PlanId      = model.PlanId;
                try
                {
                    var            customerService = new StripeCustomerService(SensativeInformation.StripeKeys.SecretKey);
                    StripeCustomer stripeCustomer  = customerService.Create(customer);

                    //Log customer id on member
                    member.SetValue("stripeUserId", stripeCustomer.Id);
                    memberService.Save(member);
                    return(RedirectToCurrentUmbracoPage());
                }
                catch (StripeException e)
                {
                    _log.Error(e.StripeError.Message);
                    ModelState.AddModelError("",
                                             "There was an error setting up your subscription. Please try again. If the issue persists please contact us");
                }
            }
            return(CurrentUmbracoPage());
        }
        public StripePlan GetUserPlan(string customerId)
        {
            var            customerService = new StripeCustomerService();
            StripeCustomer stripeCustomer  = customerService.Get(customerId);

            return(stripeCustomer.Subscriptions.First().StripePlan);
        }
Ejemplo n.º 14
0
        public StripeSubscription CreateSubscription(PurchaseInformation info, string customerIdOfStripe)
        {
            try
            {
                var customer = new StripeCustomerUpdateOptions();

                customer.SourceCard = new SourceCard()
                {
                    Number          = info.CC_number,
                    ExpirationYear  = Convert.ToInt32(info.ExpireYear),
                    ExpirationMonth = Convert.ToInt32(info.ExpireMonth),
                    Cvc             = info.CCVCode,
                    Name            = info.NameOnCard
                };


                if (!string.IsNullOrEmpty(info.Coupon))
                {
                    customer.Coupon = info.Coupon;
                }


                var            customerService = new StripeCustomerService();
                StripeCustomer stripeCustomer  = customerService.Update(customerIdOfStripe, customer);

                var subscriptionService = new StripeSubscriptionService();
                StripeSubscription stripeSubscription = subscriptionService.Create(customerIdOfStripe, info.PlanId); // optional StripeSubscriptionCreateOptions
                return(stripeSubscription);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 15
0
        public void TestCustomers()
        {
            // SUBSCRIBE

            // Arrange
            ICustomerEntity customer = CreateMockCustomer();

            // Act
            StripeManager.CreateCustomer(customer);

            // Assert
            Assert.IsNotNull(customer.PaymentSystemId);

            // RETRIEVE

            // Act
            StripeCustomer stripeCustomer = StripeManager.RetrieveCustomer(customer);

            // Assert
            Assert.IsNotNull(stripeCustomer);

            // UPDATE

            // Arrange
            customer.Email = "*****@*****.**";

            // act
            StripeCustomer updatedStripeCustomer = StripeManager.UpdateCustomer(customer);

            // Assert
            Assert.IsNotNull(updatedStripeCustomer);
        }
Ejemplo n.º 16
0
        public customers_fixture()
        {
            CustomerCreateOptionsWithShipping = new StripeCustomerCreateOptions
            {
                Email       = "*****@*****.**",
                SourceToken = "tok_visa",
                Shipping    = new StripeShippingOptions
                {
                    Name    = "Namey Namerson",
                    Line1   = "123 Main St",
                    Line2   = "Apt B",
                    Country = "USA",
                    State   = "NC",
                }
            };

            var service = new StripeCustomerService(Cache.ApiKey);

            CustomerWithShipping = service.Create(CustomerCreateOptionsWithShipping);

            CustomerUpdateOptionsWithShipping = new StripeCustomerUpdateOptions
            {
                Email    = "*****@*****.**",
                Shipping = CustomerCreateOptionsWithShipping.Shipping
            };
            CustomerUpdateOptionsWithShipping.Shipping.Phone = "8675309";

            UpdatedCustomerWithShipping = service.Update(CustomerWithShipping.Id, CustomerUpdateOptionsWithShipping);
        }
        public ActionResult <SuccessResponse> UpdateStatus(UserUpdateStatusRequest model)
        {
            int          sCode    = 200;
            BaseResponse response = null;

            try
            {
                _adminService.UpdateStatus(model);

                if (model.UserStatusId == 2)
                {
                    StripeCustomer customer = _stripeService.GetStripeCustomerByUserId(model.Id);
                    if (customer.SubscriptionTypeId != 1)
                    {
                        _stripeService.CancelSubscription(customer.SubscriptionId);
                        _stripeService.UpdateCustomerSubscriptions(model.Id, "none", "none");
                    }
                }
                response = new SuccessResponse();
            }
            catch (Exception ex)
            {
                sCode = 500;
                base.Logger.LogError(ex.ToString());
                response = new ErrorResponse($"Generic Errors: { ex.Message }");
            }


            return(StatusCode(sCode, response));
        }
Ejemplo n.º 18
0
        public ActionResult Subscribe(StripeTokenResponse data)
        {
            var myCustomer = new StripeCustomerCreateOptions();

            myCustomer.Email       = User.Identity.Name;
            myCustomer.SourceToken = data.StripeToken;
            myCustomer.PlanId      = ConfigurationManager.AppSettings["stripe:plan"]; // only if you have a plan
            myCustomer.TaxPercent  = 0;                                               // only if you are passing a plan, this tax percent will be added to the price.

            Metrics.Info($"Creating subscription for {myCustomer.Email} {myCustomer.SourceToken} {myCustomer.PlanId}");


            var            customerService = new StripeCustomerService(ConfigurationManager.AppSettings["stripe:token_secret"]);
            StripeCustomer stripeCustomer  = customerService.Create(myCustomer);


            using (var db = new Email2SmsContext())
            {
                var userId = GetUserId();
                var row    = db.Subscriptions.FirstOrDefault(f => f.User == userId);
                if (row == null)
                {
                    row = new Subscription {
                        User = userId
                    };
                    db.Subscriptions.Add(row);
                }
                row.StripeCustomer = stripeCustomer.Id;
                row.LastInvoiceUtc = DateTime.UtcNow;
                db.SaveChanges();
            }

            return(Redirect("~/home/setup"));
        }
Ejemplo n.º 19
0
        public bool CheckCustomerPaymentMethod(string sStripeCustomerId)
        {
            try
            {
                StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["stripeApi_LiveKey"]);

                bool blnPaymentMethodExists = false;

                var            customerService = new StripeCustomerService();
                StripeCustomer customer        = customerService.Get(sStripeCustomerId);

                if (!customer.Sources.Any())
                {
                    return(blnPaymentMethodExists);
                }
                else
                {
                    blnPaymentMethodExists = true;
                    return(blnPaymentMethodExists);
                }
            }
            catch (Exception ex)
            {
                oLogger.LogData("METHOD: CheckCustomerPaymentMethod; ERROR: TRUE; EXCEPTION: " + ex.Message + "; INNER EXCEPTION: " + ex.InnerException + "; STACKTRACE: " + ex.StackTrace);
                throw;
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Creates a new customer record in Stripe for the given user
        /// This will set the "PaymentSystemId" property on the given IStripeUser instance if the user was successfully created
        /// NOTE: Save changes on the underlying context for the model after calling this method
        /// </summary>
        /// <param name="customer"></param>
        /// <param name="paymentToken"></param>
        public static StripeCustomer CreateCustomer(ICustomerEntity customer, string paymentToken = null)
        {
            // Do not overwrite the user, ever
            if (customer.HasPaymentInfo())
            {
                return(null);
            }

            var newCustomer = new StripeCustomerCreateOptions();

            newCustomer.Email = customer.Email;

            if (paymentToken != null)
            {
                newCustomer.Source = new StripeSourceOptions()
                {
                    TokenId = paymentToken
                }
            }
            ;

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

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

            Logger.Log <StripeManager>("Created customer in stripe: '{0}' with id '{1}", LogLevel.Information, customer.Email, customer.PaymentSystemId);

            return(stripeCustomer);
        }
Ejemplo n.º 21
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);
        }
Ejemplo n.º 22
0
        private StripeCustomer createTCGStripeCustomer(StorePaymentMethod_Details details, string sourceToken)
        {
            StripeConfiguration.SetApiKey(secretKey);
            StripeCustomer customer = new StripeCustomer();

            try
            {
                StripeSource source = new StripeSource();
                if (sourceToken == null)
                {
                    source = createStripeSource(details.CardNumber, details.CardExpiryYear, details.CardExpiryMonth, details.CardCVV, details.CardHolderFullName, true);
                }
                else
                {
                    source.Id = sourceToken;
                }
                //ATTACH THE SOURCE TO CUSTOMER
                var customerOptions = new StripeCustomerCreateOptions()
                {
                    SourceToken = source.Id
                };

                var customerService = new StripeCustomerService();
                customer = customerService.Create(customerOptions);
            }
            catch (StripeException e)
            {
                throw new StripeException(e.HttpStatusCode, e.StripeError, e.Message);
            }
            return(customer);
        }
Ejemplo n.º 23
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);
        }
Ejemplo n.º 24
0
        void IEmailHelper.SendSubscriptionCancelled(StripeCustomer customer, string customerEmail, string customerName)
        {
            Guard.ArgumentNotNullOrEmptyString(customerName, "customerName");
            Guard.ArgumentNotNullOrEmptyString(customerEmail, "customerEmail");
            Guard.ArgumentNotNull(() => customer);

            Dictionary <string, string> values = new Dictionary <string, string>();

            values.Add("FirstName", customerName);
            values.Add("Date", customer.StripeSubscription.TrialEnd.ToString());

            var    send     = this as IEmailHelper;
            string fileName = String.Empty;

            if (root.Contains("~"))
            {
                fileName = System.Web.HttpContext.Current.Server.MapPath(root + "SubscriptionCancelled.txt");
            }
            else
            {
                fileName = root + "SubscriptionCancelled.txt";
            }

            send.SetupEmail(values, customerEmail, fileName, "We Need You Have. Subscription Cancelled Notice.");
        }
Ejemplo n.º 25
0
        public bool Post([FromBody] JObject report)
        {
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("Username", report.Property("username").Value.ToString());

            List <Subscription> sub = new Subscription().SearchDocument(parameters);

            if (sub.Count <= 0)
            {
                StripeConfiguration.SetApiKey("sk_test_p9FWyo0hC9g8y39CkRR1pnYH");

                var options = new StripeCustomerCreateOptions {
                    Email       = report.Property("email").Value.ToString(),
                    SourceToken = report.Property("id").Value.ToString()
                };
                var            service  = new StripeCustomerService();
                StripeCustomer customer = service.Create(options);

                DoSub(customer, report);
            }
            else
            {
                updateSubscription(report);
            }



            return(true);
        }
        public static Customer ToCustomer(this StripeCustomer stripeCustomer)
        {
            var customer = new Customer
            {
                Id            = stripeCustomer.Id,
                Name          = stripeCustomer.Description,
                Email         = stripeCustomer.Email,
                DefaultSource = stripeCustomer.DefaultSourceId
            };

            if (stripeCustomer.Metadata != null)
            {
                if (stripeCustomer.Metadata.ContainsKey("Name"))
                {
                    customer.Name = stripeCustomer.Metadata["Name"];
                }
                if (stripeCustomer.Metadata.ContainsKey("BusinessName"))
                {
                    customer.BusinessName = stripeCustomer.Metadata["BusinessName"];
                }
                if (stripeCustomer.Metadata.ContainsKey("abn"))
                {
                    customer.Abn = stripeCustomer.Metadata["abn"];
                }
            }
            return(customer);
        }
Ejemplo n.º 27
0
        static void TestCreateInvoiceItems(StripePayment payment)
        {
            StripeCustomer        cust = payment.CreateCustomer(new StripeCustomerInfo());
            StripeInvoiceItemInfo info = GetInvoiceItemInfo();

            info.CustomerID = cust.ID;
            StripeInvoiceItem     item    = payment.CreateInvoiceItem(info);
            StripeInvoiceItemInfo newInfo = GetInvoiceItemInfo();

            newInfo.Description = "Invoice item: " + Guid.NewGuid().ToString();
            StripeInvoiceItem item2 = payment.UpdateInvoiceItem(item.ID, newInfo);
            StripeInvoiceItem item3 = payment.GetInvoiceItem(item2.ID);

            if (item.Description == item3.Description)
            {
                throw new Exception("Update failed");
            }
            StripeInvoiceItem deleted = payment.DeleteInvoiceItem(item2.ID);

            if (!deleted.Deleted.HasValue && deleted.Deleted.Value)
            {
                throw new Exception("Delete failed");
            }
            var items = payment.GetInvoiceItems(10, 10, null);

            Console.WriteLine(items.Total);
            payment.DeleteCustomer(cust.ID);
        }
        public void Create(string userName, Plan plan, string stripeToken)
        {
            //get User
            var user = UserManager.FindByName(userName);

            if (string.IsNullOrEmpty(user.StripeCustomerId))  //First Time customer
            {
                //create customer which will create subscription if plan is set and cc info via token is provided
                var customer = new StripeCustomerCreateOptions()
                {
                    Email  = user.Email,
                    Source = new StripeSourceOptions()
                    {
                        TokenId = stripeToken
                    },
                    PlanId = plan.ExternalId  //external id is Stripe plan id
                };

                StripeCustomer stripeCustomer = StripeCustomerService.Create(customer);

                //update user
                user.StripeCustomerId = stripeCustomer.Id;
                user.ActiveUntil      = DateTime.Now.AddDays((double)plan.TrialPeriodDays);
                UserManager.Update(user);
            }
            else
            {
                //customer already exists, add subscription to customer
                var stripeSubscription = StripeSubscriptionService.Create(user.StripeCustomerId, plan.ExternalId);
                user.ActiveUntil = DateTime.Now.AddDays((double)plan.TrialPeriodDays);
                UserManager.Update(user);
            }
        }
Ejemplo n.º 29
0
        public StripeSubscription SubscribeToPlan(ApplicationUser dbUser, string stripeToken, string planToSubscribeTo)
        {
            StripeCustomer customer = CreateStripeCustomer(dbUser, stripeToken);
            var            currentSubscriptionId = String.Empty;

            if (customer.Subscriptions != null && customer.Subscriptions.TotalCount > 0)
            {
                currentSubscriptionId = customer.Subscriptions.Data[0].Id;
            }

            var service = new StripeSubscriptionService();
            StripeSubscription subscription = null;

            if (String.IsNullOrEmpty(currentSubscriptionId))
            {
                subscription = AddNewUserSubscription(customer.Id, planToSubscribeTo, service, dbUser);
            }
            else if (!planToSubscribeTo.Contains("Free"))
            {
                subscription = UpdateUserSubscription(customer.Id, currentSubscriptionId, planToSubscribeTo, service, dbUser);
            }
            else
            {
                CancleCustomerSubscription(dbUser);
            }

            return(subscription);
        }
Ejemplo n.º 30
0
        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);
        }