Пример #1
0
        public subscription_fixture()
        {
            SubscriptionCreateOptions = new StripeSubscriptionCreateOptions
            {
                TrialEnd = DateTime.Now.AddMinutes(5),
                Items    = new List <StripeSubscriptionItemOption>
                {
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan().Id, Quantity = 1
                    },
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan("silver").Id, Quantity = 2
                    }
                },
                BillingCycleAnchor = DateTime.UtcNow.AddDays(1),
            };

            var service     = new StripeSubscriptionService(Cache.ApiKey);
            var customer_id = Cache.GetCustomer().Id;

            Subscription = service.Create(customer_id, SubscriptionCreateOptions);
            service.Create(customer_id, SubscriptionCreateOptions);
            SubscriptionList = service.List(new StripeSubscriptionListOptions {
                CustomerId = customer_id
            });

            SubscriptionUpdateOptions = new StripeSubscriptionUpdateOptions
            {
                Items = new List <StripeSubscriptionItemUpdateOption>
                {
                    new StripeSubscriptionItemUpdateOption {
                        Id = Subscription.Items.Data[0].Id, Deleted = true
                    },
                    new StripeSubscriptionItemUpdateOption
                    {
                        Id       = Subscription.Items.Data[1].Id,
                        Quantity = 5,
                        Metadata = new Dictionary <string, string> {
                            { "key", "value" }
                        }
                    }
                }
            };

            SubscriptionUpdated = service.Update(Subscription.Id, SubscriptionUpdateOptions);

            SubscriptionEndedOptions = new StripeSubscriptionUpdateOptions
            {
                EndTrialNow = true
            };

            SubscriptionEnded = service.Update(Subscription.Id, SubscriptionEndedOptions);
        }
Пример #2
0
        public creating_and_updating_subscriptions_with_manual_invoicing()
        {
            var customerService     = new StripeCustomerService(Cache.ApiKey);
            var subscriptionService = new StripeSubscriptionService(Cache.ApiKey);

            var CustomerCreateOptions = new StripeCustomerCreateOptions
            {
                Email = "*****@*****.**",
            };
            var Customer = customerService.Create(CustomerCreateOptions);

            var SubscriptionCreateOptions = new StripeSubscriptionCreateOptions
            {
                Billing      = StripeBilling.SendInvoice,
                DaysUntilDue = 7,
                PlanId       = Cache.GetPlan("silver").Id
            };

            SubscriptionCreated = subscriptionService.Create(Customer.Id, SubscriptionCreateOptions);

            var SubscriptionUpdateOptions = new StripeSubscriptionUpdateOptions
            {
                DaysUntilDue = 2,
            };

            SubscriptionUpdated = subscriptionService.Update(SubscriptionCreated.Id, SubscriptionUpdateOptions);
        }
Пример #3
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;
            }
        }
Пример #4
0
        public Subscription CreateSubscription(Subscription subscription)
        {
            var subscriptionCreate = subscription.ToStripeSubscriptionCreate();
            var newSubscription    = _subscriptionService.Create(subscriptionCreate);

            return(newSubscription.ToSubscription());
        }
Пример #5
0
        public subscription_fixture()
        {
            SubscriptionCreateOptions = new StripeSubscriptionCreateOptions
            {
                Items = new List <StripeSubscriptionItemOption>
                {
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan().Id, Quantity = 1
                    },
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan2().Id, Quantity = 2
                    }
                }
            };

            var service = new StripeSubscriptionService(Cache.ApiKey);

            Subscription = service.Create(Cache.GetCustomer().Id, SubscriptionCreateOptions);

            SubscriptionUpdateOptions = new StripeSubscriptionUpdateOptions
            {
                Items = new List <StripeSubscriptionItemUpdateOption>
                {
                    new StripeSubscriptionItemUpdateOption {
                        Id = Subscription.Items.Data[0].Id, Deleted = true
                    },
                    new StripeSubscriptionItemUpdateOption {
                        Id = Subscription.Items.Data[1].Id, Quantity = 5
                    }
                }
            };

            SubscriptionUpdated = service.Update(Subscription.Id, SubscriptionUpdateOptions);
        }
