public ActionResult UserActivation(String ActivationCode)
        {
            string result   = "";
            var    userInfo = new UpdateUserInfo();

            if (!String.IsNullOrEmpty(ActivationCode))
            {
                var dr = userregistrationData.AccountConfirmation(ActivationCode);
                if (dr != null)
                {
                    result = "true";
                    String StripeCustmId   = Convert.ToString(dr["stp_custId"]);
                    var    customerOptions = new StripeCustomerCreateOptions
                    {
                        Email       = Convert.ToString(dr["Email"]),
                        Description = Convert.ToString(dr["name"]),
                    };
                    var customerDetails = StripeHelper.AddCustomer(customerOptions, StripeCustmId);
                    if (customerDetails != null)
                    {
                        var planId       = (int)Statics.StripePlans.Trial;
                        var subscription = StripeHelper.Subscription(customerDetails.Id, new StripeSubscriptionCreateOptions {
                            PlanId = planId.ToString()
                        }, out result);
                        if (String.IsNullOrEmpty(result))
                        {
                            userInfo.CustId        = customerDetails.Id;
                            userInfo.UserId        = Convert.ToInt32(dr["id"]);
                            userInfo.PlanId        = planId;
                            userInfo.PlanStartDate = Convert.ToDateTime(subscription.CurrentPeriodStart).ToString();
                            userInfo.TrialEndDate  = subscription.TrialEnd.ToString();
                            userInfo.Amount        = subscription.StripePlan.Amount.ToString();
                            userInfo.PlanEndDate   = Convert.ToDateTime(subscription.CurrentPeriodEnd).ToString();
                            AccountData.UpdateStripeData(userInfo);
                        }
                        else
                        {
                            result = "Subscription error, please contact Administrator";
                        }
                    }
                }
                else
                {
                    result = "false";
                }
            }

            ViewBag.Confirmation = result;
            return(View("Login"));
        }
Beispiel #2
0
        public IActionResult RedirectToStripe(string orderGuid, string sessionId)
        {
            var order = _orderService.GetByGuid(orderGuid);

            if (order == null || sessionId.IsNullEmptyOrWhiteSpace())
            {
                return(NotFound());
            }
            var model = new RedirectToStripeModel()
            {
                PublishableKey = StripeHelper.GetPublishableKey(_stripeSettings),
                SessionId      = sessionId,
                CancelUrl      = ApplicationEngine.RouteUrl(RouteNames.CheckoutPayment, new { orderGuid, error = true })
            };

            return(R.Success.With("redirectInfo", model).Result);
        }
