public ActionResult PaywallRefundOrder(DisplayInvoice invoice)
        {
            try
            {
                bool isSuccess = false;
                var sg = new Paywall();
                PaymentGateway pg = new PaymentGateway();
                var f = pg.StartInvoiceWizard().Initalize(invoice.Merchant.MerchantId, "USD", invoice.PaymentProvider, PaymentMode.Live, ChargeTypeEnum.Refund_Paywall)
                    .SetInvoiceId(invoice.InvoiceId)
                .SetRefundAmount(invoice.RefundAmount)
                .SetNotes(null, invoice.AdminNote);

                var response = f.FinalizeInvoice();
                if (response.Status == InvoiceStatus.Refunded)
                    isSuccess = true;

                if (isSuccess)
                    return Redirect(Url.Content("~/paywall/order/" + invoice.Merchant.PrivateManagerId.ToString().Replace("-", "") + "/" + invoice.Merchant.MerchantId.ToString().Replace("-", "") + "/" + invoice.InvoiceId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.ro));
                else
                    return Redirect(Url.Content("~/paywall/order/" + invoice.Merchant.PrivateManagerId.ToString().Replace("-", "") + "/" + invoice.Merchant.MerchantId.ToString().Replace("-", "") + "/" + invoice.InvoiceId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.sww));
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
        }
 public static DuesReceipt GetReceiptForDues(Guid invoiceId)
 {
     DuesReceipt re = new DuesReceipt();
     try
     {
         PaymentGateway pg = new PaymentGateway();
         var invoice = pg.GetDisplayInvoice(invoiceId);
         var duesItem = invoice.DuesItems.FirstOrDefault();
         var mem = MemberCache.GetMemberDisplay(duesItem.MemberPaidId);
         re.InvoiceId = invoice.InvoiceId;
         var league = MemberCache.GetLeagueOfMember(duesItem.MemberPaidId);
         re.LeagueId = league.LeagueId;
         re.LeagueName = league.Name;
         re.BasePrice = duesItem.BasePrice;
         re.PriceAfterFees = duesItem.PriceAfterFees;
         re.Fees = duesItem.ProcessorFees;
         re.PaidDuesForMonth = duesItem.PaidForDate;
         re.MemberPaid = mem.DerbyName;
         re.EmailForReceipt = mem.Email;
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return re;
 }
 public static LeagueBilling GetCurrentBillingStatus(Guid leagueId)
 {
     LeagueBilling bi = new LeagueBilling();
     try
     {
         var dc = new ManagementContext();
         PaymentGateway pg = new PaymentGateway();
         var invoice = pg.GetLatestInvoiceSubscriptionForLeagueId(leagueId);
         
         bi.LeagueId = leagueId;
         bi.LeagueName = dc.Leagues.Where(x => x.LeagueId == leagueId).Select(x => x.Name).FirstOrDefault();
         if (invoice != null)
         {
             bi.InvoiceId = invoice.InvoiceId;
             bi.Expires = invoice.Subscription.ValidUntil;
             bi.LastBilledOn = invoice.Subscription.Created;
             bi.MembershipStatus = CurrentStatusOfBillingEnum.League_Membership;
             bi.PaymentProviderCustomerId = invoice.PaymentProviderCustomerId;
         }
         else
         {
             bi.MembershipStatus = CurrentStatusOfBillingEnum.None;
         }
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return bi;
 }
 public static LeagueBillingHistory GetReceiptsForLeague(Guid leagueId)
 {
     LeagueBillingHistory history = new LeagueBillingHistory();
     history.LeagueId = leagueId;
     var league = League.LeagueFactory.GetLeague(leagueId);
     history.LeagueName = league.Name;
     try
     {
         PaymentGateway pg = new PaymentGateway();
         var invoices = pg.GetAllInvoiceSubscriptionsForLeague(leagueId);
         foreach (var invoice in invoices)
         {
             LeagueReceipt re = new LeagueReceipt();
             re.InvoiceId = invoice.InvoiceId;
             re.LeagueId = invoice.Subscription.InternalObject;
             re.Expires = invoice.Subscription.ValidUntil;
             re.AmountPaid = invoice.Subscription.Price;
             re.EmailForReceipt = league.Email;
             re.Status = invoice.InvoiceStatus;
             history.Receipts.Add(re);
         }
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return history;
 }
 public static PaywallReceipt GetReceiptForInvoice(Guid invoiceId)
 {
     PaywallReceipt re = new PaywallReceipt();
     try
     {
         PaymentGateway pg = new PaymentGateway();
         var invoice = pg.GetDisplayInvoice(invoiceId);
         re.InvoiceStatus = invoice.InvoiceStatus;
         re.InvoiceId = invoice.InvoiceId;
         re.NameOfPayment = invoice.Paywall.Name;
         re.DescriptionOfPayment = invoice.Paywall.Description;
         re.EmailForReceipt = invoice.InvoiceBilling.Email;
         re.PaywallId = invoice.Paywall.PaywallId;
         re.Expires = invoice.Paywall.ValidUntil;
         re.GeneratedPassword = invoice.Paywall.PaywallPassword;
         re.AmountPaid = invoice.Paywall.Price;
         re.AmountRefunded = invoice.Refunds.Sum(x => x.RefundAmount);
         re.MerchantId= invoice.Merchant.MerchantId;
         re.Location = invoice.Paywall.PaywallLocation;
                     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return re;
 }
 public static LeagueReceipt GetReceiptForInvoice(Guid invoiceId)
 {
     LeagueReceipt re = new LeagueReceipt();
     try
     {
         PaymentGateway pg = new PaymentGateway();
         var invoice = pg.GetDisplayInvoice(invoiceId);
         re.InvoiceId = invoice.InvoiceId;
         re.LeagueId = invoice.Subscription.InternalObject;
         var league = League.LeagueFactory.GetLeague(re.LeagueId);
         re.LeagueName = league.Name;
         re.Expires = invoice.Subscription.ValidUntil;
         re.MembershipStatus = CurrentStatusOfBillingEnum.League_Membership;
         re.AmountPaid = invoice.Subscription.Price;
         re.EmailForReceipt = league.Email;
         re.Status = invoice.InvoiceStatus;
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return re;
 }
 public JsonResult MoveInvoiceToNextStatus(string invoiceId, string status)
 {
     try
     {
         status = status.Replace("Move To", "").Trim();
         PaymentGateway pg = new PaymentGateway();
         string s = status.Replace(" ", "_");
         InvoiceStatus st = (InvoiceStatus)Enum.Parse(typeof(InvoiceStatus), s);
         pg.SetInvoiceStatus(new Guid(invoiceId), st);
         if (st == InvoiceStatus.Shipped)
         {
             var voice = pg.GetDisplayInvoice(new Guid(invoiceId));
             StoreGateway sg = new StoreGateway();
             sg.CompileAndSendShippedEmailsForStore(voice);
         }
         return Json(new { isSuccess = true, status = st.ToString() }, JsonRequestBehavior.AllowGet);
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return Json(new { isSuccess = false }, JsonRequestBehavior.AllowGet);
 }
        private void HandleStripePayments(CreateInvoiceReturn output)
        {
            if (invoice.ChargeType == ChargeTypeEnum.Refund_Paywall)
            {
                invoice.InvoiceStatus = InvoiceStatus.Refund_Started;

                // Create the Stripe Request and get the data back.
                var response = PerformStripeRefund();
                // If it was successful we will now have a redirect link
                if (response != null)
                {
                    // Try to save the data to our database
                    if (response.AmountInCentsRefunded.HasValue && response.AmountInCentsRefunded.Value > 0)
                    {
                        PaymentGateway pg = new PaymentGateway();
                        var voice = pg.GetDisplayInvoice(invoice.InvoiceId);
                        if (voice.Refunds.Sum(x => x.RefundAmount) + invoice.FinancialData.RefundAmount == voice.TotalIncludingTax)
                            pg.UpdateInvoiceForRefund(invoice.InvoiceId, InvoiceStatus.Refunded, invoice.FinancialData.RefundAmount, invoice.AdminNote);
                        else
                            pg.UpdateInvoiceForRefund(invoice.InvoiceId, InvoiceStatus.Partially_Refunded, invoice.FinancialData.RefundAmount, invoice.AdminNote);

                        voice.RefundAmount = invoice.FinancialData.RefundAmount;
                        Paywall.Paywall pw = new Paywall.Paywall();
                        pw.HandlePaywallRefund(voice);
                        output.Status = InvoiceStatus.Refunded;
                    }
                    else
                    {
                        // Could not save to our database
                        output.Error = "Failed to save to RDN database";
                        output.Status = InvoiceStatus.Failed;
                    }
                }
                else
                    output.Status = InvoiceStatus.Failed;
            }
            else if (invoice.ChargeType == ChargeTypeEnum.Subscription)
            {
                CompleteNewStripeSubscription(output);
            }
            else if (invoice.ChargeType == ChargeTypeEnum.Paywall)
            {
                CalculateRDNationFeesForPaywallPurchasesStripe();
                // Create the Stripe Request and get the data back.
                var response = PerformStripePaywallPurchaseCheckout();
                // If it was successful we will now have a redirect link
                if (response != null)
                {
                    // Try to save the data to our database
                    var result = AddInvoiceToDatabase();

                    if (result)
                    {
                        output.InvoiceId = invoice.InvoiceId;
                        output.Status = InvoiceStatus.Payment_Successful;

                        PaymentGateway pg = new PaymentGateway();
                        var voice = pg.GetDisplayInvoice(invoice.InvoiceId);
                        Paywall.Paywall pw = new Paywall.Paywall();
                        pw.HandlePaywallPayments(voice);
                    }
                    else
                    {
                        // Could not save to our database
                        output.Error = "Failed to save to RDN database";
                        output.Status = InvoiceStatus.Failed;
                    }
                }
                else
                    output.Status = InvoiceStatus.Failed;
            }
            else if (invoice.ChargeType == ChargeTypeEnum.Cancel_Subscription)
            {
                CancelStripeSubscription(output);
            }
            else if (invoice.ChargeType == ChargeTypeEnum.SubscriptionUpdated)
            {
                CompleteStripeSubscriptionUpdated(output);
            }
            else if (invoice.ChargeType == ChargeTypeEnum.InStorePurchase)
            {
                CalculateRDNationFeesForInStorePurchasesStripe();
                // Create the Stripe Request and get the data back.
                var response = PerformStripeInStorePurchaseCheckout();
                // If it was successful we will now have a redirect link
                if (response != null)
                {
                    // Try to save the data to our database
                    var result = AddInvoiceToDatabase();

                    if (result)
                    {
                        output.InvoiceId = invoice.InvoiceId;
                        output.Status = InvoiceStatus.Payment_Successful;

                        PaymentGateway pg = new PaymentGateway();
                        var voice = pg.GetDisplayInvoice(invoice.InvoiceId);
                        Store.StoreGateway sg = new Store.StoreGateway();
                        sg.HandleStoreItemPayments(voice);
                    }
                    else
                    {
                        // Could not save to our database
                        output.Error = "Failed to save to RDN database";
                        output.Status = InvoiceStatus.Failed;
                    }
                }
                else
                {
                    // Could not create a google link
                    //output.Error = response.Error;
                    output.Status = InvoiceStatus.Failed;
                }
            }
            else if (invoice.ChargeType == ChargeTypeEnum.Stripe_Checkout)
            {

                // Create the Stripe Request and get the data back.
                var response = ChargeStripeCheckoutPayment();
                // If it was successful we will now have a redirect link
                if (response != null)
                {
                    // Try to save the data to our database
                    var result = AddInvoiceToDatabase();

                    if (result)
                    {
                        output.InvoiceId = invoice.InvoiceId;
                        output.Status = InvoiceStatus.Payment_Successful;

                        var emailData = new Dictionary<string, string>
                                        {
                                            { "Why: ", invoice.Note }, 
                                            { "invoiceId",invoice.InvoiceId.ToString().Replace("-","") },
                                            { "Paid",invoice.FinancialData.TotalIncludingTax.ToString("N2")}
                                        };
                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, EmailServer.EmailServer.DEFAULT_SUBJECT + " Receipt For League Subscription", emailData, EmailServer.EmailServerLayoutsEnum.Default);
                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_KRIS_WORLIDGE_EMAIL_ADMIN, EmailServer.EmailServer.DEFAULT_SUBJECT + " New Payment Made", emailData, EmailServer.EmailServerLayoutsEnum.Default);

                    }
                    else
                    {
                        // Could not save to our database
                        output.Error = "Failed to save to RDN database";
                        output.Status = InvoiceStatus.Failed;
                    }
                }
                else
                {
                    // Could not create a google link
                    //output.Error = response.Error;
                    output.Status = InvoiceStatus.Failed;
                }
            }
        }
        public void CheckOut(CheckOut model)
        {
            var shoppingCartId = GetShoppingCartId();
            if (!shoppingCartId.HasValue)
            {
                Response.Redirect(Url.Action("ViewRDNStore"));
                return;
            }

            var sg = new StoreGateway();
            var checkout = sg.GetCheckoutData(shoppingCartId.Value, new Guid());
            if (checkout == null || checkout.ShoppingCart.ItemsCount == 0)
            {
                Response.Redirect(Url.Action("ViewRDNStore"));
                return;
            }

            PaymentProvider paymentProvider;
            if (!Enum.TryParse(model.PaymentProviderId, out paymentProvider))
            {
                Response.Redirect(Url.Action("ViewRDNStore"));
                return;
            }
            int shippingId;
            if (!Int32.TryParse(model.ShippingOptionSelectedId, out shippingId))
            {
                Response.Redirect(Url.Action("ViewRDNStore"));
                return;
            }

            var pg = new PaymentGateway();

            var invoice = pg.StartInvoiceWizard()
                .Initalize(checkout.MerchantId, checkout.Currency, paymentProvider, PaymentMode.Live, ChargeTypeEnum.InvoiceItem)
                .SetShipping(checkout.TotalShipping, ShippingType.Postal)
                .SetInvoiceId(checkout.ShoppingCart.ShoppingCartId);

            var billingInfo = new InvoiceContactInfo();
            billingInfo.City = model.BillingAddress.City;
            billingInfo.CompanyName = model.BillingAddress.CompanyName;
            billingInfo.Country = model.BillingAddress.Country;
            billingInfo.Email = model.BillingAddress.Email;
            billingInfo.Fax = model.BillingAddress.Fax;
            billingInfo.FirstName = model.BillingAddress.FirstName;
            billingInfo.LastName = model.BillingAddress.LastName;
            billingInfo.Phone = model.BillingAddress.Phone;
            billingInfo.State = model.BillingAddress.State;
            billingInfo.Street = model.BillingAddress.Street;
            billingInfo.Street2 = model.BillingAddress.Street2;
            billingInfo.Zip = model.BillingAddress.Zip;

            var shippingInfo = new InvoiceContactInfo();
            shippingInfo.City = model.ShippingAddress.City;
            shippingInfo.CompanyName = model.ShippingAddress.CompanyName;
            shippingInfo.Country = model.ShippingAddress.Country;
            shippingInfo.Email = model.ShippingAddress.Email;
            shippingInfo.Fax = model.ShippingAddress.Fax;
            shippingInfo.FirstName = model.ShippingAddress.FirstName;
            shippingInfo.LastName = model.ShippingAddress.LastName;
            shippingInfo.Phone = model.ShippingAddress.Phone;
            shippingInfo.State = model.ShippingAddress.State;
            shippingInfo.Street = model.ShippingAddress.Street;
            shippingInfo.Street2 = model.ShippingAddress.Street2;
            shippingInfo.Zip = model.ShippingAddress.Zip;
            invoice.SetInvoiceContactData(billingInfo, shippingInfo);

            //foreach (var cartitem in checkout.ShoppingCart.Items)
            //{
            //    var item = new InvoiceItem();
            //    item.ArticleNumber = cartitem.ArticleNumber;
            //    item.Article2Number = cartitem.Article2Number;
            //    item.Description = cartitem.Description;
            //    item.Name = cartitem.Name;
            //    item.BasePrice = cartitem.BasePrice;
            //    item.Price = cartitem.Price;
            //    item.Quantity = cartitem.QuantityOrdered;
            //    item.Weight = cartitem.Weight;
            //    invoice.AddItem(item);
            //}

            invoice.SetTax(checkout.TaxRate);

            var requestResponse = invoice.FinalizeInvoice();
            if (requestResponse.Error != null)
                throw new Exception(requestResponse.Error);

            Response.Redirect(requestResponse.RedirectLink);
        }
        public ActionResult PayDuesOnlinePayPal()
        {
            try
            {
                if (HttpContext.Request.InputStream != null)
                {
                    Stream stream = HttpContext.Request.InputStream;
                    var ob = Network.LoadObject<DuesSendParams>(ref stream);
                    var mem = MemberCache.GetMemberDisplay(ob.CurrentMemberId);
                    if (ob.UserId == mem.UserId)
                    {
                        var dues2 = DuesFactory.GetDuesCollectionItem(ob.DuesItemId, ob.DuesId, ob.CurrentMemberId);
                        if (dues2 != null)
                        {
                            PaymentGateway pg = new PaymentGateway();

                            var f = pg.StartInvoiceWizard()
                                .Initalize(ServerConfig.RDNATION_STORE_ID, dues2.Currency, PaymentProvider.Paypal, SiteSingleton.Instance.IsPayPalLive, ChargeTypeEnum.DuesItem)
                                .SetInvoiceId(Guid.NewGuid())
                                .AddDuesItem(new Library.Classes.Payment.Classes.Invoice.InvoiceDuesItem
                                {
                                    BasePrice = (decimal)dues2.DuesFees.FirstOrDefault().TotalPaymentNeededFromMember,
                                    WhoPaysFees = dues2.WhoPaysProcessorFeesEnum,
                                    DuesId = dues2.DuesId,
                                    DuesItemId = dues2.DuesFees.FirstOrDefault().DuesItemId,
                                    MemberPaidId = ob.CurrentMemberId,
                                    Name = "Dues For " + dues2.DuesFees.FirstOrDefault().PayBy.ToString("yyyy/MM/dd"),
                                    PaidForDate = dues2.DuesFees.FirstOrDefault().PayBy,
                                    Description = "Dues Payment",
                                })
                                .SetInvoiceContactData(new Library.Classes.Payment.Classes.Invoice.InvoiceContactInfo
                                {
                                    Email = mem.Email,
                                    FirstName = mem.Firstname,
                                    LastName = mem.LastName,
                                    Phone = mem.PhoneNumber,
                                })
                                                    .FinalizeInvoice();

                            //if (f.Status == InvoiceStatus.Paypal_Email_Not_Confirmed)
                            //    return Redirect(Url.Content("~/dues/member/" + duesModel.LeagueOwnerId.ToString().Replace("-", "") + "/" + memberId.ToString().Replace("-", "")) + "?u=" + SiteMessagesEnum.ppldnc.ToString());
                            //else if (f.Status != InvoiceStatus.Failed)
                            //    return Redirect(f.RedirectLink);
                            return Json(f, JsonRequestBehavior.AllowGet);
                        }

                    }
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, GetType());
            }
            return Json(new CreateInvoiceReturn() { Status = InvoiceStatus.Failed });
        }
 public void HandleStoreItemPaymentPending(DisplayInvoice invoice, string additionalReportingInformation = null)
 {
     try
     {
         var items = invoice.InvoiceItems;
         PaymentGateway pg = new PaymentGateway();
         //change invoice to ready to be shipped
         pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Awaiting_Payment);
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: additionalReportingInformation);
     }
 }
        public ActionResult PayDuesOnlinePayPal(DuesPortableModel duesModel)
        {
            try
            {
                if (!String.IsNullOrEmpty(Request.Form["DuesItemId"]))
                {
                    Guid memberId = RDN.Library.Classes.Account.User.GetMemberId();
                    var mem = MemberCache.GetMemberDisplay(memberId);
                    var dues2 = DuesFactory.GetDuesCollectionItem(Convert.ToInt64(Request.Form["DuesItemId"]), duesModel.DuesId, memberId);
                    if (dues2 != null)
                    {
                        PaymentGateway pg = new PaymentGateway();

                        var f = pg.StartInvoiceWizard()
                            .Initalize(ServerConfig.RDNATION_STORE_ID, dues2.Currency, PaymentProvider.Paypal, SiteSingleton.Instance.IsPayPalLive, ChargeTypeEnum.DuesItem)
                            .SetInvoiceId(Guid.NewGuid())
                            .AddDuesItem(new Library.Classes.Payment.Classes.Invoice.InvoiceDuesItem
                            {
                                BasePrice = (decimal)dues2.DuesFees.FirstOrDefault().TotalPaymentNeededFromMember,
                                WhoPaysFees = dues2.WhoPaysProcessorFeesEnum,
                                DuesId = dues2.DuesId,
                                DuesItemId = dues2.DuesFees.FirstOrDefault().DuesItemId,
                                MemberPaidId = memberId,
                                Name = "Dues For " + dues2.DuesFees.FirstOrDefault().PayBy.ToString("yyyy/MM/dd"),
                                PaidForDate = dues2.DuesFees.FirstOrDefault().PayBy,
                                Description = "Dues Payment",
                            })
                            .SetInvoiceContactData(new Library.Classes.Payment.Classes.Invoice.InvoiceContactInfo
                            {
                                Email = mem.Email,
                                FirstName = mem.Firstname,
                                LastName = mem.LastName,
                                Phone = mem.PhoneNumber,
                            })
                                                .FinalizeInvoice();
                        if (f.Status == InvoiceStatus.Paypal_Email_Not_Confirmed)
                            return Redirect(Url.Content("~/dues/member/" + duesModel.LeagueOwnerId.ToString().Replace("-", "") + "/" + memberId.ToString().Replace("-", "")) + "?u=" + SiteMessagesEnum.ppldnc.ToString());
                        else if (f.Status != InvoiceStatus.Failed)
                            return Redirect(f.RedirectLink);
                    }
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, GetType());
            }
            return Redirect(Url.Content("~/dues/league/" + duesModel.LeagueOwnerId.ToString().Replace("-", "")) + "?u=" + SiteMessagesEnum.sww.ToString());
        }
        public void HandleStoreItemPayments(DisplayInvoice invoice, string additionalReportingInformation = null, string customerId = null)
        {
            try
            {
                var items = invoice.InvoiceItems;

                PaymentGateway pg = new PaymentGateway();
                //change invoice to ready to be shipped
                pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Awaiting_Shipping, customerId);

                CompileAndSendReceiptsEmailsForStore(invoice);

                //clear item from shooping cart.
                foreach (var item in items)
                {
                    bool isRemoved = RemoveItemFromCart(invoice.ShoppingCartId, item.StoreItemId);
                    bool isSuccess = SubtractNumberOfItemsBeingSoldByMerchant(invoice.Merchant.MerchantId, item.StoreItemId, item.Quantity);
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: additionalReportingInformation);
            }
        }
        public ActionResult CheckOut(RDN.Store.Models.CheckOut model)
        {
            try
            {
                var shoppingCartId = StoreGateway.GetShoppingCartId(HttpContext);
                if (!shoppingCartId.HasValue)
                {

                    return Redirect(Url.Action("StoreCart"));
                }

                var sg = new StoreGateway();
                var checkout = sg.GetCheckoutData(shoppingCartId.Value, model.MerchantId);
                if (checkout == null || checkout.ShoppingCart.ItemsCount == 0)
                {
                    return Redirect(Url.Action("StoreCart"));

                }

                PaymentProvider paymentProvider;
                if (!Enum.TryParse(model.PaymentProviderId, out paymentProvider))
                {
                    return Redirect(Url.Action("StoreCart"));

                }

                var pg = new PaymentGateway();

                ShippingType shipType = ShippingType.Postal;
                if (checkout.WillPickUpAtStore)
                    shipType = ShippingType.PickUp;

                var invoice = pg.StartInvoiceWizard()
                    .Initalize(checkout.MerchantId, checkout.Currency, paymentProvider, PaymentMode.Live, ChargeTypeEnum.InStorePurchase)
                    .SetShipping(checkout.TotalShipping, shipType)
                    .SetInvoiceId(Guid.NewGuid())
                    .SetNotes(model.Notes)
                    .SetUserId(RDN.Library.Classes.Account.User.GetUserId())
                    .SetShoppingCartId(shoppingCartId.Value);


                if (paymentProvider == PaymentProvider.Stripe)
                {
                    string token = Request.Form["stripeToken"].ToString();
                    invoice.SetStripeTokenId(token);
                }
                var sellersAddress = new InvoiceContactInfo();
                if (shipType == ShippingType.PickUp)
                {
                    if (checkout.SellersAddress != null)
                    {
                        sellersAddress.City = checkout.SellersAddress.City;
                        sellersAddress.Country = checkout.SellersAddress.Country;
                        sellersAddress.CompanyName = checkout.SellersAddress.CompanyName;
                        sellersAddress.State = checkout.SellersAddress.State;
                        sellersAddress.Street = checkout.SellersAddress.Street;
                        sellersAddress.Street2 = checkout.SellersAddress.Street2;
                        sellersAddress.Zip = checkout.SellersAddress.Zip;
                        invoice.SetSellersAddress(sellersAddress);
                    }
                }

                var billingInfo = new InvoiceContactInfo();
                billingInfo.City = model.BillingAddress_City;
                billingInfo.Country = model.BillingAddress_Country;
                billingInfo.Email = model.BillingAddress_Email;
                billingInfo.FirstName = model.BillingAddress_FirstName;
                billingInfo.LastName = model.BillingAddress_LastName;
                billingInfo.Phone = model.BillingAddress_Phone;
                billingInfo.State = model.BillingAddress_State;
                billingInfo.Street = model.BillingAddress_Street;
                billingInfo.Street2 = model.BillingAddress_Street2;
                billingInfo.Zip = model.BillingAddress_Zip;
                if (User.Identity.IsAuthenticated)
                    RDN.Library.Classes.Account.User.AddContactToMember(RDN.Library.Classes.Account.User.GetMemberId(), billingInfo, AddressTypeEnum.Billing);
                if (model.IsBillingDifferentFromShipping)
                {
                    var shippingInfo = new InvoiceContactInfo();
                    shippingInfo.City = model.ShippingAddress_City;
                    shippingInfo.Country = model.ShippingAddress_Country;
                    shippingInfo.Email = model.ShippingAddress_Email;
                    shippingInfo.FirstName = model.ShippingAddress_FirstName;
                    shippingInfo.LastName = model.ShippingAddress_LastName;
                    shippingInfo.Phone = model.ShippingAddress_Phone;
                    shippingInfo.State = model.ShippingAddress_State;
                    shippingInfo.Street = model.ShippingAddress_Street;
                    shippingInfo.Street2 = model.ShippingAddress_Street2;
                    shippingInfo.Zip = model.ShippingAddress_Zip;
                    invoice.SetInvoiceContactData(billingInfo, shippingInfo);

                    if (User.Identity.IsAuthenticated)
                        RDN.Library.Classes.Account.User.AddContactToMember(RDN.Library.Classes.Account.User.GetMemberId(), shippingInfo, AddressTypeEnum.Shipping);

                }
                else
                    invoice.SetInvoiceContactData(billingInfo, billingInfo);


                foreach (var cartitem in checkout.ShoppingCart.Stores.FirstOrDefault().StoreItems)
                {
                    var item = new InvoiceItem();
                    item.ArticleNumber = cartitem.ArticleNumber;
                    item.Article2Number = cartitem.Article2Number;
                    item.Description = "Tax Included in Price: " + cartitem.Description;
                    item.Name = cartitem.Name;
                    item.BasePrice = cartitem.BasePrice + cartitem.BaseTaxOnItem;
                    item.Price = cartitem.Price;
                    item.TotalShipping = cartitem.Shipping;
                    item.Quantity = cartitem.QuantityOrdered;
                    item.Weight = cartitem.Weight;
                    item.SizeOfItem = cartitem.ItemSizeEnum;
                    item.ColorOfItem = cartitem.ColorAGB;
                    item.StoreItemId = cartitem.StoreItemId;
                    invoice.AddItemTaxIncluded(item);
                }

                var requestResponse = invoice.FinalizeInvoice();
                if (requestResponse.Error != null)
                    throw new Exception(requestResponse.Error);

                this.ClearCart(HttpContext.Session);

                if (requestResponse.Status == InvoiceStatus.Payment_Successful)
                    return Redirect(Url.Content("~/receipt/" + requestResponse.InvoiceId.ToString().Replace("-", "")));
                else if (requestResponse.Status == InvoiceStatus.Pending_Payment_From_Paypal)
                    return Redirect(requestResponse.RedirectLink);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
        }
        public ActionResult LeagueAddSubscription(AddSubscriptionModel add)
        {
            var memId = RDN.Library.Classes.Account.User.GetMemberId();

            try
            {
                string paymentProvider = Request.Form["PaymentType"].ToString();
                string articleNumberForSubscription = "none";

                PaymentProvider provider = PaymentProvider.None;
                if (paymentProvider == PaymentProvider.Stripe.ToString())
                {
                    provider = PaymentProvider.Stripe;
                    articleNumberForSubscription = Request.Form["stripeToken"].ToString();
                }
                else if (paymentProvider == PaymentProvider.Paypal.ToString())
                {
                    provider = PaymentProvider.Paypal;
                }
                string subType = Request.Form["SubscriptionType"].ToString();
                LeaguePlanTypesEnum sub = (LeaguePlanTypesEnum)Enum.Parse(typeof(LeaguePlanTypesEnum), subType);
                decimal price = 15.99M;
                SubscriptionPeriodStripe subStripe = SubscriptionPeriodStripe.Monthly;
                int lengthOfDays = 31;
                DateTime now = DateTime.UtcNow;
                TimeSpan ts = new TimeSpan();
                if (sub == LeaguePlanTypesEnum.One_Month)
                {
                    price = 15.99M;
                    subStripe = SubscriptionPeriodStripe.Monthly;
                    ts = now.AddMonths(1) - DateTime.UtcNow;
                    lengthOfDays = ts.Days;
                }
                else if (sub == LeaguePlanTypesEnum.Six_Months)
                {
                    price = 71.99M;
                    subStripe = SubscriptionPeriodStripe.Six_Months;
                    ts = now.AddMonths(6) - DateTime.UtcNow;
                    lengthOfDays = ts.Days;
                }
                else if (sub == LeaguePlanTypesEnum.Three_Months)
                {
                    price = 41.99M;
                    subStripe = SubscriptionPeriodStripe.Three_Months;
                    ts = now.AddMonths(3) - DateTime.UtcNow;
                    lengthOfDays = ts.Days;
                }
                else if (sub == LeaguePlanTypesEnum.Twelve_Months)
                {
                    price = 131.99M;
                    subStripe = SubscriptionPeriodStripe.Yearly;
                    ts = now.AddMonths(12) - DateTime.UtcNow;
                    lengthOfDays = ts.Days;
                }


                PaymentGateway pg = new PaymentGateway();
                var f = pg.StartInvoiceWizard().Initalize(ServerConfig.RDNATION_STORE_ID, "USD", provider, SiteSingleton.Instance.IsPayPalLive, ChargeTypeEnum.Subscription)
                    .SetInvoiceId(Guid.NewGuid())
                    .SetSubscription(new InvoiceSubscription
                    {
                        ArticleNumber = articleNumberForSubscription,
                        Description = "RDN League portal subscription",
                        DescriptionRecurring = "Fee for RDN League portal subscription",
                        Name = "RDN Member portal",
                        NameRecurring = "RDN Member portal recurring",
                        DigitalPurchaseText = "You have now access to RDN League portal",
                        Price = price,
                        SubscriptionPeriodStripe = subStripe,
                        SubscriptionPeriodLengthInDays = lengthOfDays,
                        //ValidUntil = subScriptionDate.AddDays(lengthOfDays),
                        //league id is the ownerId
                        InternalObject = add.AddSubscriptionOwnerId
                    })
                    .SetInvoiceContactData(new InvoiceContactInfo
                    {
                        City = add.City,
                        Country = add.Country,
                        Email = add.EmailAddress,
                        FirstName = add.FirstName,
                        LastName = add.LastName,
                        Phone = add.PhoneNumber,
                        State = add.State,
                        Street = add.Address,
                        Zip = add.ZipCode
                    })
                        .FinalizeInvoice();

                //clears the member cache to update all cache repos of the league members.
                MemberCache.ClearLeagueMembersCache(add.AddSubscriptionOwnerId);
                MemberCache.ClearLeagueMembersApiCache(add.AddSubscriptionOwnerId);
                //succesfully charged.
                if (f.Status == InvoiceStatus.Subscription_Running)
                    return Redirect(Url.Content("~/billing/league/receipt/" + f.InvoiceId.ToString().Replace("-", "")));
                else if (f.Status == InvoiceStatus.Pending_Payment_From_Paypal)
                    return Redirect(f.RedirectLink);
                else if (f.Status == InvoiceStatus.Card_Was_Declined)
                {
                    SiteMessage message = new SiteMessage();
                    message.MessageType = SiteMessageType.Error;
                    message.Message = "Your Card has been Declined.  Please check the information and try again.";
                    this.AddMessage(message);
                }


            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            add.AddSubscriptionOwnerId = add.AddSubscriptionOwnerId;
            var league = RDN.Library.Classes.League.LeagueFactory.GetLeague(add.AddSubscriptionOwnerId);
            if (league != null)
                add.AddSubscriptionOwnerName = league.Name;
            Dictionary<int, string> countries = LocationFactory.GetCountriesDictionary();
            add.Countries = countries.Select(item => new SelectListItem { Text = item.Value, Value = item.Key.ToString() }).ToList();
            add.Years = EnumExt.ToSelectListId(YearsEnum.Fourteen);
            add.Months = EnumExt.ToSelectListIdAndName(MonthsEnum.Jan);
            //#if DEBUG
            //                add.StripeKey = "Stripe.setPublishableKey('" + ServerConfig.STRIPE_DEBUG_KEY + "');";
            //#else
            add.StripeKey = "Stripe.setPublishableKey('" + ServerConfig.STRIPE_LIVE_KEY + "');";
            //#endif
            return View(add);
        }
        /// <summary>
        /// no need to do anything here just yet.
        /// I think when leagues start changing their subscriptions, we will need to update this code to change the plan
        /// 
        /// </summary>
        /// <param name="se"></param>
        /// <returns></returns>
        public static bool SubscriptionUpdated(StripeEvent se, string json)
        {
            try
            {
                //{ "id": "evt_1Myn3gX10D21o6", "created": 1361989292, "livemode": true, "type": "customer.subscription.updated", "data": { "object": { "plan": { "interval": "month", "name": "Monthly_Plan", "amount": 1599, "currency": "usd", "id": "Monthly_Plan", "object": "plan", "livemode": true, "interval_count": 1, "trial_period_days": null }, "object": "subscription", "start": 1359310832, "status": "active", "customer": "cus_1BMmWWvjng8Mug", "cancel_at_period_end": false, "current_period_start": 1361989232, "current_period_end": 1364408432, "ended_at": null, "trial_start": null, "trial_end": null, "canceled_at": null, "quantity": 1 }, "previous_attributes": { "current_period_start": 1359310832, "current_period_end": 1361989232 } }, "object": "event", "pending_webhooks": 1 } 

                PaymentGateway pg = new PaymentGateway();
                var f = pg.StartInvoiceWizard().Initalize(ServerConfig.RDNATION_STORE_ID, "USD",
PaymentProvider.Stripe, PaymentMode.Live, ChargeTypeEnum.SubscriptionUpdated)
                    .SetInvoiceId(Guid.NewGuid())
                    .SetInvoiceStatus(InvoiceStatus.Subscription_Should_Be_Updated_On_Charge);


                var dc = new ManagementContext();
                RDN.Library.DataModels.PaymentGateway.Stripe.StripeEventDb even = new RDN.Library.DataModels.PaymentGateway.Stripe.StripeEventDb();
                even.CreatedStripeDate = se.Created.GetValueOrDefault();
                even.StripeId = se.Id;
                even.LiveMode = se.LiveMode.GetValueOrDefault();
                if (se.Data != null)
                {
                    StripeSubscription cust = Stripe.Mapper<StripeSubscription>.MapFromJson(se.Data.Object.ToString());
                    //StripeSubscription cust = (StripeSubscription)se.Data.Object;
                    StripeSubscriptionDb custDb = new StripeSubscriptionDb();
                    even.StripeEventTypeEnum = (byte)StripeEventTypeEnum.customer_subscription_created;
                    custDb.CanceledAt = cust.CanceledAt;
                    custDb.EndedAt = cust.EndedAt;
                    custDb.Customer = dc.StripeCustomers.Where(x => x.Id == cust.CustomerId).FirstOrDefault();
                    custDb.PeriodEnd = cust.PeriodEnd;
                    custDb.PeriodStart = cust.PeriodStart;
                    custDb.Quantity = cust.Quantity;
                    custDb.Start = cust.Start;
                    custDb.Status = cust.Status;
                    if (cust.StripePlan != null)
                    {
                        custDb.StripePlan = dc.StripePlans.Where(x => x.Id == cust.StripePlan.Id).FirstOrDefault();
                        if (custDb.StripePlan == null)
                        {
                            StripePlanDb pl = new StripePlanDb();
                            pl.AmountInCents = cust.StripePlan.AmountInCents;
                            pl.Currency = cust.StripePlan.Currency;
                            pl.Id = cust.StripePlan.Id;
                            pl.Interval = cust.StripePlan.Interval;
                            pl.IntervalCount = cust.StripePlan.IntervalCount;
                            pl.LiveMode = cust.StripePlan.LiveMode;
                            pl.Name = cust.StripePlan.Name;
                            pl.TrialPeriodDays = cust.StripePlan.TrialPeriodDays;
                            custDb.StripePlan = pl;
                            dc.StripePlans.Add(pl);
                        }
                    }
                    DateTime now = DateTime.UtcNow;
                    TimeSpan ts = new TimeSpan();
                    int lengthOfDays = 31;

                    SubscriptionPeriodStripe period = SubscriptionPeriodStripe.Monthly;
                    if (cust.StripePlan.Id == StripePlanNames.Monthly_Plan.ToString())
                    {
                        period = SubscriptionPeriodStripe.Monthly;
                        ts = now.AddMonths(1) - DateTime.UtcNow;
                        lengthOfDays = ts.Days;
                    }
                    else if (cust.StripePlan.Id == StripePlanNames.Six_Month_League_Subscription.ToString())
                    {
                        period = SubscriptionPeriodStripe.Six_Months;
                        ts = now.AddMonths(6) - DateTime.UtcNow;
                        lengthOfDays = ts.Days;
                    }
                    else if (cust.StripePlan.Id == StripePlanNames.Three_Month_League_Subscription.ToString())
                    {
                        period = SubscriptionPeriodStripe.Three_Months;
                        ts = now.AddMonths(3) - DateTime.UtcNow;
                        lengthOfDays = ts.Days;
                    }
                    else if (cust.StripePlan.Id == StripePlanNames.Yearly_League_Subscription.ToString())
                    {
                        period = SubscriptionPeriodStripe.Yearly;
                        ts = now.AddMonths(12) - DateTime.UtcNow;
                        lengthOfDays = ts.Days;
                    }
                    //getting league Id here and subscriptionDate
                    var invoiceFromPast = pg.GetDisplayInvoiceWithStripeCustomerId(cust.CustomerId);
                    Guid leagueId = new Guid();
                    if (invoiceFromPast.Subscription != null)
                    {
                        leagueId = invoiceFromPast.Subscription.InternalObject;
                    }
                    f.SetPaymentProviderId(cust.CustomerId);
                    f.SetSubscription(new InvoiceSubscription
                    {
                        Description = "RDN League portal subscription",
                        DescriptionRecurring = "Fee for RDN League portal subscription",
                        Name = "RDN Member portal",
                        NameRecurring = "RDN Member portal recurring",
                        DigitalPurchaseText = "You have now access to RDN League portal",
                        Price = Convert.ToDecimal(cust.StripePlan.AmountInCents) / Convert.ToDecimal(100),
                        SubscriptionPeriodStripe = period,
                        SubscriptionPeriodLengthInDays = lengthOfDays,
                        //league id is the ownerId
                        InternalObject = leagueId
                    });

                    custDb.TrialEnd = cust.TrialEnd;
                    custDb.TrialStart = cust.TrialStart;

                    dc.StripeSubscriptions.Add(custDb);
                    even.Subscription = custDb;
                }
                dc.StripeEvents.Add(even);
                dc.SaveChanges();

                f.FinalizeInvoice();

                EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "STRIPE: New Subscription About to be charged!!", json);
                return true;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: json);
            }
            return false;
        }
        private void PerformPaypalRollinNewsWritersPayment(CreateInvoiceReturn output)
        {
            try
            {
                var status = (byte)InvoiceStatus.Payment_Awaiting_For_Mass_Payout;
                var dc = new ManagementContext();
                var invoices = dc.Invoices.Include("InvoiceBilling").Include("WriterPayouts").Where(x => x.InvoiceStatus == status).ToList();


                // Create request object
                List<Fund> tempFundsBeingPaid = new List<Fund>();
                MassPayRequestType request = new MassPayRequestType();
                ReceiverInfoCodeType receiverInfoType = ReceiverInfoCodeType.EMAILADDRESS;

                request.ReceiverType = receiverInfoType;
                // (Optional) The subject line of the email that PayPal sends when the transaction completes. The subject line is the same for all recipients.
                request.EmailSubject = "Payment For Rollin News Content " + DateTime.UtcNow.ToString("yyyy/MM/dd");

                foreach (var invoice in invoices)
                {
                    var payout = invoice.WriterPayouts.FirstOrDefault();

                    //gotta check if we are already paying this user.
                    var f = tempFundsBeingPaid.Where(x => x.UserId == payout.UserPaidId).FirstOrDefault();
                    if (f != null)
                    {
                        if (f.ActiveInUserAccount >= (f.AmountToWithdraw + (double)invoice.BasePriceForItems))
                        {
                            f.AmountToWithdraw += (double)payout.PriceAfterFees;
                            f.AmountToDeductFromTotal += (double)invoice.BasePriceForItems;

                        }
                    }
                    else
                    {
                        var fundSettings = Fund.GetCurrentFundsInformation(payout.UserPaidId);
                        if ((double)invoice.BasePriceForItems <= fundSettings.ActiveInUserAccount)
                        {
                            fundSettings.AmountToWithdraw += (double)payout.PriceAfterFees;
                            fundSettings.AmountToDeductFromTotal += (double)invoice.BasePriceForItems;
                            tempFundsBeingPaid.Add(fundSettings);
                        }
                    }

                }
                for (int i = 0; i < tempFundsBeingPaid.Count; i++)
                {
                    // (Required) Details of each payment.
                    // Note:
                    // A single MassPayRequest can include up to 250 MassPayItems.
                    MassPayRequestItemType massPayItem = new MassPayRequestItemType();
                    CurrencyCodeType currency = CurrencyCodeType.USD;
                    massPayItem.Amount = new BasicAmountType(currency, tempFundsBeingPaid[i].AmountToWithdraw.ToString("N2"));
                    massPayItem.ReceiverEmail = tempFundsBeingPaid[i].PaypalAddress;
                    massPayItem.Note = "Thanks for writing for Rollin News!  We appreciate your content. ID:" + invoice.InvoiceId.ToString().Replace("-", "");
                    if (!String.IsNullOrEmpty(tempFundsBeingPaid[i].PaypalAddress))
                        request.MassPayItem.Add(massPayItem);

                }

                // Invoke the API
                MassPayReq wrapper = new MassPayReq();
                wrapper.MassPayRequest = request;


                // Create the PayPalAPIInterfaceServiceService service object to make the API call
                PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();

                // # API call 
                // Invoke the MassPay method in service wrapper object  
                MassPayResponseType massPayResponse = service.MassPay(wrapper);

                // Display response values. 
                Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
                if (!(massPayResponse.Ack == AckCodeType.FAILURE) &&
                    !(massPayResponse.Ack == AckCodeType.FAILUREWITHWARNING))
                {


                    if (!(massPayResponse.Ack == AckCodeType.SUCCESS))
                    {

                        SendErrorsOfMassPayToAdmins(output, massPayResponse);
                        ErrorDatabaseManager.AddException(new Exception("MASSPAYERROR"), GetType(), additionalInformation: Newtonsoft.Json.JsonConvert.SerializeObject(tempFundsBeingPaid) + "______" + Newtonsoft.Json.JsonConvert.SerializeObject(massPayResponse));

                    }

                    for (int i = 0; i < tempFundsBeingPaid.Count; i++)
                    {
                        try
                        {
                            var user = SiteCache.GetPublicMemberFullWithUserId(tempFundsBeingPaid[i].UserId);
                            bool success = Fund.UpdateAmounts(tempFundsBeingPaid[i].UserId, tempFundsBeingPaid[i].TotalPaidToUser);

                            var emailData = new Dictionary<string, string> 
                            { 
                            { "derbyName", user.DerbyName},
                            {"amountPaid", tempFundsBeingPaid[i].AmountToDeductFromTotal.ToString("N2")}};
                            EmailServer.EmailServer.SendEmail(RollinNewsConfig.DEFAULT_EMAIL, RollinNewsConfig.DEFAULT_EMAIL_FROM_NAME, user.UserName, EmailServer.EmailServer.DEFAULT_SUBJECT_ROLLIN_NEWS + " You Were Just Paid!", emailData, EmailServer.EmailServerLayoutsEnum.RNPaymentJustPaid);
                        }
                        catch (Exception exception)
                        {
                            ErrorDatabaseManager.AddException(exception, exception.GetType());
                        }
                    }
                    var emailDataComplete = new Dictionary<string, string> { { "totalPaid", tempFundsBeingPaid.Sum(x=>x.AmountToDeductFromTotal).ToString("N2") },
                    {"totalUsersPaid", tempFundsBeingPaid.Count.ToString()}};
                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, RollinNewsConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, EmailServer.EmailServer.DEFAULT_SUBJECT_ROLLIN_NEWS + " Mass Pay Completed!", emailDataComplete, EmailServer.EmailServerLayoutsEnum.RNPaymentJustCompleted);

                    for (int i = 0; i < invoices.Count; i++)
                    {
                        Payment.PaymentGateway pg = new PaymentGateway();
                        pg.SetInvoiceStatus(invoices[i].InvoiceId, InvoiceStatus.Payment_Successful);
                    }
                }
                else
                {
                    SendErrorsOfMassPayToAdmins(output, massPayResponse);
                }


            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
        }
        private StripeCharge PerformStripeRefund()
        {
            try
            {
                PaymentGateway pg = new PaymentGateway();
                var merchant = pg.GetMerchant(invoice.MerchantId);
                var voice = pg.GetDisplayInvoice(invoice.InvoiceId);
                int amountInCentsTotalRefund = Convert.ToInt32((invoice.FinancialData.RefundAmount) * 100);
                var chargeService = new StripeChargeService(merchant.StripeConnectToken);
                StripeCharge stripeCharge = chargeService.Refund(voice.CustomerId, amountInCentsTotalRefund);
                invoice.PaymentProviderRefundedId = stripeCharge.Id;

                return stripeCharge;

            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return null;
        }
        private StripeCharge PerformStripePaywallPurchaseCheckout()
        {
            try
            {
                PaymentGateway pg = new PaymentGateway();
                var merchant = pg.GetMerchant(invoice.MerchantId);
                int amountInCentsTotalPayment = Convert.ToInt32((invoice.FinancialData.BasePriceForItems) * 100);
                int RDNationsCut = Convert.ToInt32(amountInCentsTotalPayment - (invoice.FinancialData.PriceSubtractingRDNationFees * 100));
                var stripeService = new StripeChargeService(merchant.StripeConnectToken); //The token returned from the above method
                var stripeChargeOption = new StripeChargeCreateOptions() { AmountInCents = amountInCentsTotalPayment, Currency = "usd", Description = invoice.InvoiceId.ToString().Replace("-", "") + ": Payment to " + merchant.OwnerName, TokenId = invoice.StripeToken, ApplicationFeeInCents = RDNationsCut };

                var response = stripeService.Create(stripeChargeOption);
                invoice.PaymentProviderCustomerId = response.Id;

                return response;

            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return null;
        }
        public ActionResult MakePaywallPayment(GameOutModel crap)
        {
            var memId = RDN.Library.Classes.Account.User.GetMemberId();
            GameOutModel game = new GameOutModel();
            game.Game = GameServerViewModel.GetGameFromCache(crap.Game.GameId);
            Paywall wall = new Paywall();
            game.Paywall = wall.GetPaywall(game.Game.PaywallId);

            try
            {
                string paymentProvider = Request.Form["PaymentType"].ToString();
                string stripeToken = "none";

                PaymentProvider provider = PaymentProvider.None;
                if (paymentProvider == PaymentProvider.Stripe.ToString())
                {
                    provider = PaymentProvider.Stripe;
                    stripeToken = Request.Form["stripeToken"].ToString();
                }
                else if (paymentProvider == PaymentProvider.Paypal.ToString())
                {
                    provider = PaymentProvider.Paypal;
                }
                string subType = Request.Form["PaymentCost"].ToString();
                PaywallPriceTypeEnum sub = (PaywallPriceTypeEnum)Enum.Parse(typeof(PaywallPriceTypeEnum), subType);
                decimal price = .99M;

                DateTime now = DateTime.UtcNow;
                DateTime validTill = DateTime.UtcNow.AddDays(1);

                if (sub == PaywallPriceTypeEnum.Daily_Payment)
                {
                    validTill = DateTime.UtcNow.AddDays(1);
                }
                else if (sub == PaywallPriceTypeEnum.Full_Payment)
                {
                    validTill = game.Paywall.EndDate.Value.AddDays(1);
                }

                PaymentGateway pg = new PaymentGateway();
                var f = pg.StartInvoiceWizard().Initalize(game.Paywall.MerchantId, "USD", provider, PaymentMode.Live, ChargeTypeEnum.Paywall)
                    .SetInvoiceId(Guid.NewGuid())
                    .SetPaywall(new InvoicePaywall
                    {
                        ValidUntil = validTill,
                        PaywallId = game.Paywall.PaywallId,
                        PriceType = sub,
                        Description = "Paid For " + game.Game.GameName + " with a " + RDN.Utilities.Enums.EnumExt.ToFreindlyName(sub) + " Pass",
                        Name = "Game Streaming Paid",
                        Price = price,
                        InternalObject = game.Game.GameId,
                        MemberPaidId = memId,
                        PaywallLocation = ServerConfig.WEBSITE_DEFAULT_LOCATION + "/roller-derby-game/" + game.Game.GameId.ToString().Replace("-", "") + "/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(game.Game.GameName) + "/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(game.Game.Team1.TeamName) + "/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(game.Game.Team2.TeamName)
                    })
                    .SetInvoiceContactData(new InvoiceContactInfo
                    {
                        Email = crap.Paywall.EmailAddress,
                        Phone = crap.Paywall.PhoneNumber,
                    });

                if (provider == PaymentProvider.Stripe)
                    f.SetStripeTokenId(stripeToken);

                var response = f.FinalizeInvoice();

                //succesfully charged.
                if (response.Status == InvoiceStatus.Payment_Successful)
                    return Redirect(ServerConfig.PAYWALL_RECEIPT_URL + response.InvoiceId.ToString().Replace("-", ""));
                else if (response.Status == InvoiceStatus.Pending_Payment_From_Paypal)
                    return Redirect(response.RedirectLink);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/roller-derby-game/" + game.Game.GameId.ToString().Replace("-", "") + "/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(game.Game.GameName) + "/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(game.Game.Team1.TeamName) + "/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(game.Game.Team2.TeamName) + "?u=" + SiteMessagesEnum.sww));

        }
        public ActionResult LeagueCancelSubscription(LeagueBilling add)
        {
            var memId = RDN.Library.Classes.Account.User.GetMemberId();

            try
            {
                var bi = RDN.Library.Classes.Billing.Classes.LeagueBilling.GetCurrentBillingStatus(add.LeagueId);

                PaymentGateway pg = new PaymentGateway();
                var f = pg.StartInvoiceWizard().Initalize(ServerConfig.RDNATION_STORE_ID, "USD", PaymentProvider.Stripe, PaymentMode.Live, ChargeTypeEnum.Cancel_Subscription)
                   .SetInvoiceId(bi.InvoiceId)
                        .FinalizeInvoice();

                //clears the member cache to update all cache repos of the league members.
                MemberCache.ClearLeagueMembersCache(add.LeagueId);
                MemberCache.ClearLeagueMembersApiCache(add.LeagueId);
                //succesfully charged.
                if (f.Status == InvoiceStatus.Cancelled)
                    return Redirect(Url.Content("~/billing/league/" + add.LeagueId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.sc));
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
        }