Exemplo n.º 1
0
        public ActionResult <Invoice> RetryInvoice([FromBody] RetryInvoiceRequest req)
        {
            // Attach payment method
            var options = new PaymentMethodAttachOptions
            {
                Customer = req.Customer,
            };
            var service       = new PaymentMethodService();
            var paymentMethod = service.Attach(req.PaymentMethod, options);

            // Update customer's default invoice payment method
            var customerOptions = new CustomerUpdateOptions
            {
                InvoiceSettings = new CustomerInvoiceSettingsOptions
                {
                    DefaultPaymentMethod = paymentMethod.Id,
                },
            };
            var customerService = new CustomerService();

            customerService.Update(req.Customer, customerOptions);

            var invoiceOptions = new InvoiceGetOptions();

            invoiceOptions.AddExpand("payment_intent");
            var     invoiceService = new InvoiceService();
            Invoice invoice        = invoiceService.Get(req.Invoice, invoiceOptions);

            return(invoice);
        }
Exemplo n.º 2
0
        public Subscription Purchase(string email, string cardCvc, string cardNumber, long cardExpirationMonth, long cardExpirationYear)
        {
            StripeConfiguration.ApiKey = Configuration.STRIPE_API_SECRET_KEY;
            var customerSvc          = new CustomerService();
            var customer             = GetOrCreateCustomer(customerSvc, email);
            var paymentMethodService = new PaymentMethodService();
            var paymentMethod        = paymentMethodService.Create(
                new PaymentMethodCreateOptions
            {
                Type = "card",
                Card = new PaymentMethodCardCreateOptions
                {
                    Cvc      = cardCvc,
                    Number   = cardNumber,
                    ExpMonth = cardExpirationMonth,
                    ExpYear  = cardExpirationYear
                },
            });

            paymentMethod = paymentMethodService.Attach(
                paymentMethod.Id,
                new PaymentMethodAttachOptions
            {
                Customer = customer.Id
            });
            var subscriptionSvc = new SubscriptionService();
            var subscription    = GetOrCreateSubscription(subscriptionSvc, customer, Configuration.STRIPE_INCOME_CALCULATOR_PRODUCT_PLAN_ID, paymentMethod.Id);

            return(subscription);
        }
        public ActionResult <Subscription> CreateSubscription([FromBody] CreateSubscriptionRequest req)
        {
            // Attach payment method
            PaymentMethod paymentMethod;

            try
            {
                var options = new PaymentMethodAttachOptions
                {
                    Customer = req.Customer,
                };
                var service = new PaymentMethodService();
                paymentMethod = service.Attach(req.PaymentMethod, options);
            }
            catch (StripeException e)
            {
                return(Ok(new { error = new { message = e.Message } }));
            }

            // Update customer's default invoice payment method
            var customerOptions = new CustomerUpdateOptions
            {
                InvoiceSettings = new CustomerInvoiceSettingsOptions
                {
                    DefaultPaymentMethod = paymentMethod.Id,
                },
            };
            var customerService = new CustomerService();

            customerService.Update(req.Customer, customerOptions);

            // Create subscription
            var subscriptionOptions = new SubscriptionCreateOptions
            {
                Customer = req.Customer,
                Items    = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Price = Environment.GetEnvironmentVariable(req.Price),
                    },
                },
            };

            subscriptionOptions.AddExpand("latest_invoice.payment_intent");
            var subscriptionService = new SubscriptionService();

            try
            {
                Subscription subscription = subscriptionService.Create(subscriptionOptions);
                return(subscription);
            }
            catch (StripeException e)
            {
                Console.WriteLine($"Failed to create subscription.{e}");
                return(BadRequest());
            }
        }
Exemplo n.º 4
0
        public static void AttachPaymentMethod(Customer existingCustomer, PaymentMethod paymentMethod, PaymentMethodService paymentMethodService)
        {
            // Attach a payment method to a customer
            var paymentMethodAttachOptions = new PaymentMethodAttachOptions {
                Customer = existingCustomer.Id
            };

            paymentMethodService.Attach(paymentMethod.Id, paymentMethodAttachOptions);
        }
Exemplo n.º 5
0
    public void AttachPaymentMethodToCustomer(string paymentMethodId, string customerId)
    {
        var options = new PaymentMethodAttachOptions
        {
            Customer = customerId,
        };

        _paymentMethodService.Attach(paymentMethodId, options);
    }