Пример #6
0
        public usage_record_fixture()
        {
            var subOptions = new StripeSubscriptionCreateOptions
            {
                Items = new List <StripeSubscriptionItemOption>
                {
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan("Metered Plan", "metered").Id
                    }
                }
            };

            var service              = new StripeSubscriptionService(Cache.ApiKey);
            var customer_id          = Cache.GetCustomer().Id;
            var subscription         = service.Create(customer_id, subOptions);
            var subscription_item_id = subscription.Items.Data[0].Id;

            UsageRecordCreateOptions = new StripeUsageRecordCreateOptions()
            {
                Action           = "increment",
                SubscriptionItem = subscription_item_id,
                Timestamp        = DateTime.Now,
                Quantity         = 2000
            };

            var usageRecordService = new StripeUsageRecordService(Cache.ApiKey);

            UsageRecord = usageRecordService.Create(UsageRecordCreateOptions);
        }
Пример #7
0
        public void createSuscription(int userId, TipoSuscripcion suscripcion, string token, string stripePrivateKey)
        {
            StripeConfiguration.SetApiKey(stripePrivateKey);
            var suscriptor = entities.Suscriptor.Find(userId);

            if (string.IsNullOrEmpty(suscriptor.stripeCustomerId))
            {
                var customer = new StripeCustomerCreateOptions()
                {
                    Email       = suscriptor.correoElectronico,
                    SourceToken = token,
                    PlanId      = suscripcion.externalId
                };

                var stripeCustomer = _customerServices.Create(customer);


                suscriptor.stripeCustomerId = stripeCustomer.Id;
                suscriptor.TipoSuscripcionSuscriptor.Add(new TipoSuscripcionSuscriptor()
                {
                    suscriptorId      = suscriptor.suscriptorId,
                    tipoSuscripcionId = suscripcion.tipoSuscripcionId,
                    fechaExperacion   = (DateTime.Now.AddDays(30)),
                    fechaCompra       = DateTime.Now
                });

                entities.SaveChanges();
            }
            else
            {
                var subscriptionService = subscriptionServices.Create(suscriptor.stripeCustomerId, suscripcion.externalId);
                ///// update suscription
            }
        }
Пример #8
0
        public subscription_fixture()
        {
            SubscriptionCreateOptions = new StripeSubscriptionCreateOptions
            {
                TrialEnd = DateTime.Now.AddMinutes(5),
                Items    = new List <StripeSubscriptionItemOption>
                {
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan().Id, Quantity = 1
                    },
                    new StripeSubscriptionItemOption {
                        PlanId = Cache.GetPlan("silver").Id, Quantity = 2
                    }
                }
            };

            var service     = new StripeSubscriptionService(Cache.ApiKey);
            var customer_id = Cache.GetCustomer().Id;

            Subscription = service.Create(customer_id, SubscriptionCreateOptions);
            service.Create(customer_id, SubscriptionCreateOptions);
            SubscriptionList = service.List(new StripeSubscriptionListOptions {
                CustomerId = customer_id
            });

            SubscriptionUpdateOptions = new StripeSubscriptionUpdateOptions
            {
                Items = new List <StripeSubscriptionItemUpdateOption>
                {
                    new StripeSubscriptionItemUpdateOption {
                        Id = Subscription.Items.Data[0].Id, Deleted = true
                    },
                    new StripeSubscriptionItemUpdateOption {
                        Id = Subscription.Items.Data[1].Id, Quantity = 5
                    }
                }
            };

            SubscriptionUpdated = service.Update(Subscription.Id, SubscriptionUpdateOptions);

            SubscriptionEndedOptions = new StripeSubscriptionUpdateOptions
            {
                EndTrialNow = true
            };

            SubscriptionEnded = service.Update(Subscription.Id, SubscriptionEndedOptions);
        }
Пример #9
0
        public void CreateSubscription(CustomerInfo customerInfo, string planId)
        {
            string customerId = GetCustomerId(customerInfo);
            StripeSubscriptionService subscriptionService = new StripeSubscriptionService();
            StripeSubscription        stripeSubscription  = subscriptionService.Create(customerId, planId);

            PaymentId = stripeSubscription.Id;
        }
        public string SubscribeAccountPlan(string planId, string customerId)
        {
            var subscriptionService = new StripeSubscriptionService();
            StripeSubscription stripeSubscription = subscriptionService.Create(customerId, planId);

            return(null);
            // optional StripeSubscriptionUpdateOptions            return null;
        }
