Exemplo n.º 1
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;
            }
        }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
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());
        }