Exemplo n.º 6
0
        public string SignUserUpToSubscription(string paymentMethodId, User user, ClubSubscription clubSubscription)
        {
            var options = new PaymentMethodAttachOptions
            {
                Customer = user.StripeUserId,
            };
            var service       = new PaymentMethodService();
            var paymentMethod = service.Attach(paymentMethodId, options);

            // Update customer's default invoice payment method
            var customerOptions = new CustomerUpdateOptions
            {
                InvoiceSettings = new CustomerInvoiceSettingsOptions
                {
                    DefaultPaymentMethod = paymentMethod.Id,
                },
            };
            var customerService = new CustomerService();

            customerService.Update(user.StripeUserId, customerOptions);

            // Create subscription
            var subscriptionOptions = new SubscriptionCreateOptions
            {
                Customer = user.StripeUserId,
                Items    = new List <SubscriptionItemOptions>()
                {
                    new SubscriptionItemOptions
                    {
                        Price = clubSubscription.StripePriceId,
                    },
                },
                Metadata = new Dictionary <string, string>()
                {
                    { "UserId", user.UserId.ToString() },
                    { "ClubSubscriptionId", clubSubscription.ClubSubscriptionId.ToString() },
                }
            };

            subscriptionOptions.AddExpand("latest_invoice.payment_intent");
            var subscriptionService = new SubscriptionService();

            try
            {
                Subscription subscription = subscriptionService.Create(subscriptionOptions);
                return("Went good");
            }
            catch (StripeException e)
            {
                Console.WriteLine($"Failed to create subscription.{e}");
                return("Went bad");
                // return BadRequest();
            }
        }
        public async Task <IActionResult> CreateSubscription([FromBody] CreateSubscription sub)
        {
            var option = new PaymentMethodAttachOptions
            {
                Customer = sub.Customer,
            };

            var service = new PaymentMethodService();

            var paymentMethod = service.Attach(sub.PaymentMethod, option);

            // Update customer's default invoice payment method
            var customerOptions = new CustomerUpdateOptions
            {
                InvoiceSettings = new CustomerInvoiceSettingsOptions
                {
                    DefaultPaymentMethod = paymentMethod.Id,
                },
            };
            var customerService = new CustomerService();
            await customerService.UpdateAsync(sub.Customer, customerOptions);

            var subscriptionOptions = new SubscriptionCreateOptions
            {
                Customer = sub.Customer,
                Items    = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Price = Environment.GetEnvironmentVariable(sub.Price),
                    }
                },
            };

            subscriptionOptions.AddExpand("latest_invoice.payment_intent");

            var subscriptionService = new SubscriptionService();

            try
            {
                Subscription subscription = subscriptionService.Create(subscriptionOptions);
                return(Ok(new ResponseViewModel <Subscription>
                {
                    Data = subscription,
                    Message = StripeConstants.SubscriptionAdded
                }));
            }
            catch (StripeException e)
            {
                Console.WriteLine($"Failed to create subscription.{e}");
                return(BadRequest());
            }
        }
Exemplo n.º 8
0
        public ActionResult <SubscriptionResponse> CreateSubscription([FromBody] CreateSubscriptionRequest req)
        {
            var customerId = HttpContext.Request.Cookies["customer"];

            // Attach payment method
            PaymentMethod paymentMethod;

            try
            {
                var options = new PaymentMethodAttachOptions
                {
                    Customer = customerId,
                };
                var service = new PaymentMethodService();
                paymentMethod = service.Attach(req.PaymentMethod, options);
            }
            catch (StripeException e)
            {
                return(BadRequest(new { error = new { message = e.Message } }));
            }

            // Create subscription
            var subscriptionOptions = new SubscriptionCreateOptions
            {
                DefaultPaymentMethod = paymentMethod.Id,
                Customer             = customerId,
                Items = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Price = Environment.GetEnvironmentVariable(req.Price.ToUpper()),
                    },
                },
            };

            subscriptionOptions.AddExpand("latest_invoice.payment_intent");
            var subscriptionService = new SubscriptionService();

            try
            {
                Subscription subscription = subscriptionService.Create(subscriptionOptions);

                return(new SubscriptionResponse
                {
                    Subscription = subscription
                });
            }
            catch (StripeException e)
            {
                Console.WriteLine($"Failed to create subscription.{e}");
                return(BadRequest());
            }
        }
Exemplo n.º 9
0
        private PaymentMethod AttachStripePaymentMethod(string customerId, string paymentMethodId)
        {
            StripeConfiguration.ApiKey = _appKeys.StripeApiKey;

            var options = new PaymentMethodAttachOptions
            {
                Customer = customerId,
            };
            var service       = new PaymentMethodService();
            var paymentMethod = service.Attach(
                paymentMethodId,
                options
                );

            return(paymentMethod);
        }