Пример #11
0
        /// <summary>
        /// Subscribes the user natural month.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="planId">The plan identifier.</param>
        /// <param name="billingAnchorCycle">The billing anchor cycle.</param>
        /// <param name="taxPercent">The tax percent.</param>
        /// <returns></returns>
        public object SubscribeUserNaturalMonth(SaasEcomUser user, string planId, DateTime?billingAnchorCycle, decimal taxPercent)
        {
            StripeSubscription stripeSubscription = _subscriptionService.Create
                                                        (user.StripeCustomerId, planId, new StripeSubscriptionCreateOptions
            {
                BillingCycleAnchor = billingAnchorCycle,
                TaxPercent         = taxPercent
            });

            return(stripeSubscription);
        }
Пример #12
0
        public static string SubscribeCustomer(string stripeCustomerId, SubscriptionPlan subscriptionPlan)
        {
            var subscriptionService = new StripeSubscriptionService()
            {
                ApiKey = GetPrivateApiKey()
            };

            var planId = GetPlanId(subscriptionPlan);

            var subscription = subscriptionService.Create(stripeCustomerId, planId);

            return(subscription.Id);
        }
Пример #13
0
        /// <summary>
        /// Subscribes the given user to the given plan, using the payment information already in stripe for that user
        /// NOTE: Save changes on the underlying context for the model after calling this method
        /// </summary>
        /// <param name="subscription"></param>
        public static void Subscribe(IStripeUser user, IStripeSubscription subscription, IStripeSubscriptionPlan plan)
        {
            if (!string.IsNullOrEmpty(subscription.PaymentSystemId))
            {
                return;
            }

            var subscriptionService = new StripeSubscriptionService();
            StripeSubscription stripeSubscription = subscriptionService.Create(user.PaymentSystemId, plan.PaymentSystemId);

            subscription.PaymentSystemId = stripeSubscription.Id;

            System.Diagnostics.Trace.TraceInformation("Subscribed customer in stripe: '{0}' with new subscription id '{1}", user.Email, subscription.PaymentSystemId);
        }
Пример #14
0
        /// <summary>
        /// Subscribes the given user to the given plan, using the payment information already in stripe for that user
        /// NOTE: Save changes on the underlying context for the model after calling this method
        /// </summary>
        /// <param name="customer"></param>
        /// <param name="subscription"></param>
        /// <param name="plan"></param>
        /// <returns></returns>
        public static StripeSubscription Subscribe(ICustomerEntity customer, ISubscriptionEntity subscription, IPlanEntity plan)
        {
            if (!string.IsNullOrEmpty(subscription.PaymentSystemId))
            {
                return(null);
            }

            var subscriptionService            = new StripeSubscriptionService();
            StripeSubscription newSubscription = subscriptionService.Create(customer.PaymentSystemId, plan.PaymentSystemId);

            subscription.PaymentSystemId = newSubscription.Id;

            Logger.Log <StripeManager>("Subscribed customer in stripe: '{0}' with new subscription id '{1}", LogLevel.Information, customer.Email, subscription.PaymentSystemId);
            return(newSubscription);
        }
Пример #15
0
 public static StripeSubscription Subscription(string custId, StripeSubscriptionCreateOptions options, out string msg)
 {
     msg = "";
     try
     {
         var subscriptionServrive        = new StripeSubscriptionService();
         StripeSubscription subscription = subscriptionServrive.Create(custId, options);
         return(subscription);
     }
     catch (Exception ex)
     {
         msg = ex.Message.ToString();
         return(null);
     }
 }
Пример #16
0
        private void DoSub(StripeCustomer cus, JObject report)
        {
            StripeConfiguration.SetApiKey("sk_test_p9FWyo0hC9g8y39CkRR1pnYH");

            var items = new List <StripeSubscriptionItemOption> {
                new StripeSubscriptionItemOption {
                    PlanId = report.Property("newPlan").Value.ToString()
                }
            };
            var options = new StripeSubscriptionCreateOptions {
                Items = items,
            };
            var service = new StripeSubscriptionService();
            StripeSubscription subscription = service.Create(cus.Id, options);

            InsertSubscription(subscription, report);
        }
Пример #17
0
        private StripeSubscription AddNewUserSubscription(string id, string planToSubscribeTo, StripeSubscriptionService service, ApplicationUser dbUser)
        {
            var items = new List <StripeSubscriptionItemOption>
            {
                new StripeSubscriptionItemOption {
                    PlanId = GetPlanIdFromPlanName(planToSubscribeTo)
                }
            };

            var options = new StripeSubscriptionCreateOptions
            {
                Items = items,
            };
            StripeSubscription subscription = service.Create(id, options);

            _emailSender.SendEmailAsync(EmailType.NewSubscriber, dbUser.Email, dbUser.FirstName);

            return(subscription);
        }
