Example #1
0
        public static TransactionResult CreateSessionRedirect(TransactionRequest request, StripeSettings stripeSettings,
                                                              ILogger logger, bool isSubscription)
        {
            var order = request.Order;

            InitStripe(stripeSettings);

            var address = DependencyResolver.Resolve <IDataSerializer>()
                          .DeserializeAs <Address>(order.BillingAddressSerialized);

            InitStripe(stripeSettings, true);
            //do we have a saved stripe customer id?
            var customerId = GetCustomerId(order.User, null, address);

            var subscriptionItems = new List <SessionSubscriptionDataItemOptions>();
            var productService    = new ProductService();
            var planService       = new PlanService();

            foreach (var orderItem in order.OrderItems)
            {
                var product = productService.Create(new ProductCreateOptions
                {
                    Name = orderItem.Product.Name,
                    Type = "service"
                });
                var lineTotal = orderItem.Price * orderItem.Quantity + orderItem.Tax;
                GetFinalAmountDetails(lineTotal, order.CurrencyCode, address, out var currencyCode, out var finalAmount);
                var planOptions = new PlanCreateOptions()
                {
                    Nickname        = product.Name,
                    Product         = product.Id,
                    Amount          = (long)finalAmount,
                    Interval        = GetInterval(orderItem.Product.SubscriptionCycle),
                    IntervalCount   = orderItem.Product.CycleCount == 0 ? 1 : orderItem.Product.CycleCount,
                    Currency        = currencyCode,
                    UsageType       = "licensed",
                    TrialPeriodDays = orderItem.Product.TrialDays
                };
                var plan = planService.Create(planOptions);
                subscriptionItems.Add(new SessionSubscriptionDataItemOptions()
                {
                    Plan     = plan.Id,
                    Quantity = orderItem.Quantity
                });
            }
            var options = new SessionCreateOptions
            {
                Customer           = customerId,
                PaymentMethodTypes = new List <string> {
                    "card",
                },
                SubscriptionData = new SessionSubscriptionDataOptions
                {
                    Items    = subscriptionItems,
                    Metadata = new Dictionary <string, string>()
                    {
                        { "orderGuid", order.Guid },
                        { "internalId", order.Id.ToString() },
                        { "isSubscription", isSubscription.ToString() }
                    }
                },
                SuccessUrl = ApplicationEngine.RouteUrl(StripeConfig.StripeReturnUrlRouteName, new { orderGuid = order.Guid }, true),
                CancelUrl  = ApplicationEngine.RouteUrl(StripeConfig.StripeCancelUrlRouteName, new { orderGuid = order.Guid }, true),
                Mode       = isSubscription ? "subscription" : "payment",
            };
            var service = new SessionService();
            var session = service.Create(options);
            var processPaymentResult = new TransactionResult()
            {
                OrderGuid = order.Guid,
            };

            if (session != null && !session.Id.IsNullEmptyOrWhiteSpace())
            {
                processPaymentResult.NewStatus = PaymentStatus.Processing;
                processPaymentResult.TransactionCurrencyCode = order.CurrencyCode;
                processPaymentResult.IsSubscription          = true;
                processPaymentResult.TransactionAmount       = order.OrderTotal;
                processPaymentResult.ResponseParameters      = new Dictionary <string, object>()
                {
                    { "sessionId", session.Id },
                    { "paymentIntentId", session.PaymentIntentId }
                };
                processPaymentResult.Success = true;
                processPaymentResult.Redirect(ApplicationEngine.RouteUrl(StripeConfig.StripeRedirectToUrlRouteName,
                                                                         new { orderGuid = order.Guid, sessionId = session.Id }));
            }
            else
            {
                processPaymentResult.Success = false;
                logger.Log <TransactionResult>(LogLevel.Warning, $"The session for Order#{order.Id} by stripe redirect failed." + session?.StripeResponse.Content);
            }

            return(processPaymentResult);
        }
