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"));
        }
Exemplo n.º 2
0
        public IActionResult AddPlan(Plan plan)
        {
            var planSerVice = new PlanService();

            plan.Proname = projectService.ShowDetail((int)plan.Proid).Proname;
            var count = planSerVice.Create(plan);

            return(Redirect(Url.Action("Index", "_Plan")));
        }
Exemplo n.º 3
0
        public JsonResult AddPlan(Plan model)
        {
            var service = new PlanService();

            model.CreateDate  = DateTime.Now;
            model.UserInfo_Id = int.Parse(Session ["user"].ToString());
            //model.UserInfo = db.UserInfoSet.First(m => m.Id == uid);
            //model.Grade = db.GradeSet.First(m => m.Id == model.Grade.Id);
            //model.Subject = db.SubjectSet.First(m => m.Id == model.Subject.Id);
            //model.Textbook = db.TextbookSet.First(m => m.Id == model.Textbook.Id);
            service.Create(model);
            return(Json(true));
        }
Exemplo n.º 4
0
        //   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(PlanOfDeposit plan)
 {
     if (ModelState.IsValid)
     {
         try
         {
             PlanService.Create(Mapper.Map <PlanOfDeposit, PlanOfDepositModel>(plan));
             return(RedirectToAction("Index"));
         }
         catch (Exception ex)
         {
             ModelState.AddModelError("", ex.Message);
             return(View(plan));
         }
     }
     return(View(plan));
 }
 public int CreatePlan(string accessId, PlanDTO PlanDTO)
 {
     try
     {
         return(PlanService.Create(PlanDTO));
     }
     catch (TimeoutException)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.RequestTimeout)
         {
             Content      = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
     catch (Exception)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
         {
             Content      = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
 }
Exemplo n.º 7
0
        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"));
        }
Exemplo n.º 8
0
        public ActionResult Pay(Payment item)
        {
            var me = (User)Session["me"];

            if (me == null)
            {
                return(RedirectToAction("Index"));
            }
            var stripeToken = Request.Form["stripeToken"];

            if (String.IsNullOrEmpty(stripeToken))
            {
                TempData["result_code"] = -1;
                TempData["message"]     = "Stripe set an error with your informations";
                TempData.Keep();
                return(RedirectToAction("Index"));
            }
            var Email               = Request.Form["stripeEmail"];
            var stripeTokenType     = Request.Form["stripeTokenType"];
            var productService      = new ProductService();
            var priceService        = new PriceService();
            var invoiceItemService  = new InvoiceItemService();
            var invoiceServices     = new InvoiceService();
            var customerService     = new CustomerService();
            var planService         = new PlanService();
            var subscriptionService = new SubscriptionService();

            var original_amount = 500;
            var amount          = Convert.ToInt32(me.reduction > 0 ? original_amount * me.reduction : original_amount);

            var product = productService.Create(new ProductCreateOptions
            {
                Name = "Name of Service",
            });

            var price = priceService.Create(new PriceCreateOptions
            {
                Product    = product.Id,
                UnitAmount = amount,
                Currency   = "usd",
                Recurring  = new PriceRecurringOptions
                {
                    Interval = "month",
                },
            });

            var customer = customerService.Create(new CustomerCreateOptions
            {
                Email  = Email,
                Source = stripeToken,
            });



            var plan = planService.Create(new PlanCreateOptions
            {
                Amount        = amount,
                Currency      = "usd",
                Interval      = "month",
                IntervalCount = 1,
                Product       = product.Id, // "prod_IinH4BV2oyao8L",
            });
            var subscription = subscriptionService.Create(new SubscriptionCreateOptions
            {
                Customer = customer.Id,
                Items    = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Plan = plan.Id,
                    },
                },
            });

            if (subscription.Status == "active")
            {
                item.original_amount = 500;
                item.amount          = amount;
                item.code            = QRCodeModel.GenerateRandomString();
                item.payer_id        = me.id;
                db1.Payment.Add(item);
                db1.SaveChanges();
                TempData["result_code"] = 1;
                TempData["message"]     = "Subscription done successfully";
                TempData.Keep();
                return(RedirectToAction("Payments"));
            }
            TempData["result_code"] = -1;
            TempData["message"]     = "An error occured during the payment";
            TempData.Keep();
            return(RedirectToAction("Index"));
        }
        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));
            }
        }
Exemplo n.º 10
0
        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);
        }
Exemplo n.º 11
0
        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);
        }