Beispiel #1
0
        public static bool DeleteCard(string cardId, string customerID)
        {
            var cardService = new StripeCardService();

            try
            {
                cardService.Delete(customerID, cardId);
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        /// <summary>
        /// Updates the credit card asynchronous.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="creditcard">The creditcard.</param>
        /// <returns></returns>
        public async Task UpdateAsync(SaasEcomUser user, CreditCard creditcard)
        {
            // Remove current card from stripe
            var currentCard = await _cardDataService.FindAsync(user.Id, creditcard.Id, true);

            var stripeCustomerId = user.StripeCustomerId;

            _cardService.Delete(stripeCustomerId, currentCard.StripeId);

            this.AddCardToStripe(creditcard, stripeCustomerId);

            // Update card in the DB
            creditcard.SaasEcomUserId = user.Id;
            await _cardDataService.UpdateAsync(user.Id, creditcard);
        }
        public async Task <dynamic> Post()
        {
            try
            {
                var    item  = RequestContext.Principal.Identity;
                string value = await Request.Content.ReadAsStringAsync();

                var entidad  = System.Web.Helpers.Json.Decode(value);
                var customer = entidad.customerId;
                var card     = entidad.cardId;

                var cardService = new StripeCardService("sk_test_CBdkobSnlUEOyOjsLQ8fpqof");
                cardService.Delete(customer, card);
                return("Eliminada");
            }
            catch (Exception ex)
            {
                return(ex);
            }
        }
Beispiel #4
0
        public ActionResult CancelSubscription(long userID)
        {
            string         customerID      = Convert.ToString(SessionController.UserSession.CustomerID);
            var            customerService = new StripeCustomerService();
            StripeCustomer stripeCustomer  = customerService.Get(customerID);

            var subscriptionID = stripeCustomer.Subscriptions.Data[0].Id;

            var subscriptionService = new StripeSubscriptionService();
            var status = subscriptionService.Cancel(subscriptionID, true); // optional cancelAtPeriodEnd flag

            SessionController.UserSession.IsPaid = false;

            //Delete the customer's card from stripe
            var           cardService = new StripeCardService();
            StripeCard    stripeCard  = cardService.Get(customerID, stripeCustomer.DefaultSourceId);
            StripeDeleted card        = cardService.Delete(customerID, stripeCard.Id);

            return(Json(status, JsonRequestBehavior.AllowGet));
        }
Beispiel #5
0
        public string UpdateCustomer(string stripeId, string ccToken)
        {
            //remove old card
            var customerService = new StripeCustomerService(Constants.StripeSecretKey);

            Stripe.StripeCustomer stripeCustomer = customerService.Get(stripeId);

            if (!String.IsNullOrEmpty(stripeCustomer.DefaultSourceId))
            {
                var cardService = new StripeCardService(Constants.StripeSecretKey);
                cardService.Delete(stripeId, stripeCustomer.DefaultSourceId);
            }
            var myCustomer = new StripeCustomerUpdateOptions();

            myCustomer.SourceToken = ccToken;

            // this will set the default card to use for this customer
            var finalCustomer = customerService.Update(stripeId, myCustomer);

            return(finalCustomer.Id);
        }
        public async Task <IActionResult> CampaignPayment(CustomerPaymentViewModel payment)
        {
            try
            {
                var user = await GetCurrentUserAsync();

                if (!ModelState.IsValid)
                {
                    return(View(payment));
                }

                var customerService = new StripeCustomerService(_stripeSettings.Value.SecretKey);
                var donation        = _campaignService.GetById(payment.DonationId);

                // Construct payment
                if (string.IsNullOrEmpty(user.StripeCustomerId))
                {
                    StripeCustomerCreateOptions customer = GetCustomerCreateOptions(payment, user);
                    var stripeCustomer = customerService.Create(customer);
                    user.StripeCustomerId = stripeCustomer.Id;
                }
                else
                {
                    //Check for existing credit card, if new credit card number is same as exiting credit card then we delete the existing
                    //Credit card information so new card gets generated automatically as default card.
                    try
                    {
                        var ExistingCustomer = customerService.Get(user.StripeCustomerId);
                        if (ExistingCustomer.Sources != null && ExistingCustomer.Sources.TotalCount > 0 && ExistingCustomer.Sources.Data.Any())
                        {
                            var cardService = new StripeCardService(_stripeSettings.Value.SecretKey);
                            foreach (var cardSource in ExistingCustomer.Sources.Data)
                            {
                                cardService.Delete(user.StripeCustomerId, cardSource.Card.Id);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log = new EventLog()
                        {
                            EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source
                        };
                        _loggerService.SaveEventLogAsync(log);
                        return(RedirectToAction("Error", "Error500", new ErrorViewModel()
                        {
                            Error = ex.Message
                        }));
                    }

                    StripeCustomerUpdateOptions customer = GetCustomerUpdateOption(payment);
                    var stripeCustomer = customerService.Update(user.StripeCustomerId, customer);
                    user.StripeCustomerId = stripeCustomer.Id;
                }

                UpdateUserEmail(payment, user);
                await UpdateUserDetail(payment, user);

                // Add customer to Stripe
                if (EnumInfo <PaymentCycle> .GetValue(donation.CycleId) == PaymentCycle.OneTime)
                {
                    var model   = (DonationViewModel)donation;
                    var charges = new StripeChargeService(_stripeSettings.Value.SecretKey);

                    // Charge the customer
                    var charge = charges.Create(new StripeChargeCreateOptions
                    {
                        Amount              = Convert.ToInt32(donation.DonationAmount * 100),
                        Description         = DonationCaption,
                        Currency            = "usd",//payment.Currency.ToLower(),
                        CustomerId          = user.StripeCustomerId,
                        StatementDescriptor = _stripeSettings.Value.StatementDescriptor,
                    });

                    if (charge.Paid)
                    {
                        var completedMessage = new CompletedViewModel
                        {
                            Message          = donation.DonationAmount.ToString(),
                            HasSubscriptions = false
                        };
                        return(RedirectToAction("Thanks", completedMessage));
                    }
                    return(RedirectToAction("Error", "Error", new ErrorViewModel()
                    {
                        Error = "Error"
                    }));
                }

                // Add to existing subscriptions and charge
                donation.Currency = "usd"; //payment.Currency;
                var plan = _campaignService.GetOrCreatePlan(donation);

                var subscriptionService = new StripeSubscriptionService(_stripeSettings.Value.SecretKey);
                var result = subscriptionService.Create(user.StripeCustomerId, plan.Id);
                if (result != null)
                {
                    var completedMessage = new CompletedViewModel
                    {
                        Message          = result.StripePlan.Nickname.Split("_")[1] + result.StripePlan.Nickname.Split("_")[0],
                        HasSubscriptions = true
                    };
                    return(RedirectToAction("Thanks", completedMessage));
                }
            }
            catch (StripeException ex)
            {
                log = new EventLog()
                {
                    EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source
                };
                _loggerService.SaveEventLogAsync(log);
                if (ex.Message.ToLower().Contains("customer"))
                {
                    return(RedirectToAction("Error", "Error500", new ErrorViewModel()
                    {
                        Error = ex.Message
                    }));
                }
                else
                {
                    ModelState.AddModelError("error", ex.Message);
                    return(View(payment));
                }
            }
            catch (Exception ex)
            {
                log = new EventLog()
                {
                    EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source
                };
                _loggerService.SaveEventLogAsync(log);
                return(RedirectToAction("Error", "Error", new ErrorViewModel()
                {
                    Error = ex.Message
                }));
            }
            return(RedirectToAction("Error", "Error", new ErrorViewModel()
            {
                Error = "Error"
            }));
        }
Beispiel #7
0
        private String ProcessStripePayment(ValidationCollectedInfo info)
        {
            if (Request["stripetoken"].HasNoText())
            {
                throw new CartException("Stripe Token is required.");
            }

            var            stripeToken           = Request["stripeToken"];
            var            stripeCustomerService = new StripeCustomerService();
            StripeCustomer stripeCustomer        = null;
            String         existingSourceId      = null;

            try
            {
                stripeCustomer = stripeCustomerService.Get(Profile.StripeCustomerId);

                if (stripeCustomer.Deleted == true)
                {
                    stripeCustomer = null;
                }
                else
                {
                    try
                    {
                        var stripeCardService = new StripeCardService();
                        var stripeCard        = stripeCardService.Create(stripeCustomer.Id, new StripeCardCreateOptions
                        {
                            SourceToken = stripeToken
                        });
                        var scOld = stripeCustomer.SourceList.Data.FirstOrDefault(c => String.Compare(c.Fingerprint, stripeCard.Fingerprint, false) == 0);

                        if (scOld != null)
                        {
                            try
                            {
                                stripeCardService.Delete(stripeCustomer.Id, stripeCard.Id);
                            }
                            catch
                            {
                            }

                            existingSourceId = scOld.Id;
                        }
                        else
                        {
                            existingSourceId = stripeCard.Id;
                        }
                    }
                    catch
                    {
                    }
                }
            }
            catch (StripeException)
            {
            }

            if (stripeCustomer == null)
            {
                stripeCustomer = stripeCustomerService.Create(new StripeCustomerCreateOptions
                {
                    Email       = User.Identity.Name,
                    Description = Profile.FirstName + " " + Profile.LastName,
                    SourceToken = stripeToken
                });
                Profile.StripeCustomerId = stripeCustomer.Id;
                Profile.Save();
                existingSourceId = stripeCustomer.DefaultSourceId;
            }

            var stripeChargeService = new StripeChargeService();
            var stripeChargeOptions = new StripeChargeCreateOptions()
            {
                Amount      = (Int32)(info.TotalPrice * 100),
                Currency    = "USD",
                Description = info.Orders.Count == 1 ? String.Format("1 flyer (ID {0})", info.Orders[0].order_id.ToString()) : String.Format("{0} flyers (IDs {1})", info.Orders.Count.ToString(), String.Join(", ", info.OrderIds)),
                Capture     = true,
                CustomerId  = stripeCustomer.Id,
                SourceTokenOrExistingSourceId = existingSourceId
            };
            var stripeCharge = stripeChargeService.Create(stripeChargeOptions);
            var result       = stripeCharge.Id;

            return(result);
        }