Beispiel #1
0
        public void CancelSubscription()
        {
            var user        = AuthHelper.GetCurrentUser();
            var usermanager = AuthHelper.GetUserManager();

            try
            {
                var cust = new StripeCustomerService().Get(user.StripeCustomerId);
                if (cust != null)
                {
                    var sub_svc = new StripeSubscriptionService();
                    var sub     = sub_svc.Get(cust.Id, cust.StripeSubscriptionList.Data[0].Id);

                    sub_svc.Cancel(cust.Id, sub.Id, true);
                }
                else
                {
                    throw new ApplicationException("Could not find the customer in stripe to change the plan");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            // Set Stripe Api Key
            StripeConfiguration.SetApiKey(AppConfiguration.StripeApiKey);

            using (var subscriptionBookingRepository = new SubscriptionBookingRepository())
            {
                var subscriptionBookingList = subscriptionBookingRepository.SubscriptionBookingsList.Where(sb => ids.Contains(sb.Id)).ToList();

                // Each Subscription Bookings
                subscriptionBookingList.ForEach(subscriptionBookings =>
                {
                    var customerInfos = subscriptionBookingRepository.CustomerInfoList
                                        .FirstOrDefault(ci => ci.CustomerId == subscriptionBookings.CustomerId);

                    // Customer Infos
                    if (customerInfos != null)
                    {
                        var subscriptionService         = new StripeSubscriptionService();
                        StripeSubscription subscription = subscriptionService.Get(subscriptionBookings.StripeSubscriptionId);
                        DateTime?canceledDate           = subscription.CanceledAt;

                        if (canceledDate.HasValue)
                        {
                            subscriptionBookings.CancelDate = canceledDate;
                        }
                    }
                });

                subscriptionBookingRepository.UpdateSubscriptionBookingCanceledDate(subscriptionBookingList);

                Console.WriteLine("Done!!!");
                Console.ReadLine();
            }
        }
        static void Main(string[] args)
        {
            // Set Stripe Api Key
            StripeConfiguration.SetApiKey(AppConfiguration.StripeApiKey);

            using (var subscriptionBookingRepository = new SubscriptionBookingRepository())
            {
                var subscriptionBookingList = subscriptionBookingRepository.SubscriptionBookingsList.Where(sb => ids.Contains(sb.Id)).ToList();

                // Each Subscription Bookings
                subscriptionBookingList.ForEach(subscriptionBookings =>
                {
                    var customerInfos = subscriptionBookingRepository.CustomerInfoList
                                        .FirstOrDefault(ci => ci.CustomerId == subscriptionBookings.CustomerId);

                    // Customer Infos
                    if (customerInfos != null)
                    {
                        var subscriptionService         = new StripeSubscriptionService();
                        StripeSubscription subscription = subscriptionService.Get(subscriptionBookings.StripeSubscriptionId);
                        DateTime?canceledDate           = subscription.CanceledAt;

                        if (canceledDate.HasValue)
                        {
                            subscriptionBookings.CancelDate = canceledDate;
                        }

                        switch (subscription.Status)
                        {
                        case "past_due":
                        case "unpaid":
                            subscriptionBookings.Status = (int)Enums.SubscriptionBookingStatus.Suspended;
                            break;

                        case "active":
                            // Set Date of Discounts
                            //subscriptionBookings.Status = (int)Enums.SubscriptionBookingStatus.Active;
                            break;

                        case "canceled":
                            //subscriptionBookings.Status = (int)Enums.SubscriptionBookingStatus.End;
                            break;

                        default:     //trialing
                            break;
                        }
                    }
                });

                subscriptionBookingRepository.UpdateSubscriptionBookingCanceledDate(subscriptionBookingList);

                Console.WriteLine("Done!!!");
                Console.ReadLine();
            }
        }
Beispiel #4
0
 public StripeSubscription RetrieveSubscription(string subscriptionId)
 {
     try
     {
         var subscriptionService = new StripeSubscriptionService();
         StripeSubscription stripeSubscription = subscriptionService.Get(subscriptionId);
         return(stripeSubscription);
     }
     catch (Exception ex) {
         throw ex;
     }
 }
Beispiel #5
0
        public async Task <string> ChangePlan(RechargeInput input)
        {
            var user        = AuthHelper.GetCurrentUser();
            var usermanager = AuthHelper.GetUserManager();

            try
            {
                StripeConfiguration.SetApiKey(System.Configuration.ConfigurationManager.AppSettings["StripeApiKey"]);
            }
            catch (Exception ex)
            {
                //log the exception and return the message to the caller
                return(ex.Message);
            }

            return(await System.Threading.Tasks.Task.Run(() =>
            {
                try
                {
                    var cust = new StripeCustomerService().Get(user.StripeCustomerId);
                    if (cust != null)
                    {
                        var sub_svc = new StripeSubscriptionService();
                        var sub = sub_svc.Get(cust.Id, cust.StripeSubscriptionList.Data[0].Id);

                        var options = new StripeSubscriptionUpdateOptions();
                        options.PlanId = input.PlanID;
                        options.Prorate = false;

                        sub_svc.Update(cust.Id, sub.Id, options);
                    }
                    else
                    {
                        throw new ApplicationException("Could not find the customer in stripe to change the plan");
                    }
                    return "Success";
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }));
        }
Beispiel #6
0
        public bool updateSubscription([FromBody] JObject report)
        {
            StripeConfiguration.SetApiKey("sk_test_p9FWyo0hC9g8y39CkRR1pnYH");
            Dictionary <string, object> parameters = new Dictionary <string, object>();

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

            Subscription sub = new Subscription().SearchDocument(parameters)[0];

            var service = new StripeSubscriptionService();
            StripeSubscription subscription = service.Get(sub.SubID);

            var items = new List <StripeSubscriptionItemUpdateOption> {
                new StripeSubscriptionItemUpdateOption {
                    PlanId = report.Property("newPlan").Value.ToString(),
                    Id     = subscription.Items.Data[0].Id
                },
            };
            StripeSubscriptionUpdateOptions options;

            if (report.Property("coupon").Value.ToString().Equals(string.Empty) || (!report.Property("coupon").Value.ToString().Equals("Partner25") && !report.Property("coupon").Value.ToString().Equals("tellnpfree6") && !report.Property("coupon").Value.ToString().Equals("tellnpfree12")))
            {
                options = new StripeSubscriptionUpdateOptions {
                    Items             = items,
                    CancelAtPeriodEnd = false
                };
            }
            else
            {
                options = new StripeSubscriptionUpdateOptions {
                    Items             = items,
                    CancelAtPeriodEnd = false,
                    CouponId          = report.Property("coupon").Value.ToString()
                };
            }

            subscription = service.Update(sub.SubID, options);
            sub.PlanName = report.Property("newPlan").Value.ToString();
            sub.UpdateDocument(sub);

            return(true);
        }
        public void RetreiveSubscription(string Api_Key, string SubscriptionId, ref string Response, ref string Errors, ref int ErrorCode)
        {
            try
            {
                StripeConfiguration.SetApiKey(Api_Key);

                var stripeSubscriptionService         = new StripeSubscriptionService();
                StripeSubscription stripeSubscription = stripeSubscriptionService.Get(SubscriptionId);

                Response  = stripeSubscription.StripeResponse.ResponseJson;
                ErrorCode = 0;
            }
            catch (StripeException e)
            {
                ErrorCode = 1;
                Serializer  serializer  = new Serializer();
                StripeError stripeError = e.StripeError;
                Errors = serializer.Serialize <StripeError>(stripeError);
            }
        }
Beispiel #8
0
        private StripeSubscription UpdateUserSubscription(string id, string currentSubscriptionId, string planToSubscribeTo, StripeSubscriptionService service, ApplicationUser dbUser)
        {
            StripeSubscription subscription = service.Get(currentSubscriptionId);

            var items = new List <StripeSubscriptionItemUpdateOption> {
                new StripeSubscriptionItemUpdateOption {
                    Id     = subscription.Items.Data[0].Id,
                    PlanId = GetPlanIdFromPlanName(planToSubscribeTo),
                },
            };
            var options = new StripeSubscriptionUpdateOptions
            {
                CancelAtPeriodEnd = false,
                Items             = items,
            };

            subscription = service.Update(currentSubscriptionId, options);

            _emailSender.SendEmailAsync(GetUpgradeOrDowngradeStatus(currentSubscriptionId, subscription.Id), dbUser.Email, dbUser.FirstName);

            return(subscription);
        }
Beispiel #9
0
        public ActionResult Login(LoginModel loginModel)
        {
            var serialization    = new Serialization();
            var userRegistration = new UserRegistration();
            var loginBA          = new Login();
            var HashCriteria     = new Hashtable();
            var actualCriteria   = string.Empty;

            if (ModelState.IsValid)
            {
                HashCriteria.Add("UserName", loginModel.UserName);
                actualCriteria = serialization.SerializeBinary((object)HashCriteria);
                var result            = loginBA.ValidateLogin(actualCriteria);
                var loginModelDetails = (LoginModel)(serialization.DeSerializeBinary(Convert.ToString(result)));

                var validateResult  = false;
                var isValidPassword = false;
                if (loginModelDetails.common != null)
                {
                    isValidPassword = SessionManagement.CipherTool.Verify(loginModel.Password, Convert.ToString(loginModelDetails.common.Password));
                }

                if (isValidPassword)
                {
                    if (loginModelDetails.common.IsEnabled == false)
                    {
                        ModelState.AddModelError("", "User account is disabled, Please contact Administrator.");
                        return(PartialView("_Login", loginModel));
                    }

                    //initialize userAuthModel
                    var userSession = Authenticate(loginModelDetails);

                    //
                    if (userSession != null)
                    {
                        var identity = new ClaimsIdentity(AuthenticationHelper.CreateClaim(userSession,
                                                                                           userSession.UserRole),
                                                          DefaultAuthenticationTypes.ApplicationCookie
                                                          );
                        AuthenticationManager.SignIn(new AuthenticationProperties()
                        {
                            AllowRefresh = true,
                            IsPersistent = true,
                            ExpiresUtc   = DateTime.UtcNow.AddHours(1)
                        }, identity);
                    }

                    SessionController.UserSession.UserId       = loginModelDetails.common.UserId;
                    SessionController.UserSession.UserName     = loginModelDetails.common.UserName;
                    SessionController.UserSession.EmailAddress = loginModelDetails.common.EmailAddress;
                    SessionController.UserSession.RoleType     = loginModelDetails.common.RoleType;
                    validateResult = true;

                    //Reteive the subscription for the user to check if this is valid or not
                    HashCriteria   = new Hashtable();
                    actualCriteria = string.Empty;
                    List <UserProfileEditModel> objUserProfileDetails = new List <UserProfileEditModel>();
                    HashCriteria.Add("UserID", loginModelDetails.common.UserId);
                    actualCriteria = serialization.SerializeBinary((object)HashCriteria);
                    var resultuser = userRegistration.GetUserSpecificDetails(actualCriteria);
                    objUserProfileDetails = (List <UserProfileEditModel>)(serialization.DeSerializeBinary(Convert.ToString(resultuser)));
                    var UserProfileDetails = objUserProfileDetails.FirstOrDefault();

                    //To get the customer credit card information for this user
                    if (UserProfileDetails.CustomerID != "" && UserProfileDetails.CustomerID != null)
                    {
                        string customerID = UserProfileDetails.CustomerID;
                        SessionController.UserSession.CustomerID = customerID;

                        var            customerService = new StripeCustomerService();
                        StripeCustomer stripeCustomer  = customerService.Get(customerID);

                        //Check if user has any subscription or not
                        if (stripeCustomer.Subscriptions.TotalCount > 0)
                        {
                            var subscriptionID = stripeCustomer.Subscriptions.Data[0].Id;

                            var subscriptionService = new StripeSubscriptionService();
                            StripeSubscription stripeSubscription = subscriptionService.Get(subscriptionID);

                            //Check if the user subscription is on or not: If on then Paid else Unpaid
                            if (stripeSubscription.Status == "active")
                            {
                                SessionController.UserSession.IsPaid = true;
                            }
                            else
                            {
                                SessionController.UserSession.IsPaid = false;
                            }
                        }
                        else
                        {
                            SessionController.UserSession.IsPaid = false;
                        }
                    }
                    else
                    {
                        SessionController.UserSession.IsPaid = false;
                    }
                }

                if (validateResult)
                {
                    var url = new
                    {
                        Url  = Request.Url.AbsoluteUri,
                        type = "Url"
                    };
                    return(Json(url, JsonRequestBehavior.AllowGet));
                }
            }
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return(PartialView("_Login", loginModel));
        }
        static void Main(string[] args)
        {
            // Set Stripe Api Key
            StripeConfiguration.SetApiKey(AppConfiguration.StripeApiKey);

            using (var subscriptionBookingRepository = new SubscriptionBookingRepository())
            {
                var subscriptionBookingList = subscriptionBookingRepository.SubscriptionBookingsList.ToList();

                // Each Subscription Bookings
                subscriptionBookingList.ForEach(subscriptionBookings =>
                {
                    var customerInfos = subscriptionBookingRepository.CustomerInfoList
                                        .FirstOrDefault(ci => ci.CustomerId == subscriptionBookings.CustomerId);

                    // Customer Infos
                    if (customerInfos != null)
                    {
                        var subscriptionService         = new StripeSubscriptionService();
                        StripeSubscription subscription = subscriptionService.Get(subscriptionBookings.StripeSubscriptionId);
                        DateTime?canceledDate           = subscription.CanceledAt;

                        var invoiceService = new StripeInvoiceService();

                        // All Invoices of Customer
                        var invoiceItems = invoiceService.List(new StripeInvoiceListOptions
                        {
                            CustomerId = customerInfos.StripeCustomerId
                        }
                                                               ).OrderBy(ic => ic.Date).ToList();

                        short cycleNumber = 0;
                        invoiceItems.ForEach(invoice =>
                        {
                            if (invoice.SubscriptionId.Equals(subscriptionBookings.StripeSubscriptionId, StringComparison.InvariantCulture))
                            {
                                cycleNumber++;
                                double totalCharge = (double)invoice.Total / 100;
                                if (!totalCharge.Equals(subscriptionBookings.TotalPrice))
                                {
                                    subscriptionBookings.Price = totalCharge;
                                }

                                DateTime?periodStart = invoice.PeriodStart;
                                DateTime?periodEnd   = invoice.PeriodEnd;
                                try
                                {
                                    if (periodStart.Value.Date == periodEnd.Value.Date)
                                    {
                                        periodEnd = periodEnd.Value.AddDays(30);
                                    }
                                    periodStart = invoice.StripeInvoiceLineItems.Data[0].StripePeriod.Start;
                                    periodEnd   = invoice.StripeInvoiceLineItems.Data[0].StripePeriod.End;
                                }
                                catch (Exception) { }
                                var subscriptionCycle = new SubscriptionCycles
                                {
                                    SubscriptionBookingId = subscriptionBookings.Id,
                                    StartDate             = periodStart,
                                    EndDate         = periodEnd,
                                    CancelDate      = subscriptionBookings.CancelDate,
                                    Status          = subscriptionBookings.Status,
                                    LastUpdatedDate = subscriptionBookings.LastUpdatedDate,
                                    LastUpdatedBy   = subscriptionBookings.LastUpdatedBy,
                                    Price           = totalCharge.Equals(0) && subscriptionBookings.PayByCredit > 0 ? subscriptionBookings.PayByCredit : totalCharge,
                                    MerchantPrice   = subscriptionBookings.MerchantPrice,
                                    PayByCredit     = subscriptionBookings.PayByCredit,
                                    TotalPrice      = totalCharge,
                                    Quantity        = subscriptionBookings.Quantity,
                                    StripeInvoiceId = invoice.Id,
                                    StripeChargeId  = invoice.ChargeId,
                                    StripeCouponId  = subscriptionBookings.StripeCouponId,
                                    CycleNumber     = cycleNumber
                                };

                                var param = new AddSubscriptionCycleParams
                                {
                                    CanceledDate             = canceledDate,
                                    SubscriptionCyclesObject = subscriptionCycle,
                                    SubscriptionInvoices     = new List <SubscriptionInvoices>()
                                };

                                SubscriptionInvoices subscriptionInvoice;

                                // Paid Charge
                                if (invoice.Paid)
                                {
                                    if (!string.IsNullOrEmpty(invoice.ChargeId))
                                    {
                                        var chargeService   = new StripeChargeService();
                                        StripeCharge charge = chargeService.Get(invoice.ChargeId);
                                        subscriptionInvoice = new SubscriptionInvoices
                                        {
                                            SubscriptionCyclesId = subscriptionCycle.Id,
                                            BookingStatus        = subscriptionCycle.Status,
                                            Quantity             = subscriptionBookings.Quantity,
                                            Price              = (double)charge.Amount / 100,
                                            MerchantPrice      = subscriptionBookings.MerchantPrice,
                                            PayByCredit        = subscriptionBookings.PayByCredit,
                                            TotalPrice         = (double)charge.Amount / 100,
                                            InvoiceStatus      = (int)Enums.InvoiceStatus.Charge,
                                            StripeChargeId     = charge.Id,
                                            ChargeAmount       = (double)charge.Amount / 100,
                                            StripeRefundId     = string.Empty,
                                            RefundAmount       = 0,
                                            RefundCreditAmount = 0,
                                            StripeCouponId     = subscriptionBookings.StripeCouponId,
                                            CreatedDate        = DateTime.UtcNow,
                                            CreatedBy          = 1
                                        };

                                        param.SubscriptionInvoices.Add(subscriptionInvoice);

                                        // Charge with Refunded
                                        if (charge.Refunded || charge.AmountRefunded > 0)
                                        {
                                            var refundList = charge.Refunds;
                                            for (int i = 0; i < refundList.Data.Count; i++)
                                            {
                                                var refundItem = charge.Refunds.Data[i];
                                                var subscriptionInvoiceRefunded = new SubscriptionInvoices
                                                {
                                                    SubscriptionCyclesId = subscriptionCycle.Id,
                                                    BookingStatus        = subscriptionCycle.Status,
                                                    Quantity             = subscriptionBookings.Quantity,
                                                    Price = (double)charge.Amount / 100 -
                                                            (double)refundItem.Amount / 100,
                                                    MerchantPrice = subscriptionBookings.MerchantPrice,
                                                    PayByCredit   = subscriptionBookings.PayByCredit,
                                                    TotalPrice    =
                                                        subscriptionBookings.MerchantPrice -
                                                        (double)refundItem.Amount / 100 -
                                                        subscriptionBookings.PayByCredit,
                                                    InvoiceStatus =
                                                        refundItem.Amount < charge.Amount
                                                            ? (int)Enums.InvoiceStatus.PartialRefund
                                                            : (int)Enums.InvoiceStatus.FullRefund,
                                                    StripeChargeId     = charge.Id,
                                                    ChargeAmount       = (double)charge.Amount / 100,
                                                    StripeRefundId     = refundItem.Id,
                                                    RefundAmount       = (double)refundItem.Amount / 100,
                                                    RefundCreditAmount = 0,
                                                    StripeCouponId     = subscriptionBookings.StripeCouponId,
                                                    CreatedDate        = DateTime.UtcNow,
                                                    CreatedBy          = 1
                                                };

                                                param.SubscriptionInvoices.Add(subscriptionInvoiceRefunded);

                                                param.SubscriptionCyclesObject.Price      = subscriptionInvoiceRefunded.Price;
                                                param.SubscriptionCyclesObject.TotalPrice = subscriptionInvoiceRefunded.TotalPrice;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        // Charge but have Coupon and use DayAxe Credit so Amount = 0
                                        subscriptionInvoice = new SubscriptionInvoices
                                        {
                                            SubscriptionCyclesId = subscriptionCycle.Id,
                                            BookingStatus        = subscriptionCycle.Status,
                                            Quantity             = subscriptionBookings.Quantity,
                                            Price              = 0,
                                            MerchantPrice      = subscriptionBookings.MerchantPrice,
                                            PayByCredit        = subscriptionBookings.PayByCredit,
                                            TotalPrice         = 0,
                                            InvoiceStatus      = (int)Enums.InvoiceStatus.Charge,
                                            StripeChargeId     = string.Empty,
                                            ChargeAmount       = 0,
                                            StripeRefundId     = string.Empty,
                                            RefundAmount       = 0,
                                            RefundCreditAmount = 0,
                                            StripeCouponId     = subscriptionBookings.StripeCouponId,
                                            CreatedDate        = DateTime.UtcNow,
                                            CreatedBy          = 1
                                        };

                                        param.SubscriptionInvoices.Add(subscriptionInvoice);
                                    }
                                }
                                else
                                {
                                    // Closed Charge
                                    subscriptionInvoice = new SubscriptionInvoices
                                    {
                                        SubscriptionCyclesId = subscriptionCycle.Id,
                                        BookingStatus        = subscriptionCycle.Status,
                                        Quantity             = subscriptionBookings.Quantity,
                                        Price              = totalCharge,
                                        MerchantPrice      = subscriptionBookings.MerchantPrice,
                                        PayByCredit        = subscriptionBookings.PayByCredit,
                                        TotalPrice         = totalCharge,
                                        InvoiceStatus      = (int)Enums.InvoiceStatus.Charge,
                                        StripeChargeId     = invoice.ChargeId,
                                        ChargeAmount       = totalCharge,
                                        StripeRefundId     = string.Empty,
                                        RefundAmount       = 0,
                                        RefundCreditAmount = 0,
                                        StripeCouponId     = subscriptionBookings.StripeCouponId,
                                        CreatedDate        = DateTime.UtcNow,
                                        CreatedBy          = 1
                                    };

                                    param.SubscriptionInvoices.Add(subscriptionInvoice);
                                }

                                subscriptionBookingRepository.AddSubscriptionCycle(param);

                                Console.WriteLine("Update - " + invoice.SubscriptionId);
                            }
                        });
                    }
                });

                Console.WriteLine("Done!!!");
                Console.ReadLine();
            }
        }
Beispiel #11
0
        public static void MembershipRenewalReminders()
        {
            var httpContext = new HttpContextWrapper(HttpContext.Current ?? new HttpContext(new SimpleWorkerRequest("temp.aspx", "", new StringWriter())));

            var context = UmbracoContext.EnsureContext(httpContext, ApplicationContext.Current, new WebSecurity(httpContext, ApplicationContext.Current), UmbracoConfig.For.UmbracoSettings(), UrlProviderResolver.Current.Providers, false);

            DataManager dm      = new DataManager(context);
            var         members = dm.GetCurrentMemberships();


            var model = new MembershipRenewal();

            model.BaseUri = "https://www.wellslittletheatre.com";
            var    subscriptionService = new StripeSubscriptionService(SensativeInformation.StripeKeys.SecretKey);
            string price = string.Empty;

            //send reminder a week before
            foreach (
                var m in
                members.Where(
                    n =>
                    (n.IsSubscription == false || (n.IsSubscription && n.CancelAtEnd == false)) &&
                    n.MembershipType != MembershipType.Life &&
                    n.EndDate.Date == DateTime.UtcNow.Date.AddMonths(1) ||
                    n.EndDate.Date == DateTime.UtcNow.Date.AddDays(7)).ToList())
            {
                var member = dm.GetMember(m.Member);
                if (member != null)
                {
                    if (m.IsSubscription && m.StripeSubscriptionId != null)
                    {
                        try
                        {
                            if (member.StripeUserId.IsNotNullOrEmpty())
                            {
                                var subscription = subscriptionService.Get(m.StripeSubscriptionId);
                                price = (subscription.StripePlan.Amount / 100m).ToString("N");
                            }
                        }
                        catch
                        (StripeException e)
                        {
                            Log.Error(
                                $"There was a stripe error whilst trying to load the current subscription price for the membership{m.MembershipId}. The error was {e.Message}.");
                        }
                    }
                    model.MembershipType = m.MembershipTypeName;
                    model.DateDue        = m.EndDate.AddDays(1);
                    model.IsSubscription = m.IsSubscription;
                    model.Price          = price;
                    model.Name           = member.Name;
                    var fileContents =
                        GetFileContents("~/MembershipRenwalEmailContent/MembershipRenewalCommingUp.cshtml");
                    var html = Engine.Razor.RunCompile(fileContents, "MembershipRenewal", typeof(MembershipRenewal),
                                                       model);

                    EmailHelpers emailService = new EmailHelpers();
                    emailService.SendEmail(member.GetContactEmail, "Membership renewal is coming up!", html);
                    Log.Info($"Renewal reminder sent to {member.Name}");
                }
            }
        }
		public StripeSubscription Get(string customerId, string subscriptionId)
		{
			return _stripeSubscriptionService.Get(customerId, subscriptionId);
		}
        public bool ProcessWebhook(string json)
        {
            var stripeEvent = StripeEventUtility.ParseEvent(json);

            // All of the types available are listed in StripeEvents
            switch (stripeEvent.Type)
            {
            case StripeEvents.CustomerSubscriptionUpdated:
                StripeSubscription stripeSubscription = Mapper <StripeSubscription> .MapFromJson(stripeEvent.Data.Object.ToString());

                var subscription = GetSubscriptionFromStripeCustomerId(stripeSubscription.CustomerId);

                // Update expiry date
                if (stripeSubscription.CurrentPeriodEnd.HasValue)
                {
                    subscription.ExpiryDate = stripeSubscription.CurrentPeriodEnd.Value;
                }

                // Update Subscription status
                subscription.Status = ToSubscriptionStatus(stripeSubscription.Status);

                Update(subscription);
                break;

            case StripeEvents.InvoicePaymentSucceeded:
                // An invoice was paid

                // Get the subscription id from the invoice
                var stripeInvoice = Mapper <StripeInvoice> .MapFromJson(stripeEvent.Data.Object.ToString());

                subscription = GetSubscriptionFromStripeCustomerId(stripeInvoice.CustomerId);

                // Get the subscription from Stripe
                StripeSubscriptionService stripeSubscriptionService = new StripeSubscriptionService();
                stripeSubscription = stripeSubscriptionService.Get(subscription.StripeCustomerId, subscription.StripeSubscriptionId);

                // Update expiry date
                if (stripeSubscription.CurrentPeriodEnd.HasValue)
                {
                    subscription.ExpiryDate = stripeSubscription.CurrentPeriodEnd.Value;
                }

                // Update Subscription status
                subscription.Status = ToSubscriptionStatus(stripeSubscription.Status);

                Update(subscription);
                break;

            case StripeEvents.CustomerSubscriptionDeleted:
                stripeSubscription = Mapper <StripeSubscription> .MapFromJson(stripeEvent.Data.Object.ToString());

                subscription = GetSubscriptionFromStripeCustomerId(stripeSubscription.CustomerId);
                if (subscription != null)
                {
                    subscription.Status = ToSubscriptionStatus(stripeSubscription.Status);
                    subscription.StripeSubscriptionId = null;
                    Update(subscription);
                }
                break;

            case StripeEvents.CustomerDeleted:
                StripeCustomer stripeCustomer = Mapper <StripeCustomer> .MapFromJson((stripeEvent.Data.Object.ToString()));

                subscription = GetSubscriptionFromStripeCustomerId(stripeCustomer.Id);
                if (subscription != null)
                {
                    subscription.StripeCustomerId = null;
                    Update(subscription);
                }
                break;
            }

            return(true);
        }
Beispiel #14
0
        private static StripeSubscription GetClientSubscription(string subscriptionId)
        {
            var subscriptionService = new StripeSubscriptionService();

            return(subscriptionService.Get(subscriptionId));
        }