Example #2
0
        public static TransactionResult CreateSubscription(TransactionRequest request, StripeSettings stripeSettings,
                                                           ILogger logger)
        {
            var order = request.Order;

            InitStripe(stripeSettings);
            var parameters = request.Parameters;

            parameters.TryGetValue("cardNumber", out var cardNumber);
            parameters.TryGetValue("cardName", out var cardName);
            parameters.TryGetValue("expireMonth", out var expireMonthStr);
            parameters.TryGetValue("expireYear", out var expireYearStr);
            parameters.TryGetValue("cvv", out var cvv);

            var paymentMethodService = new PaymentMethodService();
            var paymentMethod        = paymentMethodService.Create(new PaymentMethodCreateOptions()
            {
                Card = new PaymentMethodCardCreateOptions()
                {
                    Number   = cardNumber.ToString(),
                    ExpYear  = long.Parse(expireYearStr.ToString()),
                    ExpMonth = long.Parse(expireMonthStr.ToString()),
                    Cvc      = cvv.ToString()
                },
                Type = "card"
            });

            var address = DependencyResolver.Resolve <IDataSerializer>()
                          .DeserializeAs <Address>(order.BillingAddressSerialized);

            InitStripe(stripeSettings, true);
            //do we have a saved stripe customer id?
            var customerId        = GetCustomerId(order.User, paymentMethod, address);
            var subscriptionItems = new List <SubscriptionItemOptions>();
            var productService    = new ProductService();
            var planService       = new PlanService();


            foreach (var orderItem in order.OrderItems)
            {
                var product = productService.Create(new ProductCreateOptions
                {
                    Name = orderItem.Product.Name,
                    Type = "service"
                });
                var lineTotal = orderItem.Price * orderItem.Quantity + orderItem.Tax;
                GetFinalAmountDetails(lineTotal, order.CurrencyCode, address, out var currencyCode, out var finalAmount);
                var planOptions = new PlanCreateOptions()
                {
                    Nickname        = product.Name,
                    Product         = product.Id,
                    Amount          = (long)(finalAmount),
                    Interval        = GetInterval(orderItem.Product.SubscriptionCycle),
                    IntervalCount   = orderItem.Product.CycleCount == 0 ? 1 : orderItem.Product.CycleCount,
                    Currency        = currencyCode,
                    UsageType       = "licensed",
                    TrialPeriodDays = orderItem.Product.TrialDays
                };
                var plan = planService.Create(planOptions);
                subscriptionItems.Add(new SubscriptionItemOptions()
                {
                    Plan     = plan.Id,
                    Quantity = orderItem.Quantity
                });
            }
            //create a coupon if any
            var coupon = GetCoupon(order);
            var subscriptionOptions = new SubscriptionCreateOptions()
            {
                Customer = customerId,
                Items    = subscriptionItems,
                Metadata = new Dictionary <string, string>()
                {
                    { "orderGuid", order.Guid },
                    { "internalId", order.Id.ToString() },
                    { "isSubscription", bool.TrueString }
                },
                Coupon = coupon?.Id,

#if DEBUG
                TrialEnd = DateTime.UtcNow.AddMinutes(5)
#endif
            };

            subscriptionOptions.AddExpand("latest_invoice.payment_intent");

            var subscriptionService  = new SubscriptionService();
            var subscription         = subscriptionService.Create(subscriptionOptions);
            var processPaymentResult = new TransactionResult()
            {
                OrderGuid = order.Guid,
            };

            if (subscription.Status == "active" || subscription.Status == "trialing")
            {
                processPaymentResult.NewStatus = PaymentStatus.Complete;
                processPaymentResult.TransactionCurrencyCode = order.CurrencyCode;
                processPaymentResult.IsSubscription          = true;
                processPaymentResult.TransactionAmount       = (subscription.Plan.AmountDecimal / 100) ?? order.OrderTotal;
                processPaymentResult.ResponseParameters      = new Dictionary <string, object>()
                {
                    { "subscriptionId", subscription.Id },
                    { "invoiceId", subscription.LatestInvoiceId },
                    { "feePercent", subscription.ApplicationFeePercent },
                    { "collectionMethod", subscription.CollectionMethod },
                    { "metaInfo", subscription.Metadata }
                };
                processPaymentResult.Success = true;
            }
            else
            {
                processPaymentResult.Success = false;
                logger.Log <TransactionResult>(LogLevel.Warning, $"The subscription for Order#{order.Id} by stripe failed with status {subscription.Status}." + subscription.StripeResponse.Content);
            }

            return(processPaymentResult);
        }