public async Task <ActionResult> RemovePaymentMethod(RemovePaymentMethodBody removePaymentMethodBody)
        {
            try
            {
                Logger.LogInformation("{Id} is removing a payment method", removePaymentMethodBody.UserId);
                await PaymentService.RemovePaymentMethod(removePaymentMethodBody);

                return(Ok());
            }
            catch (Exception e)
            {
                Logger.LogError(e.ToString());
                return(BadRequest(e));
            }
        }
Пример #2
0
        /// <inheritdoc />
        /// <exception cref="UserNotFoundException">Thrown when the user is not found</exception>
        /// <exception cref="PaymentMethodNotFoundException">Thrown when the users payment method was not found</exception>
        public async Task RemovePaymentMethod(RemovePaymentMethodBody removePaymentMethodBody)
        {
            var userWithPayments =
                await ApplicationContext.Users.Include(x => x.PaymentMethods)
                .FirstOrDefaultAsync(x => x.Id == removePaymentMethodBody.UserId);

            if (userWithPayments == null)
            {
                throw new UserNotFoundException();
            }

            var paymentMethod =
                userWithPayments.PaymentMethods.FirstOrDefault(
                    x => x.StripeCardId == removePaymentMethodBody.PaymentId);

            if (paymentMethod == null)
            {
                throw new PaymentMethodNotFoundException();
            }

            bool paymentWasDefault = paymentMethod.IsDefault;

            var service = new CardService();

            try
            {
                // request card delete from the Stripe api
                service.Delete(userWithPayments.StripeCustomerId, paymentMethod.StripeCardId);

                // remove the payment method and set first to default if the removed card was the default
                ApplicationContext.PaymentMethods.Remove(paymentMethod);
                if (paymentWasDefault)
                {
                    userWithPayments.PaymentMethods.First().IsDefault = true;
                }

                await ApplicationContext.SaveChangesAsync();
            }
            catch (Exception e)
            {
                Logger.LogInformation(e.Message);
                throw;
            }
        }