Beispiel #3
0
        private static int GetCustomPlan(int skuCount)
        {
            int    Totalcost   = 249;
            int    planid      = 0;
            double Extra_Count = skuCount / 250;
            int    Extra_Cost  = (int)Math.Floor(Extra_Count) * 50;

            Totalcost += Extra_Cost;

            int OldPlanId = AccountData.GetPlanId(Totalcost);

            if (OldPlanId > 0)
            {
                var plandetials = StripeHelper.GetPlan(OldPlanId.ToString());
                if (plandetials != null)
                {
                    planid = OldPlanId;
                }
            }

            if (planid < 1)
            {
                var plans = StripeHelper.GetTopPlan();
                var Plan  = plans[0];
                planid = Convert.ToInt32(Plan.Id) + 1;
                var planOptions = new StripePlanCreateOptions()
                {
                    Id       = planid.ToString(),
                    Name     = "Custom",
                    Amount   = Totalcost * 100,
                    Currency = "usd",
                    Interval = "month",
                };
                var res = StripeHelper.CreatePlan(planOptions);
                if (res != null)
                {
                    AccountData.CreateCustomPlan(planid, Totalcost);
                }
                else
                {
                    planid = 0;
                }
            }
            return(planid);
        }
        public JsonResult DeleteCode(string CodeID)
        {
            String res = "";

            try
            {
                var couponService = new StripeCouponService();
                StripeHelper.DeleteCoupon(CodeID);
                res = adata.DeleteCouponData(CodeID);
            }
            catch (Exception ex)
            {
                res = ex.Message;
            }
            return(new JsonResult {
                Data = res, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
 public ActionResult Cards()
 {
     ViewData["Last4"]   = "XXXX";
     ViewData["Expiry"]  = "00/00";
     ViewData["Brand"]   = "XYZ";
     ViewBag.IsCardAdded = false;
     ViewBag._TrailEnd   = SessionData.TrialEndOn;
     if (!string.IsNullOrWhiteSpace(SessionData.StripeCardId))
     {
         var card = StripeHelper.GetCardDetails(SessionData.StripeCustId, SessionData.StripeCardId);
         if (card != null)
         {
             ViewData["Last4"]   = card.Last4;
             ViewData["Expiry"]  = card.ExpirationMonth + "/" + card.ExpirationYear;
             ViewData["Brand"]   = card.Brand;
             ViewBag.IsCardAdded = true;
         }
     }
     return(View());
 }
        public JsonResult UpdateUserEmail(EmailViewModel model)
        {
            String FirstName = HttpContext.User.Identity.Name;
            String Email     = model.Email.Trim();
            String msg       = "";

            if (!String.IsNullOrWhiteSpace(Email))
            {
                if (!String.IsNullOrWhiteSpace(SessionData.StripeCustId))
                {
                    msg = pdata.UpdateUserProfile(SessionData.UserID, Email);
                    if (msg == "")
                    {
                        var customerOptions = new StripeCustomerUpdateOptions
                        {
                            Email = Email
                        };
                        StripeHelper.UpdateCustomer(SessionData.StripeCustId, customerOptions);
                        SessionData.Email = Email;
                        var res = dashboardData.GetAlertData(SessionData.UserID);
                        SessionData.AlertCount = res.Count;
                        String _url         = "Settings/UpdateUserEmail";
                        String emailConfirm = ealert.SendActivationEmail(SessionData.UserID, FirstName, SessionData.LastName, Email, _url, AccounType.MppUser);
                        msg += emailConfirm;
                    }
                }
                else
                {
                    msg = Constant.STRIPE_ID_NOTFOUND;
                }
            }
            else
            {
                msg = Constant.EMAIL_NOTFOUND;
            }
            return(new JsonResult()
            {
                Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
Beispiel #7
0
        public TransactionResult ProcessTransaction(TransactionRequest request)
        {
            var stripeSettings = DependencyResolver.Resolve <StripeSettings>();

            if (request.RequestType == TransactionRequestType.Payment)
            {
                if (stripeSettings.UseRedirectionFlow)
                {
                    return(StripeHelper.CreateSessionRedirect(request, stripeSettings, _logger, false));
                }
                return(StripeHelper.ProcessPayment(request, stripeSettings, _logger));
            }
            if (request.RequestType == TransactionRequestType.Refund)
            {
                return(StripeHelper.ProcessRefund(request, stripeSettings, _logger));
            }
            if (request.RequestType == TransactionRequestType.Void)
            {
                return(StripeHelper.ProcessVoid(request, stripeSettings, _logger));
            }
            if (request.RequestType == TransactionRequestType.Capture)
            {
                return(StripeHelper.ProcessCapture(request, stripeSettings, _logger));
            }
            if (request.RequestType == TransactionRequestType.SubscriptionCreate)
            {
                if (stripeSettings.UseRedirectionFlow)
                {
                    return(StripeHelper.CreateSessionRedirect(request, stripeSettings, _logger, true));
                }
                return(StripeHelper.CreateSubscription(request, stripeSettings, _logger));
            }
            if (request.RequestType == TransactionRequestType.SubscriptionCancel)
            {
                return(StripeHelper.StopSubscription(request, stripeSettings, _logger));
            }
            return(null);
        }
Beispiel #8
0
        private AffiliationCode ConvertToAffiliation(DataRow row)
        {
            var times_redeemed = 0;
            var Code           = row.Field <String>("AffiliateCode");
            var coupon         = StripeHelper.GetCoupon(Code);
            var sales          = row.Field <Decimal>("Sales");

            if (coupon != null)
            {
                times_redeemed = coupon.TimesRedeemed;
            }
            var couponamount = row.Field <Decimal>("Amount");
            var actualPrice  = row.Field <Decimal>("PreOffSale");
            var offInPercent = row.Field <int>("Percent_off");
            var customers    = row.Field <int>("Subscribers");
            var commision    = Math.Round(row.Field <Decimal>("Commision"), 2);
            var assignId     = row.Field <int>("AssignId");

            return(new AffiliationCode()
            {
                ID = row.Field <int>("AffiliateID"),
                Code = Code,
                Percent = offInPercent,
                Duration = row.Field <int>("Duration"),
                Sales = sales,
                Subscribers = customers,
                Amount = couponamount,
                Max = row.Field <int>("Maxredeem"),
                Redeemby = row.Field <DateTime?>("Redeemby"),
                PreDiscountSale = actualPrice,
                AffiliateCommission = (commision <= 0.00M)?0.00M: commision,
                CreatedBy = row.Field <string>("CreatedBy"),
                IsAssigned = assignId <= 0 ? false : true,
                RedeemedCount = times_redeemed
            });
        }
Beispiel #9
0
        //All Services
        public void Process_AllServices()
        {
            DataTable dtbl = null, dtbl1 = null, dtbl2 = null;
            DataSet   ds    = null;
            var       sdata = new SellerData();

            dtbl = sdata.GetUserStatus();
            if (dtbl.Rows.Count > 0)
            {
                foreach (DataRow rw in dtbl.Rows)
                {
                    bool   subscription = false;
                    int    UserId       = Convert.ToInt32(rw["MppUserID"]);
                    String CustmID      = Convert.ToString(rw["stp_custId"]);
                    if (!String.IsNullOrWhiteSpace(CustmID))
                    {
                        subscription = StripeHelper.UnSubscribe(CustmID);    //unsubscribe the users either whose status is 2 or active with no card
                    }
                    if (subscription)
                    {
                        ServicesData.UpdatePlanData(UserId, 0);
                    }
                }
            }

            ds    = sdata.GetUserEmails();
            dtbl1 = ds.Tables[0];
            dtbl2 = ds.Tables[1];

            if (dtbl1.Rows.Count > 0)
            {
                DataTable tbl = new DataTable();
                tbl.Columns.AddRange(new DataColumn[2] {
                    new DataColumn("MppUserId", typeof(Int32)),
                    new DataColumn("Limit", typeof(Int32))
                });

                //Using Parallel Multi-Threading to send multiple bulk email.
                Parallel.ForEach(dtbl1.AsEnumerable(), row =>
                {
                    String msg = "";

                    Int32 Limit  = Convert.ToInt32(row["accesslimit"]);
                    Int32 UserID = Convert.ToInt32(row["MppUserID"]);
                    msg          = alert.SendNewUserAccessAlert(row["Email"].ToString(), row["FirstName"].ToString(), row["LastName"].ToString());
                    if (msg == "")
                    {
                        tbl.Rows.Add();
                        tbl.Rows[tbl.Rows.Count - 1][0] = UserID;
                        switch (Limit)
                        {
                        case 1:
                            Limit = 2;
                            break;

                        case 2:
                            Limit = 3;
                            break;

                        default:
                            Limit = 0;
                            break;
                        }
                        tbl.Rows[tbl.Rows.Count - 1][1] = Limit;
                    }
                });
                if (tbl.Rows.Count > 0)
                {
                    sdata.UpdateUserAccessLimit(tbl);
                }
            }

            if (dtbl2.Rows.Count > 0)
            {
                DataTable tbl1 = new DataTable();
                DataTable tbl2 = new DataTable();
                tbl1.Columns.AddRange(new DataColumn[2] {
                    new DataColumn("UserID", typeof(Int32)),
                    new DataColumn("Status", typeof(Int32))
                });
                tbl2.Columns.AddRange(new DataColumn[2] {
                    new DataColumn("UserID", typeof(Int32)),
                    new DataColumn("Status", typeof(Int32))
                });

                //Using Parallel Multi-Threading to send multiple bulk email.
                Parallel.ForEach(dtbl2.AsEnumerable(), row =>
                {
                    String msg            = "";
                    Int32 UserID          = Convert.ToInt32(row["MppUserID"]);
                    String FirstName      = Convert.ToString(row["FirstName"]);
                    String LastName       = Convert.ToString(row["LastName"]);
                    String Email          = Convert.ToString(row["Email"]);
                    DateTime TrialEndDate = Convert.ToDateTime(row["TrailEndDate"]);
                    msg = alert.SendTrialExpiresAlert(Email, TrialEndDate, FirstName, LastName);
                    if (msg == "")
                    {
                        if (TrialEndDate < DateTime.Now)
                        {
                            tbl2.Rows.Add();
                            tbl2.Rows[tbl2.Rows.Count - 1][0] = UserID;
                            tbl2.Rows[tbl2.Rows.Count - 1][1] = 1;
                        }
                        else
                        {
                            tbl1.Rows.Add();
                            tbl1.Rows[tbl1.Rows.Count - 1][0] = UserID;
                            tbl1.Rows[tbl1.Rows.Count - 1][1] = 1;
                        }
                    }
                });
                if (tbl1.Rows.Count > 0)
                {
                    sdata.UpdateSevenTrialEmailStatus(tbl1);
                }
                if (tbl2.Rows.Count > 0)
                {
                    sdata.UpdateTrialEndEmailStatus(tbl2);
                }
            }

            StripeServices.RenewPlan();
        }
        public void WebHook()
        {
            try
            {
                var paymentAlertStatus = 0;
                var postdata           = new StreamReader(HttpContext.Request.InputStream).ReadToEnd();
                var data       = JObject.Parse(postdata);
                var signature  = Request.Headers["Stripe-Signature"];
                var eventid    = data["id"].ToString();
                var custid     = data["data"].First().First["customer"].ToString();
                var msg        = "";
                var emailboday = "";
                var eventdata  = StripeHelper.GetStripeEvent(eventid);

                if (eventdata != null && (eventdata.Type == "invoice.payment_succeeded" || eventdata.Type == "invoice.payment_failed"))
                {
                    String coupon_id    = null;
                    var    list         = data["data"].First().First["lines"];
                    var    Amount       = ((double)list["data"].First["amount"]) / 100;
                    var    Amount_off   = ((double)data["data"].First().First["amount_due"]) / 100;
                    var    Discount     = data["data"].First().First["discount"];
                    var    start        = (double)list["data"].First["period"]["start"];
                    var    end          = (double)list["data"].First["period"]["end"];
                    var    startperiod  = MppUtility.UnixTimeStampToDateTime(start);
                    var    endperiod    = MppUtility.UnixTimeStampToDateTime(end);
                    var    discount     = Math.Round(Amount - Amount_off, 2, MidpointRounding.AwayFromZero);
                    var    customerdata = StripeHelper.GetStripeCustomer(custid);
                    var    email        = customerdata.Email;
                    var    last4        = "";
                    var    carddetails  = StripeHelper.GetCard(custid);
                    foreach (var card in carddetails)
                    {
                        last4 = card.Last4;
                    }

                    if (Discount.Count() > 0)
                    {
                        coupon_id = Discount["coupon"]["id"].ToString();
                    }

                    switch (eventdata.Type)
                    {
                    case "invoice.payment_succeeded":
                        msg                = AccountData.UpdatePaymentStatus(custid, Amount, Amount_off, coupon_id, discount, startperiod, endperiod, 1);
                        emailboday         = "Payment Success. A payment of $" + Amount_off + " was made using your card on file ending with <b> " + last4 + " </b>";
                        paymentAlertStatus = 1;
                        break;

                    case "invoice.payment_failed":
                        msg                = AccountData.UpdatePaymentStatus(custid, Amount, Amount_off, coupon_id, discount, startperiod, endperiod, 0);
                        emailboday         = "Payment failed.Payment $" + Amount_off + " failed from your card ending with <b> " + last4 + " </b> ";
                        paymentAlertStatus = 2;
                        break;
                    }
                    if (msg == "" && Amount_off != 0)
                    {
                        var respo = EmailAlert.PaymentAlertMail(email, emailboday);
                        if (respo == "success")
                        {
                            sellerData.UpdatePaymentAlert(paymentAlertStatus, custid);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                String msg = ex.Message;
            }
        }
        //Invoice Report
        public void Invoice(string invoiceId)
        {
            var invoice   = StripeHelper.GetInvoice(invoiceId);
            var unitprice = ((double)invoice.StripeInvoiceLineItems.Data.First().Amount) / 100;
            var quantity  = 1;
            var tax       = invoice.Tax == null ? 0 : (double)(invoice.Tax) / 100;
            var total     = unitprice * quantity + tax;
            var amount    = (double)invoice.Total / 100; //after discount
            var discount  = Math.Round(total - amount, 2, MidpointRounding.AwayFromZero);
            var username  = HttpContext.User.Identity.Name + " " + SessionData.LastName;
            var email     = SessionData.Email;
            var desc      = "Monthly Plan - " + invoice.StripeInvoiceLineItems.Data.First().Plan.Name;
            var fileName  = "Invoice_MPP_" + invoice.StripeInvoiceLineItems.Data.First().Plan.Name + "_" + DateTime.Now.ToShortDateString();


            Document document   = new Document(PageSize.A4, 88f, 88f, 50f, 10f);
            Font     NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);

            using (MemoryStream ms = new MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(document, ms);
                Phrase    phrase = null;
                PdfPCell  cell   = null;
                PdfPTable table  = null;
                BaseColor color  = null;

                document.Open();

                //row1

                //Header Table
                table             = new PdfPTable(2);
                table.TotalWidth  = 500f;
                table.LockedWidth = true;
                table.SetWidths(new float[] { 0.5f, 0.5f });



                //Company Name and Address
                phrase = new Phrase();
                phrase.Add(new Chunk("INVOICE", FontFactory.GetFont("Arial", 20, Font.BOLD, BaseColor.BLACK)));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                cell.VerticalAlignment = Element.ALIGN_TOP;
                table.AddCell(cell);
                //Company Logo
                cell = ImageCell("~/content/images/logo.png", 80f, Element.ALIGN_RIGHT);
                table.AddCell(cell);
                document.Add(table);
                // separation line header
                color = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#A9A9A9"));
                //line1
                DrawLine(writer, 25f, document.Top - 50f, document.PageSize.Width - 25f, document.Top - 50f, color);
                DrawLine(writer, 25f, document.Top - 51f, document.PageSize.Width - 25f, document.Top - 51f, color);


                //vendor or user details
                table             = new PdfPTable(3);
                table.TotalWidth  = 500f;
                table.LockedWidth = true;
                table.SetWidths(new float[] { 0.3f, 0.3f, 0.4f });
                table.SpacingBefore = 80f;

                //row2

                //user address
                phrase = new Phrase();
                phrase.Add(new Chunk(username + "\n\n" + email, FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);
                //Date
                phrase = new Phrase();
                phrase.Add(new Chunk("Date\n\n" + invoice.Date.Value.ToShortDateString(), FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
                cell = PhraseCell(phrase, Element.ALIGN_CENTER);
                table.AddCell(cell);
                //vendor address
                phrase = new Phrase();
                phrase.Add(new Chunk("My PPC Pal, LLC \n P.O. Box 2126 \n Yorba Linda, CA 92885", FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
                cell = PhraseCell(phrase, Element.ALIGN_RIGHT);
                table.AddCell(cell);
                document.Add(table);


                //row 3
                table               = new PdfPTable(1);
                table.TotalWidth    = 500f;
                table.LockedWidth   = true;
                table.SpacingBefore = 35f;

                phrase = new Phrase();
                phrase.Add(new Chunk("Invoice Number : " + invoice.Id + "\n", FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);
                document.Add(table);

                DrawLine(writer, 25f, document.Top - 190f, document.PageSize.Width - 25f, document.Top - 190f, BaseColor.BLACK); //line 2

                //row 4
                var FontColor  = new BaseColor(51, 122, 183);
                var HeaderFont = FontFactory.GetFont("Arial", 10, Font.BOLD, FontColor);

                table               = new PdfPTable(5);
                table.TotalWidth    = 500f;
                table.LockedWidth   = true;
                table.SpacingBefore = 15f;
                table.SetWidths(new float[] { 0.4f, 0.2f, 0.2f, 0.1f, 0.1f });

                //description
                phrase = new Phrase();
                phrase.Add(new Chunk("Description", HeaderFont));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);
                //Unit price
                phrase = new Phrase();
                phrase.Add(new Chunk("Unit Price", HeaderFont));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);
                //Discount
                phrase = new Phrase();
                phrase.Add(new Chunk("Discount", HeaderFont));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);
                //Tax
                phrase = new Phrase();
                phrase.Add(new Chunk("Tax", HeaderFont));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);
                //Amount
                phrase = new Phrase();
                phrase.Add(new Chunk("Amount", HeaderFont));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);

                document.Add(table);
                DrawLine(writer, 25f, document.Top - 220, document.PageSize.Width - 25f, document.Top - 220f, BaseColor.BLACK); //line 3
                //row 5
                table               = new PdfPTable(5);
                table.TotalWidth    = 500f;
                table.LockedWidth   = true;
                table.SpacingBefore = 25f;
                table.SetWidths(new float[] { 0.4f, 0.2f, 0.2f, 0.1f, 0.1f });

                //description
                phrase = new Phrase();
                phrase.Add(new Chunk(desc, FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);
                //Unit price
                phrase = new Phrase();
                phrase.Add(new Chunk("$ " + unitprice.ToString(), FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);
                //Discount
                phrase = new Phrase();
                phrase.Add(new Chunk("$ " + discount.ToString(), FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);
                //Tax
                phrase = new Phrase();
                phrase.Add(new Chunk("$ " + tax.ToString(), FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);
                //Amount
                phrase = new Phrase();
                phrase.Add(new Chunk("$ " + amount.ToString(), FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);

                document.Add(table);
                DrawLine(writer, 25f, document.Top - 260, document.PageSize.Width - 25f, document.Top - 260f, BaseColor.BLACK); //line 3
                //row 6
                table               = new PdfPTable(2);
                table.TotalWidth    = 500f;
                table.LockedWidth   = true;
                table.SpacingBefore = 25f;
                table.SetWidths(new float[] { 0.9f, 0.1f });

                //Total
                phrase = new Phrase();
                phrase.Add(new Chunk("Total:", FontFactory.GetFont("Arial", 10, Font.BOLD, BaseColor.BLACK)));
                cell = PhraseCell(phrase, Element.ALIGN_RIGHT);
                table.AddCell(cell);
                //Total Amount
                phrase = new Phrase();
                phrase.Add(new Chunk("$ " + amount.ToString(), FontFactory.GetFont("Arial", 10, Font.NORMAL, BaseColor.BLACK)));
                cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                table.AddCell(cell);
                document.Add(table);

                //row 7
                table               = new PdfPTable(1);
                table.TotalWidth    = 500f;
                table.LockedWidth   = true;
                table.SpacingBefore = 80f;
                //declaration
                var card = StripeHelper.GetCard(SessionData.StripeCustId);
                if (SessionData.StripeCustId != null && card != null && card.FirstOrDefault() != null)
                {
                    var str = "Your card on file ending in " + StripeHelper.GetCard(SessionData.StripeCustId).FirstOrDefault().Last4 + " will be billed automatically for the total amount shown on this invoice";
                    phrase = new Phrase();
                    phrase.Add(new Chunk(str, FontFactory.GetFont("Arial", 9, Font.NORMAL, BaseColor.BLACK)));
                    cell = PhraseCell(phrase, Element.ALIGN_LEFT);
                    table.AddCell(cell);
                    document.Add(table);
                }



                //row 8
                table               = new PdfPTable(1);
                table.TotalWidth    = 500f;
                table.LockedWidth   = true;
                table.SpacingBefore = 50f;
                //declaration

                var renewals = @"Renewals: This order renews for additional 1 month periods, unless either party provides the other with a notice of non-renewal prior to the renewal date. 
                              Terms: This order is governed by the terms of the Subscription Services Agreement between the parties, which terms are incorporated into this order for all purposes.
                             If there is a conflict between the terms of this order and the agreement, this order governs.
                             This order and the agreement are the entire agreement between the parties, and they supersede and replace all prior and contemporaneous negotiations, agreements, representations and discussions regarding this subject matter.
                             Only a signed writing of the parties may amend this order.";
                renewals = renewals.Replace(Environment.NewLine, String.Empty).Replace("  ", String.Empty);
                Chunk  beginning = new Chunk(renewals, FontFactory.GetFont("Arial", 6));
                Phrase p1        = new Phrase(beginning);


                cell = PhraseCell(p1, Element.ALIGN_LEFT);

                table.AddCell(cell);
                document.Add(table);

                document.Close();
                byte[] bytes = ms.ToArray();
                ms.Close();
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf");
                Response.ContentType = "application/pdf";
                Response.Buffer      = true;
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);
                Response.End();
                Response.Close();
            }
        }
        //Billing
        public ActionResult CreateStripeCustomer(string token)
        {
            var          email           = Session["Email"].ToString();
            var          subscription    = new StripeSubscription();
            var          customerDetails = new StripeCustomer();
            var          userInfo        = new UpdateUserInfo();
            string       msg             = "";
            var          cardStatus      = 0;
            DataTable    userData;
            StripeCharge charge = null;

            try
            {
                if (token != null)
                {
                    var ds = new AccountData().ValidateEmailAndGetUserinfo(email);
                    userData = ds.Tables[0];
                    var custID = Convert.ToString(userData.Rows[0]["stp_custId"]);
                    if (userData.Rows.Count > 0 && !string.IsNullOrWhiteSpace(custID))                                 //update
                    {
                        var customerUpdateOptions = new StripeCustomerUpdateOptions
                        {
                            Email       = email,
                            Description = Session["FirstName"] + " " + Session["LastName"],
                            SourceToken = token
                        };

                        //updated customer
                        customerDetails = StripeHelper.UpdateCustomer(custID, customerUpdateOptions);

                        //add a test charge for $1
                        var makeTestCharge = new StripeChargeCreateOptions
                        {
                            CustomerId  = customerDetails.Id,
                            Amount      = 100,
                            Currency    = "usd",
                            Description = "Card verification charge",
                            SourceTokenOrExistingSourceId = customerDetails.DefaultSourceId
                        };
                        charge = StripeHelper.MakePayment(makeTestCharge);
                        if (charge != null)
                        {
                            var refund = StripeHelper.RefundCharge(charge.Id);
                            cardStatus      = 1;
                            userInfo.CustId = customerDetails.Id;
                            userInfo.CardId = customerDetails.DefaultSourceId;
                            userInfo.UserId = Convert.ToInt32(Session["UserID"]);
                            AccountData.UpdateStripeCardData(userInfo);
                            if ((SessionData.PlanID == 1 && SessionData.TrialEndOn < DateTime.Now) || SessionData.PlanStatus == 0) //When trail was expired || Unsubscribed and adding a card since payments are not succesfull
                            {
                                msg = StripeServices.SubscribePlan(SessionData.StripeCustId, userInfo.CardId);
                            }
                            if (String.IsNullOrWhiteSpace(msg))
                            {
                                SessionData.PlanStatus   = 1; //Default subscription
                                SessionData.StripeCustId = customerDetails.Id;
                                SessionData.StripeCardId = customerDetails.DefaultSourceId;
                            }
                        }
                        else
                        {
                            StripeHelper.DeleteCard(customerDetails.DefaultSourceId, custID);
                            cardStatus = 0;
                        }
                    }
                    customerDetails = StripeHelper.GetStripeCustomer(customerDetails.Id);
                }

                var respo = new { Status = cardStatus, Message = msg, CustomerDetails = customerDetails };
                return(Json(respo, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                LogFile.WriteLog("CreateCustomer - " + ex.Message.ToString());
                return(Json(null, JsonRequestBehavior.AllowGet));
            }
        }
        //GET: Statements
        public ActionResult Statements()
        {
            List <StatementViewModel> statements = new List <StatementViewModel>();

            // To check user exist or not if exist then check codition is user active/IsArchive/profileAccess i.e expire/deleted/not access By Tarun 29-8-2018
            Boolean IsAllowToDowload = true;
            var     userData         = AccountData.GetUserDetails(SessionData.UserID);

            if (userData.Rows.Count > 0)
            {
                DataRow dr = userData.Rows[0];
                if (Convert.ToBoolean(dr["Active"]) == false)
                {
                    IsAllowToDowload = false;
                }
                else if (Convert.ToBoolean(dr["IsArchive"]) == true)
                {
                    IsAllowToDowload = false;
                }
                else if (Convert.ToInt32(dr["ProfileAccess"]) == 0)
                {
                    IsAllowToDowload = false;
                }
                else if (Convert.ToBoolean(dr["IsAccountLocked"]) == true)
                {
                    IsAllowToDowload = false;
                }
            }
            else
            {
                IsAllowToDowload = false;
            }


            if (!IsAllowToDowload)
            {
                return(View(statements));
            }
            //End 29-8-2018

            //StripeServices.RenewTrailPlan();
            var invoices = StripeHelper.GetInvoices(SessionData.StripeCustId);
            //var customer = StripeHelper.GetStripeCustomer(SessionData.StripeCustId);

            //var charges = StripeHelper.GetCharges(SessionData.StripeCustId);
            var timeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");

            if (invoices != null && invoices.Count > 0)
            {
                foreach (var item in invoices)
                {
                    if (item.StripeInvoiceLineItems.Data.First().Plan != null)
                    {
                        statements.Add(new StatementViewModel
                        {
                            Date        = item.Date.Value.ToShortDateString(),
                            Period      = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(item.StripeInvoiceLineItems.Data.First().StripePeriod.Start.Value.ToString()), timeZone).ToShortDateString() + "-" + TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(item.StripeInvoiceLineItems.Data.First().StripePeriod.End.Value.ToString()), timeZone).AddDays(-1).ToShortDateString(),
                            Price       = ((double)(item.AmountDue / 100)).ToString(),
                            Description = item.StripeInvoiceLineItems.Data.First().Plan.Name,
                            Id          = item.Id
                        });
                    }
                }
            }
            return(View(statements));
        }
Beispiel #14
0
        public static void RenewPlan()
        {
            int UserId = 0;

            try
            {
                var subs = ServicesData.GetSubscribers();
                int plan;
                if (subs.Rows.Count > 0)
                {
                    foreach (DataRow row in subs.Rows)
                    {
                        String msg        = "";
                        String CustomerId = row["stp_custId"].ToString();
                        String CardId     = row["stp_cardId"].ToString();
                        UserId = Convert.ToInt32(row["MppUserID"]);

                        if (!String.IsNullOrWhiteSpace(CustomerId) && !String.IsNullOrWhiteSpace(CardId))
                        {
                            var profile = APIData.GetUserProfileForSkuData(UserId);

                            if (profile.Rows.Count > 0)
                            {
                                DataRow  dr            = profile.Rows[0];
                                String   ProfileId     = Convert.ToString(dr["ProfileId"]);
                                DateTime LastUpdatedOn = Convert.ToDateTime(dr["AccessTokenUpdatedOn"]);

                                var Auth = new AuthorizationModel()
                                {
                                    access_token  = Convert.ToString(dr["AccessToken"]),
                                    refresh_token = Convert.ToString(dr["RefreshToken"]),
                                    token_type    = Convert.ToString(dr["TokenType"]),
                                    expires_in    = Convert.ToInt32(dr["TokenExpiresIn"])
                                };
                                var reportApi = new ReportsAPI();
                                var skuCount  = AccountData.UserSkuCount(UserId);
                                if (String.IsNullOrWhiteSpace(msg))
                                {
                                    if (skuCount > 250)
                                    {
                                        plan = GetCustomPlan(skuCount);
                                    }
                                    else
                                    {
                                        plan = GetPlanBySku(skuCount);
                                    }
                                    var subsPlan   = new StripeSubscription();
                                    var subService = StripeHelper.GetSubscription(CustomerId);
                                    if (subService != null)
                                    {
                                        subsPlan = StripeHelper.UpdateSubscription(CustomerId, subService.Id, new Stripe.StripeSubscriptionUpdateOptions {
                                            PlanId = plan.ToString(), Prorate = false
                                        }, out msg);
                                    }
                                    else
                                    {
                                        subsPlan = StripeHelper.Subscription(CustomerId, new Stripe.StripeSubscriptionCreateOptions {
                                            PlanId = plan.ToString()
                                        }, out msg);
                                    }
                                    if (String.IsNullOrWhiteSpace(msg))
                                    {
                                        UpdateUserInfo userInfo = new UpdateUserInfo
                                        {
                                            Amount        = ((double)(subsPlan.StripePlan.Amount) / 100).ToString(),
                                            CardId        = CardId,
                                            CustId        = CustomerId,
                                            UserId        = UserId,
                                            PlanId        = plan,
                                            EndedAt       = subsPlan.CurrentPeriodEnd.ToString(),
                                            PlanStartDate = subsPlan.CurrentPeriodStart.ToString(),
                                            PlanEndDate   = subsPlan.CurrentPeriodEnd.ToString(),
                                            TrialEndDate  = row["TrailEndDate"].ToString()
                                        };
                                        ServicesData.UpdateStripeData(userInfo);
                                    }
                                    else
                                    {
                                        LogAPI.WriteLog("RenewPlan - " + msg, UserId.ToString());
                                    }
                                }
                                else
                                {
                                    LogAPI.WriteLog("RenewPlan - " + msg, UserId.ToString());
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.WriteLog("RenewPlan - " + ex.Message, UserId.ToString());
            }
        }
        public async Task <IActionResult> ThreeDSecure(string source, bool livemode, string client_secret)
        {
            var order = _context.Orders.Where(x => x.StripeSource == source).Include(x => x.DeliveryType).SingleOrDefault();

            var userId    = _userManager.GetUserId(User);
            var viewModel = new CheckoutViewModel()
            {
                Basket        = OrderHelper.GetOrder(order.Id, _context),
                DeliveryTypes = _context.DeliveryTypes.
                                Where(x => x.Id > 0).
                                Include(x => x.DeliveryCompany).
                                ToList(),
                Contacts = _context.CustomerContacts.
                           Where(x => x.UserId == userId).
                           ToList()
            };

            var result = StripeHelper.ChargeSource(source, livemode, client_secret, order.Id, "OrderId");

            order.SellerMessage = result.SellerMessage;
            order.PaymentId     = result.Id;
            order.PaymentStatus = result.NetworkStatus;

            try
            {
                _context.Update(order);
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            if (result.NetworkStatus == MasterStrings.StripeDeclined)
            {
                var messages = new DeclineMessageViewModel();
                messages = StripeHelper.DeclineMessage(result.Reason);

                var statusMessage = messages.StatusMessage;
                order.PaymentMessage = messages.PaymentMessage;

                return(ControllerHelper.RedirectToLocal(this, "/Checkout/Index?id=" + order.Id + "&&failureMessage=" + statusMessage));
            }

            if (result.NetworkStatus == MasterStrings.StripeApproved ||
                result.NetworkStatus == MasterStrings.StripeNotSent && result.Type == MasterStrings.StripeResultPending)
            {
                await PlaceOrder(order.Id);

                return(ControllerHelper.RedirectToLocal(this, "/Checkout/OrderPlaced?id=" + order.Id));
            }

            if (result.NetworkStatus == MasterStrings.StripeReversed ||
                (result.NetworkStatus == MasterStrings.StripeNotSent && result.Type != MasterStrings.StripeResultPending))
            {
                var statusMessage = "The payment has been declined.<br/>Please contact your card issuer for more information.";
                order.PaymentMessage = "Status reason: " + result.Reason;

                return(ControllerHelper.RedirectToLocal(this, "/Checkout/Index?id=" + order.Id + "&&failureMessage" + statusMessage));
            }

            return(View());
        }
        public async Task <IActionResult> Index(CheckoutViewModel model)
        {
            bool isValid = true;
            var  user    = await _userManager.GetUserAsync(User);

            // stripe token?
            if (string.IsNullOrWhiteSpace(model.StripeToken) &&
                string.IsNullOrWhiteSpace(model.PayPal))
            {
                isValid              = false;
                model.StatusMessage += "Payment details required.";
            }

            // DeliveryType?
            if (model.Basket.DeliveryType == null)
            {
                isValid              = false;
                model.StatusMessage += "Delivery method required.";
            }

            // address
            if (string.IsNullOrWhiteSpace(model.Basket.CustomerContact.AddressLine1) ||
                string.IsNullOrWhiteSpace(model.Basket.CustomerContact.PostTown) ||
                string.IsNullOrWhiteSpace(model.Basket.CustomerContact.Postcode))
            {
                isValid              = false;
                model.StatusMessage += "Delivery address required. Please ensure Address Line 1, Post Town and Post Code are completed.";
            }

            if (isValid)
            {
                // update contact address and delivery type
                var inDb = OrderHelper.GetOrder(model.Basket.Id, _context);

                var deliveryType = _context.DeliveryTypes.
                                   Where(x => x.Id == model.Basket.DeliveryType.Id).
                                   SingleOrDefault();

                inDb.DeliveryType = deliveryType;

                var country = model.Basket.CustomerContact.Country;

                if (country == "Please Select")
                {
                    country = "";
                }

                var contact = new CustomerContact()
                {
                    BuildingNumber = model.Basket.CustomerContact.BuildingNumber,
                    AddressLine1   = model.Basket.CustomerContact.AddressLine1,
                    AddressLine2   = model.Basket.CustomerContact.AddressLine2,
                    PostTown       = model.Basket.CustomerContact.PostTown,
                    County         = model.Basket.CustomerContact.County,
                    Postcode       = model.Basket.CustomerContact.Postcode,
                    Country        = country,
                    MobilePhone    = model.Basket.CustomerContact.MobilePhone,
                    WorkPhone      = model.Basket.CustomerContact.WorkPhone,
                    OtherPhone     = model.Basket.CustomerContact.OtherPhone,
                    UserId         = user.Id
                };

                decimal orderTotalPrice = 0;

                foreach (var item in inDb.OrderItems)
                {
                    var product = _context.Products.
                                  Where(x => x.Id == item.ProductId).
                                  SingleOrDefault();

                    orderTotalPrice += product.Price;
                }

                inDb.CustomerContact        = contact;
                inDb.OrderTotalPostagePrice = inDb.DeliveryType.Price;
                inDb.OrderSubTotalPrice     = orderTotalPrice;
                inDb.OrderTotalPrice        = inDb.OrderSubTotalPrice + inDb.DeliveryType.Price;

                // create charge
                if (!string.IsNullOrWhiteSpace(model.StripeToken))
                {
                    // create charge
                    int amount = Convert.ToInt32(inDb.OrderTotalPrice * 100);

                    if (model.ThreeDSecure == MasterStrings.ThreeDSecureRequired || model.ThreeDSecure == MasterStrings.ThreeDSecureRecommended)
                    {
                        var source = StripeHelper.CreateSource(model.StripeToken, amount, "http://localhost:5000/Checkout/ThreeDSecure");

                        inDb.StripeSource = source.Id;

                        _context.Update(inDb);
                        _context.SaveChanges();

                        return(Redirect(source.Redirect.Url));
                    }

                    var result = StripeHelper.CreateCharge(model.StripeToken, model.Basket.Id, "OrderId", amount);

                    inDb.SellerMessage = result.SellerMessage;
                    inDb.PaymentId     = result.Id;
                    inDb.PaymentStatus = result.NetworkStatus;
                    inDb.StripeSource  = model.StripeToken;

                    _context.Update(inDb);
                    _context.SaveChanges();


                    if (result.NetworkStatus == MasterStrings.StripeDeclined)
                    {
                        var messages = new DeclineMessageViewModel();
                        messages = StripeHelper.DeclineMessage(result.Reason);

                        model.FailureMessage       += messages.StatusMessage;
                        model.Basket.PaymentMessage = messages.PaymentMessage;

                        return(ControllerHelper.RedirectToLocal(this, "/Checkout?id=" + model.Basket.Id + "&&failureMessage=" + model.FailureMessage));
                    }

                    if (result.NetworkStatus == MasterStrings.StripeApproved)
                    {
                        await PlaceOrder(model.Basket.Id);

                        return(ControllerHelper.RedirectToLocal(this, "/Checkout/OrderPlaced?id=" + model.Basket.Id));
                    }

                    return(ControllerHelper.RedirectToLocal(this, "/Checkout?id=" + model.Basket.Id + "&&failureMessage=Something went wrong with your payment, please try again."));
                }
                if (!string.IsNullOrWhiteSpace(model.PayPal))
                {
                    // process paypal

                    // create charge
                    var createdPayment = PayPalHelper.CreatePayment(model.Basket.Id, inDb.OrderItems, inDb.OrderTotalPostagePrice, _context);
                    var redirect       = "";

                    inDb.PayPalPaymentId = createdPayment.id;
                    inDb.PaymentId       = createdPayment.transactions[0].invoice_number;

                    _context.Update(inDb);
                    _context.SaveChanges();

                    var links = createdPayment.links.GetEnumerator();
                    while (links.MoveNext())
                    {
                        var link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            // Redirect the customer to link.href
                            redirect = link.href;
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(redirect))
                    {
                        return(Redirect(redirect));
                    }
                }
            }

            return(ControllerHelper.RedirectToLocal(this, string.Format("/Checkout?id={0}&&failureMessage={1}", model.Basket.Id, model.StatusMessage)));
        }
Beispiel #17
0
        public async Task <IActionResult> CompleteReturn(long id, decimal returnAmount)
        {
            var returnItem = _context.Returns.
                             Where(x => x.OrderId == id).
                             Where(x => x.ReturnCompleteDate == null).
                             SingleOrDefault();
            var          order          = _context.Orders.Where(x => x.Id == returnItem.OrderId).SingleOrDefault();
            UpdateResult result         = UpdateResult.Error;
            string       failureMessage = null;
            string       successMessage = null;

            int amount = Convert.ToInt32(returnAmount * 100);

            if (!string.IsNullOrWhiteSpace(order.StripeSource) && amount > 0)
            {
                var stripeResult = StripeHelper.RefundCharge(order.PaymentId, amount);

                returnItem.RefundStatus      = stripeResult.Status;
                returnItem.RefundCreatedDate = stripeResult.Created;

                if (stripeResult.Status == MasterStrings.StripeResultSucceeded || stripeResult.Status == MasterStrings.StripeResultPending)
                {
                    returnItem.RefundId = stripeResult.BalanceTransactionId;
                    result = UpdateResult.Success;
                }

                if (stripeResult.Status == MasterStrings.StripeResultFailed || stripeResult.Status == MasterStrings.StripeResultCancelled)
                {
                    returnItem.RefundId      = stripeResult.FailureBalanceTransactionId;
                    returnItem.RefundMessage = stripeResult.FailureReason;

                    failureMessage = "Refund failed: " + stripeResult.FailureReason;

                    result = UpdateResult.Error;
                }
            }
            else if (!string.IsNullOrWhiteSpace(order.PayPalSaleId) && amount > 0)
            {
                var payPalResult = PayPalHelper.RefundPayment(order.PayPalSaleId, amount);

                order.RefundStatus      = payPalResult.state;
                order.RefundCreatedDate = Convert.ToDateTime(payPalResult.create_time);
                order.RefundId          = payPalResult.id;
                order.RefundMessage     = payPalResult.reason_code;

                if (payPalResult.state == MasterStrings.PayPalResultCompleted || payPalResult.state == MasterStrings.PayPalResultPending)
                {
                    result = UpdateResult.Success;
                }

                if (payPalResult.state == MasterStrings.PayPalResultFailed || payPalResult.state == MasterStrings.PayPalResultCancelled)
                {
                    failureMessage = "Refund failed";
                    result         = UpdateResult.Error;
                }
            }
            else if (amount == 0)
            {
                result = UpdateResult.Success;
            }
            else
            {
                failureMessage = "Refund couldn't be completed.  Please complete this via payment handler.";
            }

            if (result == UpdateResult.Success)
            {
                returnItem.ReturnCompleteDate = DateTime.Now;
                await UpdateOrder(order.Id, MasterStrings.OrderReturned);

                successMessage = "Order updated.";
            }

            _context.Update(returnItem);
            _context.SaveChanges();


            var redirectUrl = string.Format("/ManageOrders/ViewOrder?id={0}", id);

            if (string.IsNullOrWhiteSpace(failureMessage))
            {
                redirectUrl += string.Format("&&failureMessage={0}", failureMessage);
            }
            if (string.IsNullOrWhiteSpace(successMessage))
            {
                redirectUrl += string.Format("&&successMessage={0}", successMessage);
            }

            return(ControllerHelper.RedirectToLocal(this, redirectUrl));
        }
Beispiel #18
0
        public static string SubscribePlan(String CustomerId, String CardId)
        {
            int    plan;
            String msg = "";

            try
            {
                Int32    UserId    = SessionData.UserID;
                DateTime Trialdate = SessionData.TrialEndOn;

                if (!String.IsNullOrWhiteSpace(CardId))
                {
                    var profile = APIData.GetUserProfileForSkuData(UserId);
                    if (profile.Rows.Count > 0)
                    {
                        DataRow  dr            = profile.Rows[0];
                        String   ProfileId     = Convert.ToString(dr["ProfileId"]);
                        DateTime LastUpdatedOn = Convert.ToDateTime(dr["AccessTokenUpdatedOn"]);

                        var Auth = new AuthorizationModel()
                        {
                            access_token  = Convert.ToString(dr["AccessToken"]),
                            refresh_token = Convert.ToString(dr["RefreshToken"]),
                            token_type    = Convert.ToString(dr["TokenType"]),
                            expires_in    = Convert.ToInt32(dr["TokenExpiresIn"])
                        };
                        var reportApi = new ReportsAPI();
                        var skuCount  = AccountData.UserSkuCount(UserId);

                        if (String.IsNullOrWhiteSpace(msg))
                        {
                            var subsPlan = new StripeSubscription();
                            if (skuCount > 250)
                            {
                                plan = GetCustomPlan(skuCount);
                            }
                            else
                            {
                                plan = GetPlanBySku(skuCount);
                            }
                            var subService = StripeHelper.GetSubscription(CustomerId);
                            if (subService != null)
                            {
                                subsPlan = StripeHelper.UpdateSubscription(CustomerId, subService.Id, new Stripe.StripeSubscriptionUpdateOptions {
                                    PlanId = plan.ToString(), Prorate = false
                                }, out msg);
                            }
                            else
                            {
                                subsPlan = StripeHelper.Subscription(CustomerId, new Stripe.StripeSubscriptionCreateOptions {
                                    PlanId = plan.ToString()
                                }, out msg);
                            }

                            if (String.IsNullOrWhiteSpace(msg))
                            {
                                UpdateUserInfo userInfo = new UpdateUserInfo
                                {
                                    Amount        = ((double)(subsPlan.StripePlan.Amount) / 100).ToString(),
                                    CardId        = CardId,
                                    CustId        = CustomerId,
                                    UserId        = UserId,
                                    PlanId        = plan,
                                    EndedAt       = subsPlan.CurrentPeriodEnd.ToString(),
                                    PlanStartDate = subsPlan.CurrentPeriodStart.ToString(),
                                    PlanEndDate   = subsPlan.CurrentPeriodEnd.ToString(),
                                    TrialEndDate  = Trialdate.ToString()
                                };
                                msg = AccountData.UpdateStripeData(userInfo);
                                if (msg == "")
                                {
                                    SessionData.PlanID = plan;
                                }
                            }
                            else
                            {
                                LogAPI.WriteLog("SubscribePlan - " + msg, SessionData.SellerName);
                            }
                        }
                    }
                    else
                    {
                        msg = Constant.PROFILE_NOTFOUND;
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                LogFile.WriteLog("SubscribePlan - " + msg, SessionData.SellerName);
            }
            return(msg);
        }
Beispiel #19
0
        public AdminController(UserAccountService <ApplicationUser> userAccountService, StripeHelper stripeHelper)
        {
            if (userAccountService == null)
            {
                throw new ArgumentNullException(nameof(userAccountService));
            }
            _userAccountService = userAccountService;

            _stripeHelper = stripeHelper;
        }
Beispiel #20
0
        public HttpStatusCode WebHook()
        {
            try
            {
                var    paymentAlertStatus = 0;
                string secret             = MppUtility.ReadConfig("MS_WebHookReceiverSecret_Custom");
                var    postdata           = new StreamReader(HttpContext.Request.InputStream).ReadToEnd();
                var    emailboday         = "";
                var    signature          = Request.Headers["Stripe-Signature"];
                var    stripeEvent        = StripeEventUtility.ConstructEvent(postdata, signature, secret);
                var    eventid            = stripeEvent.Id;
                var    eventdata          = StripeHelper.GetStripeEvent(eventid);
                var    data   = JObject.Parse(postdata);
                var    custid = data["data"].First().First["customer"].ToString();
                var    msg    = "";

                if (eventdata != null && (eventdata.Type == "invoice.payment_succeeded" || eventdata.Type == "invoice.payment_failed"))
                {
                    String coupon_id    = null;
                    var    list         = data["data"].First().First["lines"];
                    var    Amount       = ((double)list["data"].First["amount"]) / 100;
                    var    Amount_off   = ((double)data["data"].First().First["amount_due"]) / 100;
                    var    Discount     = data["data"].First().First["discount"];
                    var    start        = (double)list["data"].First["period"]["start"];
                    var    end          = (double)list["data"].First["period"]["end"];
                    var    startperiod  = MppUtility.UnixTimeStampToDateTime(start);
                    var    endperiod    = MppUtility.UnixTimeStampToDateTime(end);
                    var    discount     = Math.Round(Amount - Amount_off, 2, MidpointRounding.AwayFromZero);
                    var    customerdata = StripeHelper.GetStripeCustomer(custid);
                    var    email        = customerdata.Email;
                    var    last4        = "";
                    var    carddetails  = StripeHelper.GetCard(custid);
                    foreach (var card in carddetails)
                    {
                        last4 = card.Last4;
                    }

                    if (Discount.Count() > 0)
                    {
                        coupon_id = Discount["coupon"]["id"].ToString();
                    }

                    switch (eventdata.Type)
                    {
                    case "invoice.payment_succeeded":
                        msg                = AccountData.UpdatePaymentStatus(custid, Amount, Amount_off, coupon_id, discount, startperiod, endperiod, 1);
                        emailboday         = "A payment of $" + Amount_off + " was made using your card on file ending with <b> " + last4 + " </b>";
                        paymentAlertStatus = 1;
                        break;

                    case "invoice.payment_failed":
                        msg = AccountData.UpdatePaymentStatus(custid, Amount, Amount_off, coupon_id, discount, startperiod, endperiod, 0);
                        upData.UpdatePlanData(custid, 0);
                        StripeHelper.UnSubscribe(custid);
                        emailboday         = @"A payment $" + Amount_off + " failed from your card ending with <b> " + last4 + " </b>" + "Please check your card details or add new card.";
                        paymentAlertStatus = 2;
                        break;
                    }
                    if (msg == "" && Amount_off != 0)
                    {
                        var respo = EmailAlert.PaymentAlertMail(email, emailboday);
                        if (respo == "success")
                        {
                            sellerData.UpdatePaymentAlert(paymentAlertStatus, custid);
                        }
                    }
                }
                else if (stripeEvent.Type == "charge.failed")
                {
                    var Amount          = ((double)data["data"].First().First["amount"]) / 100;
                    var failure_message = data["data"].First().First["failure_message"].ToString();
                    // msg = AccountData.UpdatePaymentStatus(custid, Amount, Amount, 0, 0.00, startperiod, endperiod, 0);
                    if (Amount > 1)//Card verification charge
                    {
                        upData.UpdatePlanData(custid, 0);
                        StripeHelper.UnSubscribe(custid);
                    }
                    var last4        = "";
                    var carddetails  = StripeHelper.GetCard(custid);
                    var customerdata = StripeHelper.GetStripeCustomer(custid);
                    var email        = customerdata.Email;
                    foreach (var card in carddetails)
                    {
                        last4 = card.Last4;
                    }
                    emailboday = @"A payment $" + Amount + " failed from your card ending with <b> " + last4 + " </b>" + "Please check your card details or add new card.</b>Possible reason:" + failure_message;
                    var respo = EmailAlert.PaymentAlertMail(email, emailboday);
                    if (respo == "success" && Amount > 1)
                    {
                        sellerData.UpdatePaymentAlert(2, custid);
                    }
                }
            }
            catch (Exception ex)
            {
                String msg = ex.Message;
                LogFile.WriteLog(msg);
            }
            return(HttpStatusCode.OK);
        }
        //[ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel model, String returnUrl)
        {
            String    msg    = "";
            Int32     UserID = 0;
            DataSet   ds;
            DataTable dt, dtbl;
            DataRow   dr = null, dr1 = null;

            if (ModelState.IsValid)
            {
                String email = model.Email.Trim();
                ds = userregistrationData.ValidateEmailAndGetUserinfo(email);

                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    dt     = ds.Tables[0];
                    dr     = dt.Rows[0];
                    UserID = Convert.ToInt32(dr["MppUserID"]);
                    msg    = userregistrationData.CheckUserLogin(UserID, model.Password);

                    if (msg == "")
                    {
                        dtbl = ds.Tables[1];
                        dr1  = dtbl.Rows[0];
                        String CustmId, CardId;

                        SessionData.UserID = UserID;

                        String FirstName = Convert.ToString(dr["FirstName"]);
                        SessionData.LastName = Convert.ToString(dr["LastName"]);
                        String   PlanDate = Convert.ToString(dr1["PlanDate"]);
                        DateTime?Today, NextPlanDate = DateTime.MaxValue;
                        Today = DateTime.Now;

                        DateTime StartDate = Convert.ToDateTime(dr["StartDate"]);

                        if (!String.IsNullOrWhiteSpace(PlanDate))
                        {
                            NextPlanDate = Convert.ToDateTime(PlanDate);
                        }

                        SessionData.StartDate         = StartDate.ToString("yyyy/MM/dd hh:mm:ss tt");
                        SessionData.PlanStatus        = Convert.ToInt32(dr["PlanStatus"]);
                        SessionData.PlanID            = Convert.ToInt32(dr["PlanID"]);
                        SessionData.FormulaAccess     = Convert.ToInt16(dr["IsSetFormula"]);
                        SessionData.TrialEndOn        = Convert.ToDateTime(dr["TrailEndDate"]);
                        SessionData.Email             = email;
                        SessionData.IsAgreementAccept = Convert.ToInt16(dr["IsAgreementConfirm"]);
                        SessionData.ProfileAccess     = Convert.ToInt16(dr["ProfileAccess"]);
                        SessionData.AlertCount        = Convert.ToInt32(dr1["total_alerts"]);
                        CustmId = Convert.ToString(dr["stp_custId"]);
                        CardId  = Convert.ToString(dr["stp_cardId"]);

                        if (!String.IsNullOrWhiteSpace(CustmId))
                        {
                            FormsAuthentication.SetAuthCookie(FirstName, false);
                            var custm = StripeHelper.GetStripeCustomer(CustmId);
                            if (!String.IsNullOrWhiteSpace(custm.DefaultSourceId) && String.IsNullOrWhiteSpace(CardId))
                            {
                                StripeHelper.DeleteCard(custm.DefaultSourceId, CustmId);
                            }
                            SessionData.StripeCardId = CardId;
                            SessionData.StripeCustId = CustmId;

                            if (((SessionData.PlanID == 1 && SessionData.TrialEndOn < Today && !String.IsNullOrWhiteSpace(CardId)) || NextPlanDate < Today) && SessionData.PlanStatus == 1) // When plan was expired
                            {
                                if (String.IsNullOrWhiteSpace(CardId))
                                {
                                    return(RedirectToAction("Plan", "Settings"));
                                }
                                else
                                {
                                    msg = StripeServices.SubscribePlan(CustmId, CardId);
                                }
                                if (!String.IsNullOrWhiteSpace(msg))
                                {
                                    TempData["IsValid"] = msg;
                                    return(RedirectToAction("Login", "UserAccount"));
                                }
                            }

                            if (SessionData.PlanID != 1)
                            {
                                if (SessionData.PlanStatus == 0) // handles unsubscribed status after trial period
                                {
                                    return(RedirectToAction("Plan", "Settings"));
                                }
                                else if (String.IsNullOrWhiteSpace(CardId) && SessionData.PlanStatus == 1) // When CardId was not found and Plan was not trail
                                {
                                    return(RedirectToAction("Cards", "Settings"));
                                }
                            }
                        }
                        else
                        {
                            return(View("Error"));
                        }

                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return(Redirect(returnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("Dashboard", "Main"));
                        }
                    }
                }
                else
                {
                    msg = "Invalid login attempt!";
                }

                TempData["IsValid"] = msg;
                return(RedirectToAction("Login", "UserAccount"));
            }
            return(View(model));
        }