public async Task <SetupIntent> CreateSetupIntent()
        {
            // Here we create a customer, then create a SetupIntent.
            // The SetupIntent is the object that keeps track of the
            // Customer's intent to allow saving their card details
            // so they can be charged later when the customer is no longer
            // on your site.

            // Create a customer
            var options  = new CustomerCreateOptions();
            var service  = new CustomerService();
            var customer = await service.CreateAsync(options);

            // Create a setup intent, and return the setup intent.
            var setupIntentOptions = new SetupIntentCreateOptions
            {
                Customer = customer.Id,
            };
            var setupIntentService = new SetupIntentService();

            // We're returning the full SetupIntent object here, but you could
            // also just return the ClientSecret for the newly created
            // SetupIntent as that's the only required data to confirm the
            // SetupIntent on the front end with Stripe.js.
            return(await setupIntentService.CreateAsync(setupIntentOptions));
        }
示例#2
0
        public JsonResult SetupCard()
        {
            var options = new SetupIntentCreateOptions {
            };
            var service = new SetupIntentService();
            var intent  = service.Create(options);

            return(Json(intent.ClientSecret, JsonRequestBehavior.AllowGet));
        }
        public ActionResult Render(string tr)
        {
            var paymentIntent = PaymentService.GetPaymentIntentByTransactionRef(tr);

            StripeConfiguration.ApiKey = ConfigurationManager.AppSettings["Cashier:Stripe:Secret"];

            string intentId           = "";
            string intentClientSecret = "";

            if (paymentIntent.MotoMode == true)
            {
                var serviceSI = new SetupIntentService();
                var setup     = serviceSI.Create(new SetupIntentCreateOptions
                {
                    PaymentMethodTypes = new List <string>
                    {
                        "card"
                    },
                    Metadata = new Dictionary <string, string>
                    {
                        { "TransactionReference", paymentIntent.TransactionReference }
                    }
                });
                intentId           = setup.Id;
                intentClientSecret = setup.ClientSecret;
            }
            else
            {
                var servicePI = new PaymentIntentService();
                var createPI  = new PaymentIntentCreateOptions
                {
                    Amount             = (long)paymentIntent.Amount * 100,
                    Currency           = paymentIntent.Currency,
                    PaymentMethodTypes = new List <string>
                    {
                        "card"
                    },
                    Description = paymentIntent.Description
                };
                createPI.Metadata = new Dictionary <string, string>
                {
                    { "TransactionReference", paymentIntent.TransactionReference }
                };
                var responsePI = servicePI.Create(createPI);
                intentId           = responsePI.Id;
                intentClientSecret = responsePI.ClientSecret;
            }

            ViewBag.PaymentIntent         = paymentIntent;
            ViewBag.TransactionReference  = paymentIntent.TransactionReference;
            ViewBag.ClientSecret          = intentClientSecret;
            ViewBag.StripePaymentIntentId = intentId;
            ViewBag.TestMode = ConfigurationManager.AppSettings["Cashier:Stripe:LiveMode"].ToLower() == "false";

            return(View("StripeCardPayment", CurrentPage));
        }
示例#4
0
        public SetupIntent CreateNewCard(string customerId, string userId)
        {
            var setupIntentService = new SetupIntentService();
            var intentOptions      = new SetupIntentCreateOptions
            {
                Customer = customerId
            };

            return(setupIntentService.Create(intentOptions));
        }
示例#5
0
        public async Task <string> PostSetupPayment()
        {
            var options = new SetupIntentCreateOptions
            {
                Usage = "off_session"
            };
            var service     = new SetupIntentService();
            var setupIntent = await service.CreateAsync(options);

            return(setupIntent.ClientSecret);
        }
示例#6
0
        public async Task <SetupIntent> CreateSetupIntent(string customerId)
        {
            var setupIntentOptions = new SetupIntentCreateOptions
            {
                Customer = customerId,
            };
            var setupIntentService = new SetupIntentService();
            var response           = await setupIntentService.CreateAsync(setupIntentOptions);

            return(response);
        }
示例#7
0
        public StripePaymentService(PaymentIntentService paymentIntentService, CustomerService customerService, PaymentMethodService paymentMethodService, SetupIntentService setupIntentService)
        {
            Guard.Argument(paymentIntentService, nameof(paymentIntentService)).NotNull();
            Guard.Argument(customerService, nameof(customerService)).NotNull();
            Guard.Argument(paymentMethodService, nameof(paymentMethodService)).NotNull();
            Guard.Argument(setupIntentService, nameof(setupIntentService)).NotNull();

            _paymentIntentService = paymentIntentService;
            _customerService      = customerService;
            _paymentMethodService = paymentMethodService;
            _setupIntentService   = setupIntentService;
        }
        public async Task <string> CreateClientSecretAsync()
        {
            var options = new SetupIntentCreateOptions {
                PaymentMethodTypes = new List <string> {
                    "card"
                }
            };

            var         service = new SetupIntentService();
            SetupIntent intent  = await service.CreateAsync(options);

            return(intent.ClientSecret);
        }
