public static bool ChargeFailed(StripeEvent se, string json)
        {
            try
            {

                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)
                {
                    //StripeCharge inv = (StripeCharge)se.Data.Object;
                    StripeCharge inv = Stripe.Mapper<StripeCharge>.MapFromJson(se.Data.Object.ToString());
                    StripeChargeDb nnv = new StripeChargeDb();
                    even.StripeEventTypeEnum = (byte)StripeEventTypeEnum.charge_failed;
                    nnv.AmountInCents = inv.AmountInCents;
                    nnv.AmountInCentsRefunded = inv.AmountInCentsRefunded;
                    nnv.Currency = inv.Currency;
                    nnv.Customer = dc.StripeCustomers.Where(x => x.Id == inv.CustomerId).FirstOrDefault();
                    nnv.Description = inv.Description;
                    nnv.FailureMessage = inv.FailureMessage;

                    nnv.FeeInCents = inv.FeeInCents;
                    nnv.Id = inv.Id;
                    nnv.Invoice = dc.StripeInvoices.Where(x => x.Id == inv.InvoiceId).FirstOrDefault();
                    nnv.LiveMode = inv.LiveMode;
                    nnv.Paid = inv.Paid;
                    nnv.Refunded = inv.Refunded;
                    if (inv.StripeCard != null)
                    {
                        nnv.StripeCard = dc.StripeCards.Where(x => x.AddressLine1 == inv.StripeCard.AddressLine1).Where(x => x.Last4 == inv.StripeCard.Last4).FirstOrDefault();
                        if (nnv.StripeCard == null)
                        {
                            nnv.StripeCard = CreateStripeCard(inv.StripeCard, json);
                            dc.StripeCards.Add(nnv.StripeCard);
                        }
                    }
                    even.Charge = nnv;
                    dc.StripeCharges.Add(nnv);

                    var invoice = (from xx in dc.Invoices
                                   where xx.PaymentProviderCustomerId == inv.CustomerId
                                   where xx.InvoicePaid == false
                                   select xx).OrderByDescending(x => x.Created).FirstOrDefault();
                    if (invoice == null)
                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "STRIPE: Invoice Not Found, Can't Be Confirmed, CHARGE FAILED", inv.CustomerId + " " + inv.ToString() + json);
                    else
                    {
                        if (invoice.InvoiceStatus == (byte)InvoiceStatus.Subscription_Should_Be_Updated_On_Charge)
                        {
                            //update league subscription
                            //League.League.UpdateLeagueSubscriptionPeriod(invoice.Subscription.ValidUntil, true, invoice.Subscription.InternalObject);
                            //EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "STRIPE: Subscription Updated!!", invoice.InvoiceId + " Amount:" + inv.AmountInCents + ":" + inv.ToString() + json);
                        }

                        invoice.InvoicePaid = false;
                        if (nnv.FailureMessage == null)
                        {
                            invoice.InvoiceStatus = (byte)InvoiceStatus.Failed;
                            nnv.FailureMessage = "Payment Declined, Please contact RDNation @ [email protected].";
                        }
                        else if (nnv.FailureMessage.Contains("Your card number is incorrect"))
                            invoice.InvoiceStatus = (byte)InvoiceStatus.Card_Was_Declined;
                        else
                            invoice.InvoiceStatus = (byte)InvoiceStatus.Failed;

                        invoice.InvoiceStatusUpdated = DateTime.UtcNow;
                        invoice.Merchant = invoice.Merchant;

                        var customerService = new StripeCustomerService();
                        StripeSubscription subscription = customerService.CancelSubscription(inv.CustomerId, true);

                        EmailLeagueAboutCardDeclinedSubscription(invoice.Subscription.InternalObject, invoice.InvoiceId, nnv.FailureMessage, ServerConfig.LEAGUE_SUBSCRIPTION_UPDATESUBSUBSCRIBE + invoice.Subscription.InternalObject.ToString().Replace("-", ""), ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN);
                    }

                }
                dc.StripeEvents.Add(even);
                dc.SaveChanges();

                return true;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: json);
            }
            return false;
        }
        public JsonResult ChangePlan(string organizationId, string planId, string stripeToken, string last4) {
            if (String.IsNullOrEmpty(organizationId) || !User.CanAccessOrganization(organizationId))
                throw new ArgumentException("Invalid organization id.", "organizationId"); // TODO: These should probably throw http Response exceptions.

            if (!Settings.Current.EnableBilling)
                return Json(new { Success = false, Message = "Plans cannot be changed while billing is disabled." });

            Organization organization = _repository.GetById(organizationId);
            if (organization == null)
                return Json(new { Success = false, Message = "Invalid OrganizationId." });

            BillingPlan plan = _billingManager.GetBillingPlan(planId);
            if (plan == null)
                return Json(new { Success = false, Message = "Invalid PlanId." });

            if (String.Equals(organization.PlanId, plan.Id) && String.Equals(BillingManager.FreePlan.Id, plan.Id))
                return Json(new { Success = true, Message = "Your plan was not changed as you were already on the free plan." });

            // Only see if they can downgrade a plan if the plans are different.
            string message;
            if (!String.Equals(organization.PlanId, plan.Id) && !_billingManager.CanDownGrade(organization, plan, User.UserEntity, out message))
                return Json(new { Success = false, Message = message });

            var customerService = new StripeCustomerService();

            try {
                // If they are on a paid plan and then downgrade to a free plan then cancel their stripe subscription.
                if (!String.Equals(organization.PlanId, BillingManager.FreePlan.Id) && String.Equals(plan.Id, BillingManager.FreePlan.Id)) {
                    if (!String.IsNullOrEmpty(organization.StripeCustomerId))
                        customerService.CancelSubscription(organization.StripeCustomerId);

                    organization.BillingStatus = BillingStatus.Trialing;
                    organization.RemoveSuspension();
                } else if (String.IsNullOrEmpty(organization.StripeCustomerId)) {
                    if (String.IsNullOrEmpty(stripeToken))
                        return Json(new { Success = false, Message = "Billing information was not set." });

                    organization.SubscribeDate = DateTime.Now;

                    StripeCustomer customer = customerService.Create(new StripeCustomerCreateOptions {
                        TokenId = stripeToken,
                        PlanId = planId,
                        Description = organization.Name
                    });

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                    organization.StripeCustomerId = customer.Id;
                    if (customer.StripeCardList.StripeCards.Count > 0)
                        organization.CardLast4 = customer.StripeCardList.StripeCards[0].Last4;
                } else {
                    var update = new StripeCustomerUpdateSubscriptionOptions {
                        PlanId = planId
                    };
                    bool cardUpdated = false;

                    if (!String.IsNullOrEmpty(stripeToken)) {
                        update.TokenId = stripeToken;
                        cardUpdated = true;
                    }

                    customerService.UpdateSubscription(organization.StripeCustomerId, update);
                    if (cardUpdated)
                        organization.CardLast4 = last4;

                    organization.BillingStatus = BillingStatus.Active;
                    organization.RemoveSuspension();
                }

                _billingManager.ApplyBillingPlan(organization, plan, User.UserEntity);
                _repository.Update(organization);

                _notificationSender.PlanChanged(organization.Id);
            } catch (Exception e) {
                Log.Error().Exception(e).Message("An error occurred while trying to update your billing plan: " + e.Message).Report(r => r.MarkAsCritical()).Write();
                return Json(new { Success = false, Message = e.Message });
            }

            return Json(new { Success = true });
        }
        public HttpResponseMessage Delete(string id, int organizationId, CancelReason cancelReason, string cancelText)
        {
            OrganizationId = organizationId;
            try
            {
                if (UserIsAdminOfOrganization)
                {

                    var customerService = new StripeCustomerService();
                    StripeSubscription stripeSubscription = customerService.CancelSubscription(id);    // you can optionally pass cancelAtPeriodEnd instead of immediately cancelling 

                    var organization = this.organizationService.Get(organizationId);
                    organization.Subscription.Status = SubscriptionStatus.INACTIVE;
                    organization.Subscription.CustomerBillingId = id;
                    organization.Subscription.CancelReason = cancelReason;

                    this.subscriptionService.SaveSubscription(organization);
                    emailHelper.SendCancelNotice(id, organizationId, System.Enum.GetName(typeof(CancelReason), cancelReason), cancelText);
                    return Request.CreateResponse(HttpStatusCode.Accepted);
                }
            }
            catch (StripeException ex)
            {
                emailHelper.SendStripeError(ex);
            }
            catch (Exception e)
            {
                emailHelper.SendErrorEmail(e);
            }
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
Exemplo n.º 4
0
 public bool CancelSubscription(string customerId)
 {
     try
     {
         var customerService = new StripeCustomerService();
         var response = customerService.CancelSubscription(customerId);
         return true;
     }
     catch (StripeException stripeEx)
     {
         EventLog.LogEvent(stripeEx);
         return false;
     }
     catch (Exception ex)
     {
         EventLog.LogEvent(ex);
         return false;
     }
 }
        private bool PerformStripeSubscriptionCancellation(CreateInvoiceReturn invoiceReturn)
        {
            try
            {
                ManagementContext dc = new ManagementContext();
                var invoice = dc.Invoices.Include("Items")
                    .Include("Payments").Include("Logs")
                    .Include("Subscription").Include("InvoiceShipping")
                    .Include("InvoiceBilling").Include("Merchant").Where(x => x.InvoiceId == invoiceReturn.InvoiceId).FirstOrDefault();

                if (invoice != null)
                {
                    invoice.InvoiceStatus = (byte)InvoiceStatus.Cancelled;
                    invoice.PaymentProvider = invoice.PaymentProvider;
                    invoice.BasePriceForItems = invoice.BasePriceForItems;
                    invoice.Merchant = invoice.Merchant;
                    var customerService = new StripeCustomerService();
                    StripeSubscription subscription = customerService.CancelSubscription(invoice.PaymentProviderCustomerId);
                    int c = dc.SaveChanges();
                    return c > 0;
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
                if (exception.Message.Contains("Your card was declined"))
                    invoiceReturn.Status = InvoiceStatus.Card_Was_Declined;
            }
            return false;
        }