Exemplo n.º 10
0
        public bool AddCardToExistingCustomer(SetupIntent intent, string StripeCustomerID)
        {
            bool result = true;

            try
            {
                var options = new PaymentMethodAttachOptions
                {
                    Customer = StripeCustomerID,
                };
                var service       = new PaymentMethodService();
                var paymentMethod = service.Attach(intent.PaymentMethodId, options);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                result = false;
            }

            return(result);
        }
Exemplo n.º 11
0
        public static void AddNewPaymentOption(string cardNumber, int expiryMonth, int expiryYear, string cvc)
        {
            StripeConfiguration.ApiKey = Constants.StripeKey;
            var options = new PaymentMethodCreateOptions
            {
                Type = "card",
                Card = new PaymentMethodCardCreateOptions
                {
                    Number   = cardNumber,
                    ExpMonth = expiryMonth,
                    ExpYear  = expiryYear,
                    Cvc      = cvc
                }
            };
            var           service       = new PaymentMethodService();
            PaymentMethod pmMethod      = service.Create(options);
            var           attachOptions = new PaymentMethodAttachOptions
            {
                Customer = App.PaymentId
            };
            var attachService = new PaymentMethodService();

            attachService.Attach(pmMethod.Id, attachOptions);
        }
Exemplo n.º 12
0
        public static async Task <dynamic> CreateClientAsync(string email, string name, string cardNumber, int month, int year, string cvv)
        {
            var optionstoken = new TokenCreateOptions
            {
                Card = new CreditCardOptions
                {
                    Number   = cardNumber,
                    ExpMonth = month,
                    ExpYear  = year,
                    Cvc      = cvv
                }
            };

            var   servicetoken = new TokenService();
            Token stripetoken  = await servicetoken.CreateAsync(optionstoken);

            var customer = new CustomerCreateOptions
            {
                Email  = email,
                Name   = name,
                Source = stripetoken.Id,
            };

            Console.WriteLine(" stripetoken attributes :" + stripetoken);

            var services = new CustomerService();
            var created  = services.Create(customer);


            var option = new PaymentMethodCreateOptions
            {
                Type = "card",
                Card = new PaymentMethodCardCreateOptions
                {
                    Number   = cardNumber,
                    ExpMonth = month,
                    ExpYear  = year,
                    Cvc      = cvv,
                },
            };

            var service = new PaymentMethodService();
            var result  = service.Create(option);

            Console.WriteLine(" PaymentMethodService attributes :" + result);

            var options = new PaymentMethodAttachOptions
            {
                Customer = created.Id,
            };
            var method = new PaymentMethodService();

            method.Attach(
                result.Id,
                options
                );

            if (created.Id == null)
            {
                return("Failed");
            }
            else
            {
                return(created.Id);
            }
        }
        public ActionResult <Subscription> CreateSubscription([FromBody] CreateSubscriptionRequest req)
        {
            if (!ModelState.IsValid)
            {
                return(this.FailWithMessage("invalid params"));
            }
            var newPrice = Environment.GetEnvironmentVariable(req.Price.ToUpper());

            if (newPrice is null || newPrice == "")
            {
                return(this.FailWithMessage($"No price with the new price ID ({req.Price}) found in .env"));
            }

            // Attach payment method
            var options = new PaymentMethodAttachOptions
            {
                Customer = req.Customer,
            };
            var service = new PaymentMethodService();

            PaymentMethod paymentMethod;

            try
            {
                paymentMethod = service.Attach(req.PaymentMethod, options);
            }
            catch (Exception e)
            {
                return(this.FailWithMessage($"Failed to attach payment method {e}"));
            }

            // Update customer's default invoice payment method
            var customerOptions = new CustomerUpdateOptions
            {
                InvoiceSettings = new CustomerInvoiceSettingsOptions
                {
                    DefaultPaymentMethod = paymentMethod.Id,
                },
            };
            var customerService = new CustomerService();

            try
            {
                customerService.Update(req.Customer, customerOptions);
            }
            catch (StripeException e)
            {
                return(this.FailWithMessage($"Failed to attach payment method {e}"));
            }

            // Create subscription
            var subscriptionOptions = new SubscriptionCreateOptions
            {
                Customer = req.Customer,
                Items    = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Price    = Environment.GetEnvironmentVariable(req.Price),
                        Quantity = req.Quantity,
                    },
                },
            };

            subscriptionOptions.AddExpand("latest_invoice.payment_intent");
            var subscriptionService = new SubscriptionService();

            try
            {
                return(subscriptionService.Create(subscriptionOptions));
            }
            catch (StripeException e)
            {
                return(this.FailWithMessage($"Failed to attach payment method: {e}"));
            }
        }
