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(); } }
public HttpResponseMessage Delete(string id, int organizationId, CancelReason cancelReason, string cancelText) { OrganizationId = organizationId; try { if (UserIsAdminOfOrganization) { var customerService = new StripeCustomerService(); StripeSubscription stripeSubscription = customerService.CancelSubscription(id); // you can optionally pass cancelAtPeriodEnd instead of immediately cancelling var organization = this.organizationService.Get(organizationId); organization.Subscription.Status = SubscriptionStatus.INACTIVE; organization.Subscription.CustomerBillingId = id; organization.Subscription.CancelReason = cancelReason; this.subscriptionService.SaveSubscription(organization); emailHelper.SendCancelNotice(id, organizationId, System.Enum.GetName(typeof(CancelReason), cancelReason), cancelText); return(Request.CreateResponse(HttpStatusCode.Accepted)); } } catch (StripeException ex) { emailHelper.SendStripeError(ex); } catch (Exception e) { emailHelper.SendErrorEmail(e); } return(Request.CreateResponse(HttpStatusCode.BadRequest)); }
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); }
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; } }
public async Task <IActionResult> UpgradeAccountPlan(IndexViewModel model, IFormCollection collection) { string newSubscriptonSelection = model.PaymentViewModel.SubscriptionPlan; var user = await GetCurrentUserAsync(); if (user != null) { using (_dbContext) { var dbUser = _dbContext.Users.Find(user.Id); //Process subscription payment string stripeToken = collection["stripeToken"]; StripeSubscription stripeSubscription = _stripeService.SubscribeToPlan(dbUser, stripeToken, newSubscriptonSelection); dbUser.SubscriptionPlan = newSubscriptonSelection; dbUser.StripeCustomerId = stripeSubscription.CustomerId; dbUser.MonthlyPromotionLimitReached = false; _dbContext.SaveChanges(); } return(RedirectToAction(nameof(Index), new { Message = ManageMessageId.AccountUpdateSuccess })); } return(RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error })); }
private static bool ChangeSubscription(StripeSubscription subscription, string option) { try { var subscriptionService = new StripeSubscriptionService(); var subscriptionToChange = (Subscriptions)(int.Parse(option)); var actualSubscription = (Subscriptions)Enum.Parse(typeof(Subscriptions), subscription.Items.Data.First().Plan.Id); var isUpgrade = subscriptionToChange > actualSubscription ? true : false; var updateSubscription = new StripeSubscriptionUpdateOptions() { Items = new List <StripeSubscriptionItemUpdateOption>() { new StripeSubscriptionItemUpdateOption() { Id = subscription.Items.Data.First().Id, PlanId = subscriptionToChange.ToString() } }, Prorate = isUpgrade }; StripeSubscription updatedSubscription = subscriptionService.Update(subscription.Id, updateSubscription); return(true); } catch (Exception ex) { Console.WriteLine($"An error ocurred while updating your subscription.\nError: { ex.Message }"); return(false); } }
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); }
private bool UpdateStripeSubscription(string email, string token, int quantity, UserInfo userInfo) { var myUpdatedSubscription = new StripeCustomerUpdateSubscriptionOptions(); //if token has been created, then replace the previous one (new credit card) if (!string.IsNullOrEmpty(token)) { myUpdatedSubscription.TokenId = token; } myUpdatedSubscription.PlanId = Constants.StripeSubscriptionPlan; myUpdatedSubscription.Quantity = quantity; var customerService = new StripeCustomerService(); try { StripeSubscription stripeSubscription = customerService.UpdateSubscription(userInfo.PaymentCustomerId, myUpdatedSubscription); //save profile ID and profile status with user info userInfo.Subscribed = true; userInfo.PaymentCustomerStatus = stripeSubscription.Status; db.Entry(userInfo).State = EntityState.Modified; } catch (Exception e) { Utilities.LogAppError("Subscription modify failed: " + e.Message); return(false); } return(true); }
CustomerPayment ISubscriptionService.SaveCustomerSubscription(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(); //Update if (id != null && id != "null") { var myCustomer = InitializeUpdateSubscriptionOptions(payment, organization); StripeSubscription stripeCustomer = customerService.UpdateSubscription(id, myCustomer); } //Create 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); }
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()); } }
public static bool UnSubscribe(string CustId) { var subsService = new StripeSubscriptionService(); StripeList <StripeSubscription> activeSub = subsService.List(new StripeSubscriptionListOptions() { CustomerId = CustId, Limit = 10 }); try { if (activeSub.Count() > 0) { foreach (var sub in activeSub) { StripeSubscription subs = subsService.Cancel(sub.Id); } } return(true); } catch (Exception ex) { return(false); } }
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); }
public int CancelSubscription(string userMail, string plansId) { StripeConfiguration.SetApiKey("sk_test_YskwifolV97dD2Iu0v8YgDt5"); var customerService = new StripeCustomerService(); StripeList <StripeCustomer> customerItems = customerService.List( new StripeCustomerListOptions() { Limit = 300 } ); bool found = false; var customer = new StripeCustomer(); foreach (StripeCustomer cus in customerItems) { if (cus.Email == userMail) { found = true; customer = cus; break; } } if (found) { var subscriptionService = new StripeSubscriptionService(); StripeList <StripeSubscription> response = subscriptionService.List(new StripeSubscriptionListOptions { Limit = 3333 }); found = false; var subscript = new StripeSubscription(); foreach (StripeSubscription subs in response) { if (subs.CustomerId == customer.Id && subs.StripePlan.Id == plansId) { found = true; subscript = subs; break; } } if (found) { StripeSubscription subscription = subscriptionService.Cancel(subscript.Id, new StripeSubscriptionCancelOptions()); } } return(0); }
public string SubscribeAccountPlan(string planId, string customerId) { var subscriptionService = new StripeSubscriptionService(); StripeSubscription stripeSubscription = subscriptionService.Create(customerId, planId); return(null); // optional StripeSubscriptionUpdateOptions return null; }
public void CreateSubscription(CustomerInfo customerInfo, string planId) { string customerId = GetCustomerId(customerInfo); StripeSubscriptionService subscriptionService = new StripeSubscriptionService(); StripeSubscription stripeSubscription = subscriptionService.Create(customerId, planId); PaymentId = stripeSubscription.Id; }
private void InsertSubscription(StripeSubscription subscription, JObject report) { new Subscription() { PlanName = subscription.StripePlan.Id, CustID = subscription.CustomerId, SubID = subscription.Id, Username = report.Property("username").Value.ToString() }.InsertIntoDocument(); }
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(); } }
public async Task PurchasePremiumAsync(User user, string paymentToken, short additionalStorageGb) { var customerService = new StripeCustomerService(); var customer = await customerService.CreateAsync(new StripeCustomerCreateOptions { Description = user.Name, Email = user.Email, SourceToken = paymentToken }); var subCreateOptions = new StripeSubscriptionCreateOptions { CustomerId = customer.Id, Items = new List <StripeSubscriptionItemOption>(), Metadata = new Dictionary <string, string> { ["userId"] = user.Id.ToString() } }; subCreateOptions.Items.Add(new StripeSubscriptionItemOption { PlanId = PremiumPlanId, Quantity = 1 }); if (additionalStorageGb > 0) { subCreateOptions.Items.Add(new StripeSubscriptionItemOption { PlanId = StoragePlanId, Quantity = additionalStorageGb }); } StripeSubscription subscription = null; try { var subscriptionService = new StripeSubscriptionService(); subscription = await subscriptionService.CreateAsync(subCreateOptions); } catch (StripeException) { await customerService.DeleteAsync(customer.Id); throw; } user.Gateway = Enums.GatewayType.Stripe; user.GatewayCustomerId = customer.Id; user.GatewaySubscriptionId = subscription.Id; user.Premium = true; user.PremiumExpirationDate = subscription.CurrentPeriodEnd; }
/// <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); }
public void Cancel(PawzeUser pawzeUser, Subscription pawzeSubscription) { var subscriptionService = new Stripe.StripeSubscriptionService(APIKey); StripeSubscription subscription = subscriptionService.Cancel(pawzeUser.StripeCustomerId, pawzeSubscription.StripeSubscriptionId); pawzeSubscription.StripeSubscriptionId = null; _subscriptionRepository.Update(pawzeSubscription); _unitOfWork.Commit(); }
private CompletedViewModel GetSubscriptionMessage(StripeSubscription result, bool HasSubscriptions) { var completedMessage = new CompletedViewModel { Message = result.StripePlan.Nickname.Split("_")[1], Message1 = result.StripePlan.Nickname.Split("_")[0], HasSubscriptions = HasSubscriptions }; return(completedMessage); }
public StripeSubscription RetrieveSubscription(string subscriptionId) { try { var subscriptionService = new StripeSubscriptionService(); StripeSubscription stripeSubscription = subscriptionService.Get(subscriptionId); return(stripeSubscription); } catch (Exception ex) { throw ex; } }
static void TestInvoices(StripePayment payment) { var invoices = payment.GetInvoices(10, 10); StripeInvoice inv = payment.GetInvoice(invoices.Data [0].ID); StripeCustomer cust = payment.CreateCustomer(new StripeCustomerInfo()); StripeSubscription sub = payment.Subscribe(cust.ID, new StripeSubscriptionInfo { Card = GetCC() }); StripeInvoice inv2 = payment.GetUpcomingInvoice(cust.ID); payment.Unsubscribe(cust.ID, true); payment.DeleteCustomer(cust.ID); }
static void TestDeserializePastDue() { string json = @"{ ""status"": ""past_due"", }"; StripeSubscription sub = JsonConvert.DeserializeObject <StripeSubscription> (json); if (sub.Status != StripeSubscriptionStatus.PastDue) { throw new Exception("Failed to deserialize `StripeSubscriptionStatus.PastDue`"); } string json2 = JsonConvert.SerializeObject(sub); }
public BillingSubscription(StripeSubscription sub) { Status = sub.Status; TrialStartDate = sub.TrialStart; TrialEndDate = sub.TrialEnd; EndDate = sub.CurrentPeriodEnd; CancelledDate = sub.CanceledAt; CancelAtEndDate = sub.CancelAtPeriodEnd; if (sub.Items?.Data != null) { Items = sub.Items.Data.Select(i => new BillingSubscriptionItem(i)); } }
protected void ReActiveMembershipLinkButton_OnClick(object sender, EventArgs e) { var subscriptionOptions = new StripeSubscriptionUpdateOptions() { PlanId = _subscriptions.StripePlanId }; var subscriptionService = new StripeSubscriptionService(); StripeSubscription subscription = subscriptionService.Update(_subscriptionBookings.StripeSubscriptionId, subscriptionOptions); var bookingRepository = new BookingRepository(); switch (subscription.Status) { case "past_due": case "unpaid": _subscriptionBookings.Status = (int)Enums.SubscriptionBookingStatus.Suspended; bookingRepository.ExpiredBookingByCancelledSubscription(PublicDiscounts.Id); break; case "active": // Set Date of Discounts _subscriptionBookings.Status = (int)Enums.SubscriptionBookingStatus.Active; // Set Date of Subscription Bookings _subscriptionBookings.StartDate = subscription.CurrentPeriodStart; _subscriptionBookings.EndDate = subscription.CurrentPeriodEnd; _subscriptionBookings.LastUpdatedDate = DateTime.UtcNow; _subscriptionBookings.LastUpdatedBy = 0; break; case "canceled": _subscriptionBookings.Status = (int)Enums.SubscriptionBookingStatus.End; bookingRepository.ExpiredBookingByCancelledSubscription(PublicDiscounts.Id); break; default: //trialing break; } _subscriptionBookings.Description = subscription.StripeResponse.ObjectJson; _subscriptionBookingRepository.Update(_subscriptionBookings); NextCycleLit.Visible = true; cancelMembershipLink.Visible = true; reactiveMembershipLink.Visible = false; ErrorMessageLabel.Visible = true; ErrorMessageLabel.Text = Message.SubscriptionReActive; ErrorMessageLabel.CssClass = "success-message"; }
public static StripeSubscription UpdatePlan(string subsId, StripeSubscriptionUpdateOptions obj) { var subscriptionService = new StripeSubscriptionService(); try { StripeSubscription stripeSubscription = subscriptionService.Update(subsId, obj); return(stripeSubscription); } catch (Exception ex) { return(null); } }
/// <summary> /// Changes the given subscription to use the new plan /// </summary> /// <param name="customer"></param> /// <param name="subscription"></param> /// <param name="newPlan"></param> /// <returns></returns> public static StripeSubscription ChangeSubscriptionPlan(ICustomerEntity customer, ISubscriptionEntity subscription, IPlanEntity newPlan) { StripeSubscriptionUpdateOptions options = new StripeSubscriptionUpdateOptions() { PlanId = newPlan.PaymentSystemId }; var subscriptionService = new StripeSubscriptionService(); StripeSubscription changedSubscription = subscriptionService.Update(customer.PaymentSystemId, subscription.PaymentSystemId, options); Logger.Log <StripeManager>("Changed subscription for customer in stripe: '{0}' with new subscription id '{1}", LogLevel.Information, customer.Email, subscription.PaymentSystemId); return(changedSubscription); }
/// <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); }
/// <summary> /// Unsubscribes the given subscription /// NOTE: Save changes on the underlying context for the model after calling this method /// </summary> /// <param name="customer"></param> /// <param name="subscription"></param> /// <returns></returns> public static StripeSubscription Unsubscribe(ICustomerEntity customer, ISubscriptionEntity subscription) { if (string.IsNullOrEmpty(subscription.PaymentSystemId) || string.IsNullOrEmpty(customer.PaymentSystemId)) { return(null); } var subscriptionService = new StripeSubscriptionService(); StripeSubscription sub = subscriptionService.Cancel(customer.PaymentSystemId, subscription.PaymentSystemId); subscription.PaymentSystemId = null; Logger.Log <StripeManager>("Unsuscribed customer in stripe: '{0}' with new subscription id '{1}", LogLevel.Information, customer.Email, subscription.PaymentSystemId); return(sub); }