示例#9
0
        public ActionResult Index()
        {
            //TODO: need to save customer
            var options = new SetupIntentCreateOptions
            {
                Customer = createACustomer()
            };
            var service = new SetupIntentService();
            var intent  = service.Create(options);

            ViewData["ClientSecret"] = intent.ClientSecret;
            return(View());
        }
示例#10
0
        public async Task <IActionResult> RegisterCard(AppZeroAPI.Entities.Customer customer)
        {
            var customerId = customer.customer_id;
            var options    = new SetupIntentCreateOptions
            {
                Customer = customerId.ToString(),
            };
            var service      = new SetupIntentService();
            var intent       = service.Create(options);
            var clientSecret = intent.ClientSecret;
            var response     = await Task.FromResult(clientSecret);

            return(Ok(response));
        }
示例#11
0
        public ActionResult <Charge> ChargeCustomer(string sessionId)
        {
            try
            {
                // Retrieve Session

                var sessionService = new SessionService(_client);
                var session        = sessionService.Get("cs_test_c1FLnMmlumB6lwsmH0ZjgwA3F0VWfMy9idVRTysO5adsZMbCKxSti3wUx3");

                // Retrieve Customer

                var customerService = new CustomerService(_client);
                var customer        = customerService.Get(session.CustomerId);

                // Retrieve SetupIntent

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

                // Retrieve PaymentMethod

                var paymentMethodService = new PaymentMethodService(_client);
                var paymentMethod        = paymentMethodService.Get(setupIntent.PaymentMethodId);


                var paymentIntentOptions = new PaymentIntentCreateOptions
                {
                    Amount        = 2300,
                    Currency      = "usd",
                    Confirm       = true,
                    Customer      = customer.Id,
                    PaymentMethod = paymentMethod.Id
                };
                var paymentIntentService = new PaymentIntentService(_client);
                var intent = paymentIntentService.Create(paymentIntentOptions);



                return(Json(intent.ClientSecret));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        public SetupIntentServiceTest(
            StripeMockFixture stripeMockFixture,
            MockHttpClientFixture mockHttpClientFixture)
            : base(stripeMockFixture, mockHttpClientFixture)
        {
            this.service = new SetupIntentService(this.StripeClient);

            this.cancelOptions = new SetupIntentCancelOptions
            {
            };

            this.confirmOptions = new SetupIntentConfirmOptions
            {
            };

            this.createOptions = new SetupIntentCreateOptions
            {
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
            };

            this.listOptions = new SetupIntentListOptions
            {
                Limit = 1,
            };

            this.updateOptions = new SetupIntentUpdateOptions
            {
                Metadata = new Dictionary <string, string>
                {
                    { "key", "value" },
                },
            };
        }
示例#13
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);
        }