Exemplo n.º 14
0
        protected Models.PaymentIntent UpdatePaymentIntent(string sessionId)
        {
            StripeConfiguration.ApiKey = ConfigurationManager.AppSettings["Cashier:Stripe:Secret"];
            var sessionService = new SessionService();
            var session        = sessionService.Get(sessionId);

            var setupIntentService = new SetupIntentService();
            var setupIntent        = setupIntentService.Get(session.SetupIntentId);

            var paymentIntent = PaymentService.GetPaymentIntentByTransactionRef(session.Metadata["TransactionRef"]);

            if (string.IsNullOrEmpty(setupIntent.PaymentMethodId))
            {
                paymentIntent.PaymentStatus = PaymentStatus.Failed;
                PaymentService.UpdatePaymentStatus(paymentIntent.TransactionReference, session.PaymentIntentId, PaymentStatus.Failed);
                return(paymentIntent);
            }

            var ddPriceName = $"Direct Debit - {paymentIntent.DirectDebitFrequencyInterval} {Enum.GetName(typeof(PaymentFrequencyUnit), paymentIntent.DirectDebitFrequencyUnit)}{(paymentIntent.DirectDebitFrequencyInterval > 1 ? "s" : "")} - {paymentIntent.Amount}";

            var productService = new ProductService();
            var product        = productService.List().FirstOrDefault(p => p.Description == "Direct Debit");

            if (product == null)
            {
                product = productService.Create(new ProductCreateOptions
                {
                    Name = ddPriceName,
                    Type = "service"
                });
            }

            var priceService = new PriceService();
            var price        = priceService.List().FirstOrDefault(p => p.Nickname == ddPriceName);

            if (price == null)
            {
                price = priceService.Create(new PriceCreateOptions
                {
                    Nickname   = ddPriceName,
                    Product    = product.Id,
                    UnitAmount = (long)paymentIntent.Amount * 100,
                    Currency   = paymentIntent.Currency,
                    Recurring  = new PriceRecurringOptions
                    {
                        Interval      = Enum.GetName(typeof(PaymentFrequencyUnit), paymentIntent.DirectDebitFrequencyUnit).ToLower(),
                        IntervalCount = paymentIntent.DirectDebitFrequencyInterval,
                        UsageType     = "licensed"
                    }
                });
            }

            var customerService = new CustomerService();
            var customer        = customerService.List().FirstOrDefault(c => c.Name == paymentIntent.CustomerUniqueReference);

            if (customer == null)
            {
                customer = customerService.Create(new CustomerCreateOptions
                {
                    Name          = paymentIntent.CustomerUniqueReference,
                    Description   = paymentIntent.CustomerUniqueReference,
                    PaymentMethod = setupIntent.PaymentMethodId,
                    Email         = paymentIntent.CustomerEmail,
                    Address       = new AddressOptions
                    {
                        Line1      = paymentIntent.CustomerAddressLines,
                        City       = paymentIntent.CustomerCity,
                        Country    = paymentIntent.CustomerCountry,
                        PostalCode = paymentIntent.CustomerPostcode
                    }
                });
            }
            else
            {
                var paymentMethodService = new PaymentMethodService();
                paymentMethodService.Attach(setupIntent.PaymentMethodId, new PaymentMethodAttachOptions
                {
                    Customer = customer.Id
                });
            }

            var subscriptionService = new SubscriptionService();
            var subscriptionCreate  = new SubscriptionCreateOptions
            {
                Customer             = customer.Id,
                DefaultPaymentMethod = setupIntent.PaymentMethodId,
                BillingCycleAnchor   = paymentIntent.DirectDebitStartDate,
                Items = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Price = price.Id
                    }
                }
            };

            if (paymentIntent.DirectDebitTrialDateEnd.HasValue)
            {
                //let the trial date specify the days that should not be charged
                subscriptionCreate.TrialEnd = paymentIntent.DirectDebitTrialDateEnd;
            }
            else
            {
                //otherwise let it start on the anchor date and disable proration
                subscriptionCreate.ProrationBehavior = "none";
            }
            var subscription = subscriptionService.Create(subscriptionCreate);

            paymentIntent.PaymentStatus = PaymentStatus.Succeeded;
            PaymentService.UpdatePaymentStatus(paymentIntent.TransactionReference, subscription.Id, PaymentStatus.Succeeded);

            return(paymentIntent);
        }