Пример #18
0
        public async Task <dynamic> Post()
        {
            try
            {
                var    item  = RequestContext.Principal.Identity;
                string value = await Request.Content.ReadAsStringAsync();

                var entidad = System.Web.Helpers.Json.Decode(value);

                var suscripcion         = entidad.suscripcion;
                var custumer            = entidad.costumer;
                var subscriptionService = new StripeSubscriptionService("sk_test_CBdkobSnlUEOyOjsLQ8fpqof");
                var result = subscriptionService.Create(custumer, suscripcion);
                return(result);
            }
            catch (Exception ex)
            {
                return(ex);
            }
        }
Пример #19
0
        public ActionResult Charge(string stripeEmail, string stripeToken)
        {
            var req       = this.HttpContext.Request.Form;
            var customers = new StripeCustomerService();
            var charges   = new StripeChargeService();

            var customer = customers.Create(new StripeCustomerCreateOptions
            {
                Email       = stripeEmail,
                SourceToken = stripeToken
            });

            var charge = charges.Create(new StripeChargeCreateOptions
            {
                Amount      = 500,//charge in cents
                Description = "Sample Charge",
                Currency    = "usd",
                CustomerId  = customer.Id
            });

            StripeSubscriptionService subscriptionSvc = new StripeSubscriptionService();

            subscriptionSvc.Create(customer.Id, "EBSystems");

            var subscriptionOptions = new StripeSubscriptionUpdateOptions()
            {
                PlanId   = "EBSystems",
                Prorate  = false,
                TrialEnd = DateTime.Now.AddMinutes(2)
            };

            var subscriptionService         = new StripeSubscriptionService();
            StripeSubscription subscription = subscriptionService.Update("sub_BlX0rziJyWis7k", subscriptionOptions);

            //StripeSubscriptionService subscriptionSvc = new StripeSubscriptionService();
            //subscriptionSvc.Create(customer.Id, "ebsystems_standard");
            // further application specific code goes here

            return(View());
        }
