public ActionResult CreatePlan(int Id) { var service = this._serviceRepo.GetServiceById(Id); var options = new PlanCreateOptions { Product = new PlanProductCreateOptions { Name = "Monthly" }, Amount = (long)(service.Rate * 100), Currency = "usd", Interval = "month", }; var planservice = new PlanService(); if (string.IsNullOrEmpty(service.StripePlanName)) { Plan plan = planservice.Create(options); this._serviceRepo.CreateStripPlanForService(Id, plan.Id); } else { Plan existingPlan = planservice.Get(service.StripePlanName); if (existingPlan == null) { Plan plan = planservice.Create(options); this._serviceRepo.CreateStripPlanForService(Id, plan.Id); } } return(RedirectToAction("Index")); }
public void SerializeDecimalTiersProperly() { var options = new PlanCreateOptions { Tiers = new List <PlanTierOptions> { new PlanTierOptions { UnitAmountDecimal = 0.003m, FlatAmountDecimal = 0.12m, UpTo = 10, }, new PlanTierOptions { UnitAmountDecimal = 0.004m, FlatAmountDecimal = 0.24m, UpTo = PlanTierUpTo.Inf, } }, }; Assert.Equal( "tiers[0][flat_amount_decimal]=0.12&tiers[0][unit_amount_decimal]=0.003&tiers[0][up_to]=10&" + "tiers[1][flat_amount_decimal]=0.24&tiers[1][unit_amount_decimal]=0.004&tiers[1][up_to]=inf", FormEncoder.CreateQueryString(options)); }
public void SerializeTiersProperly() { var options = new PlanCreateOptions { Tiers = new List <PlanTierOptions> { new PlanTierOptions { UnitAmount = 1000, UpTo = new PlanTierOptions.UpToBound { Bound = 10 } }, new PlanTierOptions { UnitAmount = 2000, UpTo = new PlanTierOptions.UpToInf() } }, }; var url = this.service.ApplyAllParameters(options, string.Empty, false); Assert.Equal("?tiers[0][unit_amount]=1000&tiers[0][up_to]=10&tiers[1][unit_amount]=2000&tiers[1][up_to]=inf", url); }
public PlanServiceTest() { this.service = new PlanService(); this.createOptions = new PlanCreateOptions { Amount = 123, Currency = "usd", Interval = "month", Nickname = "Plan Nickmame", Product = new PlanProductCreateOptions { Name = "Product Name", }, }; this.updateOptions = new PlanUpdateOptions { Metadata = new Dictionary <string, string> { { "key", "value" }, }, }; this.listOptions = new PlanListOptions { Limit = 1, }; }
public PlanServiceTest( StripeMockFixture stripeMockFixture, MockHttpClientFixture mockHttpClientFixture) : base(stripeMockFixture, mockHttpClientFixture) { this.service = new PlanService(this.StripeClient); this.createOptions = new PlanCreateOptions { Amount = 123, Currency = "usd", Interval = "month", Nickname = "Plan Nickmame", Product = new PlanProductCreateOptions { Name = "Product Name", }, }; this.updateOptions = new PlanUpdateOptions { Metadata = new Dictionary <string, string> { { "key", "value" }, }, }; this.listOptions = new PlanListOptions { Limit = 1, }; }
public virtual async Task <Plan> Create(PlanCreateOptions createOptions) { var url = this.ApplyAllParameters(createOptions, Urls.Plans, false); var response = await Requestor.Post(url); return(Mapper <Plan> .MapFromJson(response)); }
public PlanServiceTest( StripeMockFixture stripeMockFixture, MockHttpClientFixture mockHttpClientFixture) : base(stripeMockFixture, mockHttpClientFixture) { this.service = new PlanService(this.StripeClient); this.createOptions = new PlanCreateOptions { AmountDecimal = 0.01234567890m, // Ensure decimals work Currency = "usd", Interval = "month", Nickname = "Plan Nickmame", Product = new PlanProductCreateOptions { Name = "Product Name", }, }; this.createDecimalTierOptions = new PlanCreateOptions { Currency = "usd", Interval = "month", Nickname = "Plan Nickmame", Product = new PlanProductCreateOptions { Name = "Product Name", }, Tiers = new List <PlanTierOptions> { new PlanTierOptions { UnitAmountDecimal = 0.04m, UpTo = 10, }, new PlanTierOptions { UnitAmountDecimal = 0.03m, UpTo = PlanTierUpTo.Inf, }, }, }; this.updateOptions = new PlanUpdateOptions { Metadata = new Dictionary <string, string> { { "key", "value" }, }, }; this.listOptions = new PlanListOptions { Limit = 1, }; }
// step two - create plan on product:"simple-market Vendor" [Sm Admin Dashboard ??] public Plan CreatePlan(ProdPlanVm vm) { var options = new PlanCreateOptions { Product = vm.ProductId, Nickname = vm.Nickname, //"sm vendorship USD", Interval = vm.Interval, //"yearly", Currency = "usd", Amount = vm.Amount }; var service = new PlanService(); return(service.Create(options)); }
public ActionResult Create(SubscriptionPlanViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } try { var productOptions = new ProductCreateOptions { Name = viewModel.Name, Type = "service", }; var productService = new ProductService(); Product product = productService.Create(productOptions); if (product != null) { var planOptions = new PlanCreateOptions(); planOptions.Currency = viewModel.Currency; planOptions.Interval = viewModel.Interval; planOptions.Nickname = product.Name; planOptions.Amount = Convert.ToInt64(Convert.ToDecimal(viewModel.Amount) * 100); planOptions.ProductId = product.Id; var planService = new PlanService(); Plan plan = planService.Create(planOptions); } } catch (Exception ex) { var msg = ex.Message; } return(RedirectToAction("Index")); }
public void SerializeTiersProperly() { var options = new PlanCreateOptions { Tiers = new List <PlanTierOptions> { new PlanTierOptions { UnitAmount = 1000, UpTo = 10, }, new PlanTierOptions { UnitAmount = 2000, UpTo = PlanTierUpTo.Inf, } }, }; Assert.Equal( "tiers[0][unit_amount]=1000&tiers[0][up_to]=10&" + "tiers[1][unit_amount]=2000&tiers[1][up_to]=inf", FormEncoder.CreateQueryString(options)); }
public IActionResult Subscription(CustomerPaymentViewModel payment) { string email = HttpContext.Session.GetString("User"); ViewBag.isLoggedIn = 1; try { NewWebSubContext context = HttpContext.RequestServices.GetService(typeof(new_websub.NewWebSubContext)) as NewWebSubContext; string query = "select * from useraccounts u inner join address a on u.AddressId=a.addresskey where u.Email=@Email"; MySqlConnection conn = context.GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand(query, conn); MySqlParameter param = new MySqlParameter("@Email", email); param.MySqlDbType = MySqlDbType.VarChar; cmd.Parameters.Add(param); MySqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { User user = new User(); user.Email = email; user.Id = reader["UserID"].ToString(); user.FullName = reader["UserName"].ToString(); user.StripeCustomerId = ""; user.AddressLine1 = reader["Address1"].ToString(); user.AddressLine2 = reader["Address2"].ToString(); user.City = reader["City"].ToString(); user.State = reader["State"].ToString(); user.Zip = reader["Zipcode"].ToString(); user.Country = reader["Country"].ToString(); user.HistoryView = true; StripeConfiguration.SetApiKey(_stripeSettings.Value.SecretKey); var tokenoptions = new TokenCreateOptions { Card = new CreditCardOptions { Number = payment.CardNumber, ExpYear = payment.ExpiryYear, ExpMonth = payment.ExpiryMonth, Cvc = payment.Cvc } }; var tokenservice = new TokenService(); Token stripeToken = tokenservice.Create(tokenoptions); payment.cardtoken = stripeToken.Id; CustomerCreateOptions customerCreateOptions = GetCustomerCreateOptions(payment, user); var cusservice = new CustomerService(); var customers = cusservice.Create(customerCreateOptions); Subscription subscription; var plservice = new PlanService(); try { var plplan = plservice.Get(payment.subsctype); var items = new List <SubscriptionItemOption> { new SubscriptionItemOption { PlanId = plplan.Id } }; var suboptions = new SubscriptionCreateOptions { CustomerId = customers.Id, Items = items }; var subservice = new SubscriptionService(); subscription = subservice.Create(suboptions); } catch { var options = new PlanCreateOptions { Product = new PlanProductCreateOptions { Id = payment.subsctype, Name = payment.subsctype }, Amount = payment.Amount, Currency = payment.Currency, Interval = payment.subsctype, Id = payment.subsctype }; var service = new PlanService(); Plan plan = service.Create(options); var items = new List <SubscriptionItemOption> { new SubscriptionItemOption { PlanId = plan.Id } }; var suboptions = new SubscriptionCreateOptions { CustomerId = customers.Id, Items = items }; var subservice = new SubscriptionService(); subscription = subservice.Create(suboptions); } reader.Close(); // insert into subscriptions table query = "insert into subscriptions(Email, CustomerId, SubscriptionId, Subscription_Started, Subscription_Ended) values(@Email," + "@CustomerId, @SubscriptionId, @Subscription_Started, @Subscription_Ended)"; MySqlCommand cmd1 = new MySqlCommand(query, conn); MySqlParameter param1 = new MySqlParameter("@Email", user.Email); param1.MySqlDbType = MySqlDbType.VarChar; cmd1.Parameters.Add(param1); param1 = new MySqlParameter("@CustomerId", subscription.CustomerId); param1.MySqlDbType = MySqlDbType.VarChar; cmd1.Parameters.Add(param1); param1 = new MySqlParameter("@SubscriptionId", subscription.Id); param1.MySqlDbType = MySqlDbType.VarChar; cmd1.Parameters.Add(param1); param1 = new MySqlParameter("@Subscription_Started", subscription.StartDate); param1.MySqlDbType = MySqlDbType.DateTime; cmd1.Parameters.Add(param1); param1 = new MySqlParameter("@Subscription_Ended", subscription.EndedAt); param1.MySqlDbType = MySqlDbType.DateTime; cmd1.Parameters.Add(param1); cmd1.ExecuteNonQuery(); HttpContext.Session.SetInt32("isLoggedIn", 1); payment.massage = "Payment created successfully"; //return View("Success"); // render Success.cshtml return(View(payment)); } else { return(RedirectToAction(nameof(Login))); } } catch (Exception ex) { MailMessage mail = new MailMessage(); mail.From = new MailAddress(_emailSettings.Value.PrimaryEmail); mail.Subject = "Subscription Fail"; mail.IsBodyHtml = true; mail.Body = ex.Message; mail.Sender = new MailAddress(_emailSettings.Value.PrimaryEmail); mail.To.Add(email); SmtpClient smtp = new SmtpClient(); smtp.Host = _emailSettings.Value.PrimaryDomain; //Or Your SMTP Server Address smtp.Port = _emailSettings.Value.PrimaryPort; smtp.UseDefaultCredentials = false; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Credentials = new System.Net.NetworkCredential(_emailSettings.Value.PrimaryEmail, _emailSettings.Value.PrimaryPassword); //Or your Smtp Email ID and Password smtp.EnableSsl = _emailSettings.Value.EnableSsl; smtp.Send(mail); payment.massage = ex.Message; return(View(payment)); } }
public static TransactionResult CreateSessionRedirect(TransactionRequest request, StripeSettings stripeSettings, ILogger logger, bool isSubscription) { var order = request.Order; InitStripe(stripeSettings); var address = DependencyResolver.Resolve <IDataSerializer>() .DeserializeAs <Address>(order.BillingAddressSerialized); InitStripe(stripeSettings, true); //do we have a saved stripe customer id? var customerId = GetCustomerId(order.User, null, address); var subscriptionItems = new List <SessionSubscriptionDataItemOptions>(); var productService = new ProductService(); var planService = new PlanService(); foreach (var orderItem in order.OrderItems) { var product = productService.Create(new ProductCreateOptions { Name = orderItem.Product.Name, Type = "service" }); var lineTotal = orderItem.Price * orderItem.Quantity + orderItem.Tax; GetFinalAmountDetails(lineTotal, order.CurrencyCode, address, out var currencyCode, out var finalAmount); var planOptions = new PlanCreateOptions() { Nickname = product.Name, Product = product.Id, Amount = (long)finalAmount, Interval = GetInterval(orderItem.Product.SubscriptionCycle), IntervalCount = orderItem.Product.CycleCount == 0 ? 1 : orderItem.Product.CycleCount, Currency = currencyCode, UsageType = "licensed", TrialPeriodDays = orderItem.Product.TrialDays }; var plan = planService.Create(planOptions); subscriptionItems.Add(new SessionSubscriptionDataItemOptions() { Plan = plan.Id, Quantity = orderItem.Quantity }); } var options = new SessionCreateOptions { Customer = customerId, PaymentMethodTypes = new List <string> { "card", }, SubscriptionData = new SessionSubscriptionDataOptions { Items = subscriptionItems, Metadata = new Dictionary <string, string>() { { "orderGuid", order.Guid }, { "internalId", order.Id.ToString() }, { "isSubscription", isSubscription.ToString() } } }, SuccessUrl = ApplicationEngine.RouteUrl(StripeConfig.StripeReturnUrlRouteName, new { orderGuid = order.Guid }, true), CancelUrl = ApplicationEngine.RouteUrl(StripeConfig.StripeCancelUrlRouteName, new { orderGuid = order.Guid }, true), Mode = isSubscription ? "subscription" : "payment", }; var service = new SessionService(); var session = service.Create(options); var processPaymentResult = new TransactionResult() { OrderGuid = order.Guid, }; if (session != null && !session.Id.IsNullEmptyOrWhiteSpace()) { processPaymentResult.NewStatus = PaymentStatus.Processing; processPaymentResult.TransactionCurrencyCode = order.CurrencyCode; processPaymentResult.IsSubscription = true; processPaymentResult.TransactionAmount = order.OrderTotal; processPaymentResult.ResponseParameters = new Dictionary <string, object>() { { "sessionId", session.Id }, { "paymentIntentId", session.PaymentIntentId } }; processPaymentResult.Success = true; processPaymentResult.Redirect(ApplicationEngine.RouteUrl(StripeConfig.StripeRedirectToUrlRouteName, new { orderGuid = order.Guid, sessionId = session.Id })); } else { processPaymentResult.Success = false; logger.Log <TransactionResult>(LogLevel.Warning, $"The session for Order#{order.Id} by stripe redirect failed." + session?.StripeResponse.Content); } return(processPaymentResult); }
public static TransactionResult CreateSubscription(TransactionRequest request, StripeSettings stripeSettings, ILogger logger) { var order = request.Order; InitStripe(stripeSettings); var parameters = request.Parameters; parameters.TryGetValue("cardNumber", out var cardNumber); parameters.TryGetValue("cardName", out var cardName); parameters.TryGetValue("expireMonth", out var expireMonthStr); parameters.TryGetValue("expireYear", out var expireYearStr); parameters.TryGetValue("cvv", out var cvv); var paymentMethodService = new PaymentMethodService(); var paymentMethod = paymentMethodService.Create(new PaymentMethodCreateOptions() { Card = new PaymentMethodCardCreateOptions() { Number = cardNumber.ToString(), ExpYear = long.Parse(expireYearStr.ToString()), ExpMonth = long.Parse(expireMonthStr.ToString()), Cvc = cvv.ToString() }, Type = "card" }); var address = DependencyResolver.Resolve <IDataSerializer>() .DeserializeAs <Address>(order.BillingAddressSerialized); InitStripe(stripeSettings, true); //do we have a saved stripe customer id? var customerId = GetCustomerId(order.User, paymentMethod, address); var subscriptionItems = new List <SubscriptionItemOptions>(); var productService = new ProductService(); var planService = new PlanService(); foreach (var orderItem in order.OrderItems) { var product = productService.Create(new ProductCreateOptions { Name = orderItem.Product.Name, Type = "service" }); var lineTotal = orderItem.Price * orderItem.Quantity + orderItem.Tax; GetFinalAmountDetails(lineTotal, order.CurrencyCode, address, out var currencyCode, out var finalAmount); var planOptions = new PlanCreateOptions() { Nickname = product.Name, Product = product.Id, Amount = (long)(finalAmount), Interval = GetInterval(orderItem.Product.SubscriptionCycle), IntervalCount = orderItem.Product.CycleCount == 0 ? 1 : orderItem.Product.CycleCount, Currency = currencyCode, UsageType = "licensed", TrialPeriodDays = orderItem.Product.TrialDays }; var plan = planService.Create(planOptions); subscriptionItems.Add(new SubscriptionItemOptions() { Plan = plan.Id, Quantity = orderItem.Quantity }); } //create a coupon if any var coupon = GetCoupon(order); var subscriptionOptions = new SubscriptionCreateOptions() { Customer = customerId, Items = subscriptionItems, Metadata = new Dictionary <string, string>() { { "orderGuid", order.Guid }, { "internalId", order.Id.ToString() }, { "isSubscription", bool.TrueString } }, Coupon = coupon?.Id, #if DEBUG TrialEnd = DateTime.UtcNow.AddMinutes(5) #endif }; subscriptionOptions.AddExpand("latest_invoice.payment_intent"); var subscriptionService = new SubscriptionService(); var subscription = subscriptionService.Create(subscriptionOptions); var processPaymentResult = new TransactionResult() { OrderGuid = order.Guid, }; if (subscription.Status == "active" || subscription.Status == "trialing") { processPaymentResult.NewStatus = PaymentStatus.Complete; processPaymentResult.TransactionCurrencyCode = order.CurrencyCode; processPaymentResult.IsSubscription = true; processPaymentResult.TransactionAmount = (subscription.Plan.AmountDecimal / 100) ?? order.OrderTotal; processPaymentResult.ResponseParameters = new Dictionary <string, object>() { { "subscriptionId", subscription.Id }, { "invoiceId", subscription.LatestInvoiceId }, { "feePercent", subscription.ApplicationFeePercent }, { "collectionMethod", subscription.CollectionMethod }, { "metaInfo", subscription.Metadata } }; processPaymentResult.Success = true; } else { processPaymentResult.Success = false; logger.Log <TransactionResult>(LogLevel.Warning, $"The subscription for Order#{order.Id} by stripe failed with status {subscription.Status}." + subscription.StripeResponse.Content); } return(processPaymentResult); }