示例#14
0
        public async Task <IActionResult> Index()
        {
            Event stripeEvent = null;
            PaymentProviderEvent providerEvent = null;

            try
            {
                string json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
                stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], PaymentProviderConfig.TestWebhookSigningKey, 300L, false);

                providerEvent = new PaymentProviderEvent();
                providerEvent.ProviderType = (int)PaymentMethods.Stripe;
                providerEvent.RecievedOn   = DateTime.UtcNow;
                providerEvent.Data         = JsonConvert.SerializeObject(stripeEvent);
                providerEvent.Processed    = false;
                providerEvent.CustomerId   = "SYSTEM";
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
                return(BadRequest());
            }

            if (stripeEvent == null)
            {
                return(BadRequest());
            }

            try
            {
                switch (stripeEvent.Type)
                {
                case "charge.succeeded":
                    var succeededCharge = JsonConvert.DeserializeObject <Charge>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = succeededCharge.CustomerId;
                    providerEvent.Processed  = true;
                    providerEvent.Type       = typeof(Charge).FullName;

                    CqrsEvent stripeChargeSucceededEvent = new CqrsEvent();
                    stripeChargeSucceededEvent.Type = (int)CqrsEventTypes.StripeChargeSucceeded;
                    stripeChargeSucceededEvent.Data = stripeEvent.Data.RawObject.ToString();

#if !DEBUG
                    await _cqrsProvider.EnqueuePaymentEventAsync(stripeChargeSucceededEvent);
#else
                    await _paymentProviderService.ProcessStripePaymentAsync(succeededCharge);
#endif
                    break;

                case "charge.failed":
                    var failedCharge = JsonConvert.DeserializeObject <Charge>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = failedCharge.CustomerId;
                    providerEvent.Type       = typeof(Charge).FullName;

                    CqrsEvent stripeChargeFailedEvent = new CqrsEvent();
                    stripeChargeFailedEvent.Type = (int)CqrsEventTypes.StripeChargeFailed;
                    stripeChargeFailedEvent.Data = stripeEvent.Data.RawObject.ToString();

#if !DEBUG
                    await _cqrsProvider.EnqueuePaymentEventAsync(stripeChargeFailedEvent);
#else
                    await _paymentProviderService.ProcessStripeChargeFailedAsync(failedCharge);
#endif
                    break;

                case "charge.refunded":
                    var refundedCharge = JsonConvert.DeserializeObject <Charge>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = refundedCharge.CustomerId;
                    providerEvent.Type       = typeof(Charge).FullName;

                    CqrsEvent stripeChargeRefundedEvent = new CqrsEvent();
                    stripeChargeRefundedEvent.Type = (int)CqrsEventTypes.StripeChargeRefunded;
                    stripeChargeRefundedEvent.Data = stripeEvent.Data.RawObject.ToString();

#if !DEBUG
                    await _cqrsProvider.EnqueuePaymentEventAsync(stripeChargeRefundedEvent);
#else
                    await _paymentProviderService.ProcessStripeSubscriptionRefundAsync(refundedCharge);
#endif
                    break;

                case "customer.subscription.updated":
                    var updatedSubscription = JsonConvert.DeserializeObject <Subscription>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = updatedSubscription.CustomerId;
                    providerEvent.Processed  = true;
                    providerEvent.Type       = typeof(Subscription).FullName;

                    CqrsEvent stripeSubUpdatedEvent = new CqrsEvent();
                    stripeSubUpdatedEvent.Type = (int)CqrsEventTypes.StripeSubUpdated;
                    stripeSubUpdatedEvent.Data = stripeEvent.Data.RawObject.ToString();

#if !DEBUG
                    await _cqrsProvider.EnqueuePaymentEventAsync(stripeSubUpdatedEvent);
#else
                    await _paymentProviderService.ProcessStripeSubscriptionUpdateAsync(updatedSubscription);
#endif
                    break;

                case "customer.subscription.deleted":
                    var deletedSubscription = JsonConvert.DeserializeObject <Subscription>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = deletedSubscription.CustomerId;
                    providerEvent.Processed  = true;
                    providerEvent.Type       = typeof(Subscription).FullName;

                    CqrsEvent stripeSubDeletedEvent = new CqrsEvent();
                    stripeSubDeletedEvent.Type = (int)CqrsEventTypes.StripeSubDeleted;
                    stripeSubDeletedEvent.Data = stripeEvent.Data.RawObject.ToString();

#if !DEBUG
                    await _cqrsProvider.EnqueuePaymentEventAsync(stripeSubDeletedEvent);
#else
                    await _paymentProviderService.ProcessStripeSubscriptionCancellationAsync(deletedSubscription);
#endif

                    break;

                case "customer.subscription.created":
                    var createdSubscription = JsonConvert.DeserializeObject <Subscription>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = createdSubscription.CustomerId;
                    providerEvent.Type       = typeof(Subscription).FullName;
                    break;

                case "checkout.session.completed":
                    var session = JsonConvert.DeserializeObject <Session>(stripeEvent.Data.RawObject.ToString());
                    providerEvent.CustomerId = session.CustomerId;
                    providerEvent.Processed  = true;
                    providerEvent.Type       = typeof(Session).FullName;

                    CqrsEvent stripeSessionCompletedEvent = new CqrsEvent();
                    stripeSessionCompletedEvent.Type = (int)CqrsEventTypes.StripeCheckoutCompleted;
                    stripeSessionCompletedEvent.Data = stripeEvent.Data.RawObject.ToString();

                    if (!String.IsNullOrWhiteSpace(session.Mode) && session.Mode.ToLower() == "setup")
                    {
                        var service     = new SetupIntentService();
                        var setupIntent = service.Get(session.SetupIntentId);
                        providerEvent.CustomerId = setupIntent.Metadata["customer_id"];

                        stripeSessionCompletedEvent.Type = (int)CqrsEventTypes.StripeCheckoutUpdated;
#if !DEBUG
                        await _cqrsProvider.EnqueuePaymentEventAsync(stripeSessionCompletedEvent);
#else
                        await _paymentProviderService.ProcessStripeCheckoutUpdateAsync(session);
#endif
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
                Logging.SendExceptionEmail(ex, "StripeHandler");
                return(BadRequest());
            }
            finally
            {
                await _paymentProviderService.SaveEventAsync(providerEvent);
            }

            return(Ok());
        }