Пример #20
0
        public StripeCustomer CreateUser(PurchaseInformation info, string email, string coupon = null)
        {
            try
            {
                var customer = new StripeCustomerCreateOptions();
                customer.Email = email;

                customer.SourceCard = new SourceCard()
                {
                    Number          = info.CC_number,
                    ExpirationYear  = Convert.ToInt32(info.ExpireYear),
                    ExpirationMonth = Convert.ToInt32(info.ExpireMonth),
                    Cvc             = info.CCVCode,
                    Name            = info.NameOnCard
                };
                //customer.PlanId = info.PlanId;                          // only if you have a plan
                //if (!string.IsNullOrEmpty(coupon))
                //    customer.CouponId = coupon;
                var            customerService = new StripeCustomerService();
                StripeCustomer stripeCustomer  = customerService.Create(customer);

                StripeSubscriptionCreateOptions options = new StripeSubscriptionCreateOptions()
                {
                    PlanId   = info.PlanId,
                    Quantity = 1,
                    CouponId = !string.IsNullOrEmpty(info.Coupon) ? info.Coupon : null
                };


                var subscriptionService = new StripeSubscriptionService();
                StripeSubscription stripeSubscription = subscriptionService.Create(stripeCustomer.Id, options); // optional StripeSubscriptionCreateOptions
                stripeCustomer.Subscriptions.Data.Add(stripeSubscription);
                return(stripeCustomer);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <ActionResult> Confirm(string stripeToken)
        {
            try
            {
                StripeConfiguration.SetApiKey("sk_test_ILBG36E21hK6nO8C6fOpQvWs");
                var             userId = User.Identity.GetUserId();
                var             planId = "plan_DtiCy8lnNADxbN";
                ApplicationUser user   = await UserManager.FindByIdAsync(userId);

                if (string.IsNullOrEmpty(user.CustomerIdentifier))
                {
                    var customer = new StripeCustomerCreateOptions();
                    customer.Email       = $"{user.Email}";
                    customer.Description = $"{user.Email}[{userId}]";
                    customer.PlanId      = planId;

                    customer.SourceToken = stripeToken;
                    var            customerService = new StripeCustomerService();
                    StripeCustomer stripeCustomer  = customerService.Create(customer);
                    user.CustomerIdentifier = stripeCustomer.Id;
                    stripeCustomer.Subscriptions.Data.ForEach(
                        async s => await SaveSubscription(s, user));
                    await UserManager.UpdateAsync(user);
                }
                else
                {
                    var subscriptionService = new StripeSubscriptionService();
                    var stripeSubscription  = subscriptionService.Create(user.CustomerIdentifier, planId);
                    await SaveSubscription(stripeSubscription, user);

                    await _userManager.UpdateAsync(user);
                }
                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #22
0
        public string AssignCustomerPlan(string customerId, string planId, string cardNumber,
                                         string cardCvc, int cardExpirationMonth, int cardExpirationYear)
        {
            // Create token
            var token = CreateToken(cardNumber, cardCvc, cardExpirationMonth, cardExpirationYear);

            var subscriptionService = new StripeSubscriptionService();
            var subscription        = subscriptionService.List(customerId).FirstOrDefault();

            if (subscription == null)
            {
                var options = new StripeSubscriptionCreateOptions
                {
                    Card = new StripeCreditCardOptions
                    {
                        TokenId = token.Id
                    },
                    PlanId = planId
                };

                subscription = subscriptionService.Create(customerId, planId, options);
            }
            else
            {
                var options = new StripeSubscriptionUpdateOptions
                {
                    Card = new StripeCreditCardOptions
                    {
                        TokenId = token.Id
                    },
                    PlanId = planId
                };

                subscription = subscriptionService.Update(customerId, subscription.Id, options);
            }


            return(subscription.Status);
        }
Пример #23
0
        public ActionResult ChangePlan(CustomerChangePlanViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var subscriptionService = new StripeSubscriptionService();
            var subs = subscriptionService.List(model.CustomerId);

            if (subs.Any())
            {
                foreach (var sub in subs)
                {
                    subscriptionService.Cancel(model.CustomerId, sub.Id);
                }
            }

            subscriptionService.Create(model.CustomerId, model.SelectedPlan);

            return(RedirectToAction("Details", new { id = model.CustomerId }));
        }
        public void CreateSubscription(string Api_Key, string customerId, string stripeSubscriptionCreateOptionsJSON, ref string Response, ref string Errors, ref int ErrorCode)
        {
            try
            {
                StripeConfiguration.SetApiKey(Api_Key);

                Serializer serializer = new Serializer();
                var        stripeSubscriptionCreateOptions = serializer.Deserialize <StripeSubscriptionCreateOptions>(stripeSubscriptionCreateOptionsJSON);

                var stripeSubscriptionService         = new StripeSubscriptionService();
                StripeSubscription stripeSubscription = stripeSubscriptionService.Create(customerId, stripeSubscriptionCreateOptions);

                Response  = stripeSubscription.StripeResponse.ResponseJson;
                ErrorCode = 0;
            }
            catch (StripeException e)
            {
                ErrorCode = 1;
                Serializer  serializer  = new Serializer();
                StripeError stripeError = e.StripeError;
                Errors = serializer.Serialize <StripeError>(stripeError);
            }
        }
Пример #25
0
        public StripeSubscription CreateNewSubscription(string sStripeCustomerId)
        {
            try
            {
                StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["stripeApi_LiveKey"]);

                var subscriptionOptions = new StripeSubscriptionCreateOptions()
                {
                    PlanId = "1"
                };

                var subscriptionService = new StripeSubscriptionService();

                StripeSubscription subscription = subscriptionService.Create(sStripeCustomerId, subscriptionOptions);

                return(subscription);
            }
            catch (Exception ex)
            {
                oLogger.LogData("METHOD: CreateNewSubscription; ERROR: TRUE; EXCEPTION: " + ex.Message + "; INNER EXCEPTION: " + ex.InnerException + "; STACKTRACE: " + ex.StackTrace);
                throw;
            }
        }
Пример #26
0
        private void CreateStripeSubscription(string stripeToken, string coupon)
        {
            using (var db = InitializeSettings.DbFactory)
            {
                var data = db.Get <Majorsilence.Vpn.Poco.Users>(_userId);


                var options = new Stripe.StripeSubscriptionCreateOptions();
                options.TokenId = stripeToken;
                if (coupon.Trim() != "")
                {
                    options.CouponId = coupon;
                }

                var subscriptionService = new StripeSubscriptionService();
                StripeSubscription stripeSubscription = subscriptionService.Create(data.StripeCustomerAccount,
                                                                                   Helpers.SiteInfo.StripePlanId, options);


                var subscriptionInfo = new StripeSubscriptionService(Helpers.SiteInfo.StripeAPISecretKey);
                var subscriptionList = subscriptionInfo.List(data.StripeCustomerAccount).ToList();

                if (subscriptionList.Count() > 1)
                {
                    throw new Exceptions.StripeSubscriptionException(
                              string.Format("More then one subscription detected for vpn customer: {0}, stripe customer: {1}",
                                            _userId, data.StripeCustomerAccount)
                              );
                }



                data.StripeSubscriptionId = subscriptionList.First().Id;

                db.Update(data);
            }
        }
Пример #27
0
        private static ClientSubscription GenerateClientAndSubscription()
        {
            var customerService = new StripeCustomerService();

            Console.WriteLine("Creating customer");
            var customerOptions = new StripeCustomerCreateOptions()
            {
                SourceToken = "tok_visa_debit",
                Description = "Test getting things done."
            };

            StripeCustomer customer = customerService.Create(customerOptions);

            Console.WriteLine("Customer created successfully");

            var subscriptionOptions = new StripeSubscriptionCreateOptions()
            {
                Items = new List <StripeSubscriptionItemOption>()
                {
                    new StripeSubscriptionItemOption()
                    {
                        PlanId   = Subscriptions.plan_spotifyBasic.ToString(),
                        Quantity = 1
                    }
                }
            };

            var subscriptionService         = new StripeSubscriptionService();
            StripeSubscription subscription = subscriptionService.Create(customer.Id, subscriptionOptions);

            return(new ClientSubscription()
            {
                Customer = customer,
                Subscription = subscription
            });
        }
        public async Task <IActionResult> CampaignRePayment(CustomerRePaymentViewModel payment)
        {
            var user = await GetCurrentUserAsync();

            try
            {
                List <CountryViewModel> countryList = GetCountryList();
                payment.countries = countryList;
                if (!ModelState.IsValid)
                {
                    return(View(payment));
                }

                var customerService = new StripeCustomerService(_stripeSettings.Value.SecretKey);
                var donation        = _campaignService.GetById(payment.DonationId);

                UpdateUserRepaymentEmail(payment, user);
                await UpdateRepaymentUserDetail(payment, user);

                // Add customer to Stripe
                if (EnumInfo <PaymentCycle> .GetValue(donation.CycleId) == PaymentCycle.OneTime)
                {
                    var model   = (DonationViewModel)donation;
                    var charges = new StripeChargeService(_stripeSettings.Value.SecretKey);

                    // Charge the customer
                    var charge = charges.Create(new StripeChargeCreateOptions
                    {
                        Amount              = Convert.ToInt32(donation.DonationAmount * 100),
                        Description         = DonationCaption,
                        Currency            = "usd", //payment.Currency.ToLower(),
                        CustomerId          = user.StripeCustomerId,
                        StatementDescriptor = _stripeSettings.Value.StatementDescriptor,
                    });

                    if (charge.Paid)
                    {
                        var completedMessage = new CompletedViewModel
                        {
                            Message          = donation.DonationAmount.ToString(),
                            HasSubscriptions = false
                        };
                        return(RedirectToAction("Thanks", completedMessage));
                    }
                    return(RedirectToAction("Error", "Error", new ErrorViewModel()
                    {
                        Error = "Error"
                    }));
                }
                donation.Currency = "usd";//payment.Currency;
                // Add to existing subscriptions and charge
                var plan = _campaignService.GetOrCreatePlan(donation);

                var subscriptionService = new StripeSubscriptionService(_stripeSettings.Value.SecretKey);
                var result = subscriptionService.Create(user.StripeCustomerId, plan.Id);
                if (result != null)
                {
                    CompletedViewModel completedMessage = new CompletedViewModel();
                    completedMessage = GetSubscriptionMessage(result, true);
                    return(RedirectToAction("Thanks", completedMessage));
                }
            }
            catch (StripeException ex)
            {
                log = new EventLog()
                {
                    EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email
                };
                _loggerService.SaveEventLogAsync(log);
                if (ex.Message.ToLower().Contains("customer"))
                {
                    return(RedirectToAction("Error", "Error500", new ErrorViewModel()
                    {
                        Error = ex.Message
                    }));
                }
                else
                {
                    ModelState.AddModelError("error", ex.Message);
                    return(View(payment));
                }
            }
            catch (Exception ex)
            {
                log = new EventLog()
                {
                    EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email
                };
                _loggerService.SaveEventLogAsync(log);
                return(RedirectToAction("Error", "Error", new ErrorViewModel()
                {
                    Error = ex.Message
                }));
            }
            return(RedirectToAction("Error", "Error", new ErrorViewModel()
            {
                Error = "Error"
            }));
        }
        public async Task <IActionResult> CampaignPayment(CustomerPaymentViewModel payment)
        {
            var user = await GetCurrentUserAsync();

            try
            {
                List <CountryViewModel> countryList = GetCountryList();
                payment.countries = countryList;
                payment.yearList  = GeneralUtility.GetYeatList();
                if (!ModelState.IsValid)
                {
                    return(View(payment));
                }

                var customerService = new StripeCustomerService(_stripeSettings.Value.SecretKey);
                var donation        = _campaignService.GetById(payment.DonationId);

                // Construct payment
                if (string.IsNullOrEmpty(user.StripeCustomerId))
                {
                    StripeCustomerCreateOptions customer = GetCustomerCreateOptions(payment, user);
                    var stripeCustomer = customerService.Create(customer);
                    user.StripeCustomerId = stripeCustomer.Id;
                }
                else
                {
                    //Check for existing credit card, if new credit card number is same as exiting credit card then we delete the existing
                    //Credit card information so new card gets generated automatically as default card.
                    //try
                    //{
                    //    var ExistingCustomer = customerService.Get(user.StripeCustomerId);
                    //    if (ExistingCustomer.Sources != null && ExistingCustomer.Sources.TotalCount > 0 && ExistingCustomer.Sources.Data.Any())
                    //    {
                    //        var cardService = new StripeCardService(_stripeSettings.Value.SecretKey);
                    //        foreach (var cardSource in ExistingCustomer.Sources.Data)
                    //        {
                    //            cardService.Delete(user.StripeCustomerId, cardSource.Card.Id);
                    //        }
                    //    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    log = new EventLog() { EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email };
                    //    _loggerService.SaveEventLogAsync(log);
                    //    return RedirectToAction("Error", "Error500", new ErrorViewModel() { Error = ex.Message });
                    //}

                    StripeCustomerUpdateOptions customer = GetCustomerUpdateOption(payment);
                    try
                    {
                        var stripeCustomer = customerService.Update(user.StripeCustomerId, customer);
                        user.StripeCustomerId = stripeCustomer.Id;
                    }
                    catch (StripeException ex)
                    {
                        log = new EventLog()
                        {
                            EventId = (int)LoggingEvents.GET_CUSTOMER, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email
                        };
                        _loggerService.SaveEventLogAsync(log);
                        if (ex.Message.ToLower().Contains("customer"))
                        {
                            return(RedirectToAction("Error", "Error500", new ErrorViewModel()
                            {
                                Error = ex.Message
                            }));
                        }
                        else
                        {
                            ModelState.AddModelError("error", _localizer[ex.Message]);
                            return(View(payment));
                        }
                    }
                }

                UpdateUserEmail(payment, user);
                await UpdateUserDetail(payment, user);

                // Add customer to Stripe
                if (EnumInfo <PaymentCycle> .GetValue(donation.CycleId) == PaymentCycle.OneTime)
                {
                    var model   = (DonationViewModel)donation;
                    var charges = new StripeChargeService(_stripeSettings.Value.SecretKey);

                    // Charge the customer
                    var charge = charges.Create(new StripeChargeCreateOptions
                    {
                        Amount              = Convert.ToInt32(donation.DonationAmount * 100),
                        Description         = DonationCaption,
                        Currency            = "usd",//payment.Currency.ToLower(),
                        CustomerId          = user.StripeCustomerId,
                        StatementDescriptor = _stripeSettings.Value.StatementDescriptor,
                    });

                    if (charge.Paid)
                    {
                        var completedMessage = new CompletedViewModel
                        {
                            Message          = donation.DonationAmount.ToString(),
                            HasSubscriptions = false
                        };
                        return(RedirectToAction("Thanks", completedMessage));
                    }
                    return(RedirectToAction("Error", "Error", new ErrorViewModel()
                    {
                        Error = "Error"
                    }));
                }

                // Add to existing subscriptions and charge
                donation.Currency = "usd"; //payment.Currency;
                var plan = _campaignService.GetOrCreatePlan(donation);

                var subscriptionService = new StripeSubscriptionService(_stripeSettings.Value.SecretKey);
                var result = subscriptionService.Create(user.StripeCustomerId, plan.Id);
                if (result != null)
                {
                    CompletedViewModel completedMessage = new CompletedViewModel();
                    completedMessage = GetSubscriptionMessage(result, true);
                    return(RedirectToAction("Thanks", completedMessage));
                }
            }
            catch (StripeException ex)
            {
                log = new EventLog()
                {
                    EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email
                };
                _loggerService.SaveEventLogAsync(log);
                if (ex.Message.ToLower().Contains("customer"))
                {
                    return(RedirectToAction("Error", "Error500", new ErrorViewModel()
                    {
                        Error = ex.Message
                    }));
                }
                else
                {
                    ModelState.AddModelError("error", ex.Message);
                    return(View(payment));
                }
            }
            catch (Exception ex)
            {
                log = new EventLog()
                {
                    EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email
                };
                _loggerService.SaveEventLogAsync(log);
                return(RedirectToAction("Error", "Error", new ErrorViewModel()
                {
                    Error = ex.Message
                }));
            }
            return(RedirectToAction("Error", "Error", new ErrorViewModel()
            {
                Error = "Error"
            }));
        }
        public IHttpActionResult ChangePlan(string id, string planId, string stripeToken = null, string last4 = null, string couponId = null)
        {
            if (String.IsNullOrEmpty(id) || !CanAccessOrganization(id))
            {
                return(BadRequest("Invalid organization id."));
            }

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

            Organization organization = _repository.GetById(id);

            if (organization == null)
            {
                return(Ok(new { Success = false, Message = "Invalid OrganizationId." }));
            }

            BillingPlan plan = BillingManager.GetBillingPlan(planId);

            if (plan == null)
            {
                return(Ok(new { Success = false, Message = "Invalid PlanId." }));
            }

            if (String.Equals(organization.PlanId, plan.Id) && String.Equals(BillingManager.FreePlan.Id, plan.Id))
            {
                return(Ok(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, ExceptionlessUser, out message))
            {
                return(Ok(new { Success = false, Message = message }));
            }

            var customerService     = new StripeCustomerService();
            var subscriptionService = new StripeSubscriptionService();

            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))
                    {
                        var subs = subscriptionService.List(organization.StripeCustomerId).Where(s => !s.CanceledAt.HasValue);
                        foreach (var sub in subs)
                        {
                            subscriptionService.Cancel(organization.StripeCustomerId, sub.Id);
                        }
                    }

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

                    organization.SubscribeDate = DateTime.Now;

                    var createCustomer = new StripeCustomerCreateOptions {
                        TokenId     = stripeToken,
                        PlanId      = planId,
                        Description = organization.Name,
                        Email       = ExceptionlessUser.EmailAddress
                    };

                    if (!String.IsNullOrWhiteSpace(couponId))
                    {
                        createCustomer.CouponId = couponId;
                    }

                    StripeCustomer customer = customerService.Create(createCustomer);

                    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 StripeSubscriptionUpdateOptions {
                        PlanId = planId
                    };
                    var  create      = new StripeSubscriptionCreateOptions();
                    bool cardUpdated = false;

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

                    var subscription = subscriptionService.List(organization.StripeCustomerId).FirstOrDefault(s => !s.CanceledAt.HasValue);
                    if (subscription != null)
                    {
                        subscriptionService.Update(organization.StripeCustomerId, subscription.Id, update);
                    }
                    else
                    {
                        subscriptionService.Create(organization.StripeCustomerId, planId, create);
                    }

                    customerService.Update(organization.StripeCustomerId, new StripeCustomerUpdateOptions {
                        Email = ExceptionlessUser.EmailAddress
                    });

                    if (cardUpdated)
                    {
                        organization.CardLast4 = last4;
                    }

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

                _billingManager.ApplyBillingPlan(organization, plan, ExceptionlessUser);
                _repository.Save(organization);

                _messagePublisher.Publish(new PlanChanged {
                    OrganizationId = 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(Ok(new { Success = false, Message = e.Message }));
            }

            return(Ok(new { Success = true }));
        }