예제 #1
0
        public async Task <string> CreatePayment(MemberModel member, PaymentModel payment, string successUrl, string cancelUrl)
        {
            StripeConfiguration.ApiKey = payment.ApiSecretKey;

            var options = new SessionCreateOptions
            {
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Name        = payment.Title,
                        Description = payment.Description,
                        Amount      = (int)(payment.Amount * 100),
                        Currency    = payment.CurrencyCode,
                        Quantity    = 1
                    },
                },
                CustomerEmail = member.Email,
                SuccessUrl    = successUrl,
                CancelUrl     = cancelUrl
            };

            var     service = new SessionService();
            Session session = await service.CreateAsync(options);

            return(session.Id);
        }
예제 #2
0
        public async Task <BillingReference> CreateSession(Customer customer, string priceBillingId)
        {
            var opts = new SessionCreateOptions {
                PaymentMethodTypes = new List <string> {
                    "card"
                },
                Customer        = customer.BillingReference.BillingId,
                SetupIntentData = new SessionSetupIntentDataOptions()
                {
                    Metadata = new Dictionary <string, string> {
                        { "customer_id", customer.BillingReference.BillingId },
                    }
                },
                Mode       = "setup",
                SuccessUrl = config.SuccessUrl,
                CancelUrl  = config.CancelUrl
            };

            if (customer.Subscription != null)
            {
                opts.SetupIntentData.Metadata.Add("subscription_id", customer.Subscription.BillingReference.BillingId);
            }

            var session = await sessionService.CreateAsync(opts);

            return(BillingReference.CheckoutSession(session.Id));
        }
예제 #3
0
        async Task <string> IPaymentSessionFactory.CreateSubscriptionSession(string returnUrlBase, string customerId, IEnumerable <string> productIds, Dictionary <string, string> subscriptionMetadata)
        {
            var sessService            = new SessionService();
            var sessionCreationOptions = new SessionCreateOptions()
            {
                Customer  = customerId,
                Mode      = "subscription",
                LineItems = (from prod in productIds
                             select new SessionLineItemOptions()
                {
                    Price = prod,
                    Quantity = 1
                }).ToList(),
                SubscriptionData = new SessionSubscriptionDataOptions()
                {
                    Metadata = subscriptionMetadata
                },
                PaymentMethodTypes = new List <string>()
                {
                    "card"
                },
                SuccessUrl = returnUrlBase + "?result=success&session_id={CHECKOUT_SESSION_ID}",
                CancelUrl  = returnUrlBase + "?result=cancel"
            };

            var session = await sessService.CreateAsync(sessionCreationOptions);

            return(session.Id);
        }
        public async Task <CreateSessionResult> Handle(CreateSessionRequest request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var options = new SessionCreateOptions
            {
                PaymentMethodTypes = _options.Value.PaymentMethodTypes,
                SubscriptionData   = new SessionSubscriptionDataOptions
                {
                    Items = new List <SessionSubscriptionDataItemOptions>
                    {
                        new SessionSubscriptionDataItemOptions
                        {
                            Plan = request.Model.PlanId
                        }
                    },
                    DefaultTaxRates = _options.Value.TaxIds
                },
                SuccessUrl = "https://example.com/success?session_id={CHECKOUT_SESSION_ID}",
                CancelUrl  = "https://example.com/cancel"
            };
            var session = await _sessionService.CreateAsync(options, null, cancellationToken);

            CreateSessionResult result = new CreateSessionResult(session);

            return(result);
        }
        public async Task <IActionResult> CreateCheckoutSession()
        {
            // Create new Checkout Session for the order
            // Other optional params include:
            //  [billing_address_collection] - to display billing address details on the page
            //  [customer] - if you have an existing Stripe Customer ID
            //  [customer_email] - lets you prefill the email input in the form
            //  [automatic_tax] - to automatically calculate sales tax, VAT and GST in the checkout page
            //  For full details see https:#stripe.com/docs/api/checkout/sessions/create

            //  ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
            var options = new SessionCreateOptions
            {
                SuccessUrl = $"{this.options.Value.Domain}/success.html?session_id={{CHECKOUT_SESSION_ID}}",
                CancelUrl  = $"{this.options.Value.Domain}/canceled.html",
                Mode       = "payment",
                LineItems  = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Quantity = long.Parse(Request.Form["quantity"]),
                        Price    = this.options.Value.Price,
                    },
                },
                // AutomaticTax = new SessionAutomaticTaxOptions { Enabled = true },
            };

            var service = new SessionService(this.client);
            var session = await service.CreateAsync(options);

            Response.Headers.Add("Location", session.Url);
            return(new StatusCodeResult(303));
        }
예제 #6
0
        public async Task <string> CreateSession(List <StoreModel.Checkout.OrderItem> orderItems)
        {
            var options = new SessionCreateOptions
            {
                PaymentMethodTypes = new List <string> {
                    "card",
                },
                LineItems = new List <SessionLineItemOptions> {
                    new SessionLineItemOptions {
                        Name        = "T-shirt",
                        Description = "Comfortable cotton t-shirt",
                        Amount      = 500,
                        Currency    = "usd",
                        Quantity    = 1,
                    },
                },
                SuccessUrl = "https://example.com/success?session_id={CHECKOUT_SESSION_ID}",
                CancelUrl  = "https://example.com/cancel",
            };

            var service = new SessionService();

            Session session = await service.CreateAsync(options).ConfigureAwait(false);

            return(session.Id);
        }
예제 #7
0
        public async Task <Session> CreateSessionAsync(string customerId, string accountId, string itemName, string itemDescription, decimal amount, decimal applicationFee, string successUrl, string cancelUrl)
        {
            var options = new SessionCreateOptions
            {
                Customer           = customerId,
                PaymentMethodTypes = new List <string> {
                    "card",
                },
                LineItems = new List <SessionLineItemOptions> {
                    new SessionLineItemOptions {
                        Name        = itemName,
                        Description = itemDescription,
                        Amount      = (long)(amount * 100),
                        Currency    = "usd",
                        Quantity    = 1,
                    },
                },
                PaymentIntentData = new SessionPaymentIntentDataOptions
                {
                    Description          = itemName,
                    SetupFutureUsage     = "off_session",
                    ApplicationFeeAmount = (long)(applicationFee * 100),
                    //TransferData = new Stripe.Checkout.SessionPaymentIntentDataOptions
                    //{
                    //    Destination = accountId,
                    //}
                },
                SuccessUrl = successUrl,
                CancelUrl  = cancelUrl
            };

            var service = new  SessionService();

            return(await service.CreateAsync(options));
        }
        public async Task<CreateCheckoutSessionResponse> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            // Create new Checkout Session for the order
            // Other optional params include:
            //  [billing_address_collection] - to display billing address details on the page
            //  [customer] - if you have an existing Stripe Customer ID
            //  [customer_email] - lets you prefill the email input in the form
            //  For full details see https:#stripe.com/docs/api/checkout/sessions/create

            //  ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
            var options = new SessionCreateOptions
            {
                SuccessUrl = $"{this.options.Value.Domain}/success.html?session_id={{CHECKOUT_SESSION_ID}}",
                CancelUrl = $"{this.options.Value.Domain}/canceled.html",
                PaymentMethodTypes = new List<string> { "card" },
                Mode = "payment",
                LineItems = new List<SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Quantity = req.Quantity,
                        Price = this.options.Value.Price,
                    },
                },
            };

            var service = new SessionService(this.client);
            var session = await service.CreateAsync(options);

            return new CreateCheckoutSessionResponse
            {
                SessionId = session.Id,
            };
        }
예제 #9
0
        public async Task <IActionResult> Get()
        {
            StripeConfiguration.ApiKey = "sk_test_very_secret_should_come_from_azure_key_vault"; //Get it from your stripe dashboard

            var options = new SessionCreateOptions
            {
                PaymentMethodTypes = new List <string>
                {
                    "card",
                    "ideal"
                },
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Name        = $"Pants with 3 legs",
                        Description = $"Pants for those who have 3 legs",
                        Amount      = 100, // 1 euro
                        Currency    = "eur",
                        Quantity    = 1
                    }
                },
                SuccessUrl = "https://localhost:5001/success?session_id={CHECKOUT_SESSION_ID}",
                CancelUrl  = "https://localhost:5001/failed"
            };

            var     service = new SessionService();
            Session session = await service.CreateAsync(options);

            return(Ok(session.Id));
        }
예제 #10
0
        public async Task <string> CreatePaymentSession(StripeCreatePaymentSessionInput input)
        {
            var payment = await _subscriptionPaymentRepository.GetAsync(input.PaymentId);

            var paymentTypes         = _stripePaymentGatewayConfiguration.PaymentMethodTypes;
            var sessionCreateOptions = new SessionCreateOptions
            {
                PaymentMethodTypes = paymentTypes,
                SuccessUrl         = input.SuccessUrl + (input.SuccessUrl.Contains("?") ? "&" : "?") +
                                     "sessionId={CHECKOUT_SESSION_ID}",
                CancelUrl = input.CancelUrl
            };

            if (payment.IsRecurring && !payment.IsProrationPayment())
            {
                var plan = await _stripeGatewayManager.GetOrCreatePlanForPayment(input.PaymentId);

                sessionCreateOptions.SubscriptionData = new SessionSubscriptionDataOptions
                {
                    Items = new List <SessionSubscriptionDataItemOptions>
                    {
                        new SessionSubscriptionDataItemOptions
                        {
                            Plan = plan.Id,
                        }
                    }
                };
            }
            else
            {
                sessionCreateOptions.LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Amount      = (long)_stripeGatewayManager.ConvertToStripePrice(payment.Amount),
                        Name        = StripeGatewayManager.ProductName,
                        Currency    = LDIConsts.Currency,
                        Description = payment.Description,
                        Quantity    = 1
                    }
                };
            }

            var service = new SessionService();
            var session = await service.CreateAsync(sessionCreateOptions);

            await _subscriptionPaymentExtensionDataRepository.SetExtensionDataAsync(
                payment.Id,
                StripeGatewayManager.StripeSessionIdSubscriptionPaymentExtensionDataKey,
                session.Id
                );

            return(session.Id);
        }
예제 #11
0
        public async Task <IActionResult> Create(StripePaymentDTO payment)
        {
            try
            {
                var domain = _config.GetValue <string>("HiddenVilla_Client_URL");

                var options = new SessionCreateOptions
                {
                    PaymentMethodTypes = new List <string>
                    {
                        "card"
                    },
                    LineItems = new List <SessionLineItemOptions>
                    {
                        new SessionLineItemOptions
                        {
                            PriceData = new SessionLineItemPriceDataOptions
                            {
                                UnitAmount  = payment.Amount, // convert to cent
                                Currency    = "usd",
                                ProductData = new SessionLineItemPriceDataProductDataOptions
                                {
                                    Name = payment.ProductName
                                }
                            },
                            Quantity = 1
                        }
                    },
                    Mode       = "payment",
                    SuccessUrl = domain + "/success-payment?session_id={{CHECKOUT_SESSION_ID}}",
                    CancelUrl  = domain + payment.ReturnUrl
                };

                var     service = new SessionService();
                Session session = await service.CreateAsync(options);

                return(Ok(new SuccessModel()
                {
                    Data = session.Id
                }));
            }
            catch (Exception e)
            {
                return(BadRequest(new ErrorModel()
                {
                    ErrorMessage = e.Message
                }));
            }


            return(View());
        }
        public async Task <IActionResult> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            // This ID is typically stored with the authenticated user in your database. For
            // demonstration purposes, we're pulling this value from environment variables.
            //
            // Note this is not required to create a Subscription, but demonstrates how you would
            // create a new Subscription using Stripe Checkout with an existing user.
            var stripeCustomerId = this.options.Value.Customer;

            var options = new SessionCreateOptions
            {
                SuccessUrl         = $"{this.options.Value.Domain}/success.html?session_id={{CHECKOUT_SESSION_ID}}",
                CancelUrl          = $"{this.options.Value.Domain}/cancel.html",
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                Mode      = "subscription",
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Price    = req.PriceId,
                        Quantity = 1,
                    },
                },
                Customer = stripeCustomerId,
            };
            var service = new SessionService(this.client);

            try
            {
                var session = await service.CreateAsync(options);

                return(Ok(new CreateCheckoutSessionResponse
                {
                    SessionId = session.Id,
                }));
            }
            catch (StripeException e)
            {
                Console.WriteLine(e.StripeError.Message);
                return(BadRequest(new ErrorResponse
                {
                    ErrorMessage = new ErrorMessage
                    {
                        Message = e.StripeError.Message,
                    }
                }));
            }
        }
        public async Task <IActionResult> Create(StripePaymentDTO payment)
        {
            try
            {
                var domain = _configuration.GetValue <string>("HiddenVilla_Client_URL");
                if (HotelAssignment2_API.Startup._Env.ToLower() == "Development".ToLower())
                {
                    domain = _configuration.GetValue <string>("HiddenVilla_Client_URL_Local");
                }
                var option = new SessionCreateOptions
                {
                    PaymentMethodTypes = new List <string>
                    {
                        "card"
                    }
                    , LineItems = new List <SessionLineItemOptions>
                    {
                        new SessionLineItemOptions
                        {
                            PriceData = new SessionLineItemPriceDataOptions
                            {
                                UnitAmount    = payment.Amount
                                , Currency    = "USD"
                                , ProductData = new SessionLineItemPriceDataProductDataOptions
                                {
                                    Name = payment.ProductName
                                }
                            }
                            , Quantity = 1
                        }
                    }
                    , Mode       = "payment"
                    , SuccessUrl = domain + "/success-payment?session_id={{CHECKOUT_SESSION_ID}}" //stripe return session id. automacally populates {{}} field
                    , CancelUrl  = domain + payment.ReturnUrl
                };

                var     service = new SessionService();
                Session session = await service.CreateAsync(option);

                return(Ok(new SuccessModel()
                {
                    Data = session.Id
                }));
            }catch (Exception e)
            {
                return(BadRequest(new ErrorModel()
                {
                    ErrorMessage = e.Message
                }));
            }
        }
        public async Task <CustomerPortalSessionResponseDto> CreateAsync(string stripeCustomerId)
        {
            var options = new SessionCreateOptions
            {
                Customer  = stripeCustomerId,
                ReturnUrl = $"{_stripeOptions.Domain}/login",
            };

            var session = await _sessionService.CreateAsync(options);

            return(new CustomerPortalSessionResponseDto()
            {
                Url = session.Url,
            });
        }
        public async Task <IActionResult> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            var options = new SessionCreateOptions
            {
                // See https://stripe.com/docs/api/checkout/sessions/create
                // for additional parameters to pass.
                // {CHECKOUT_SESSION_ID} is a string literal; do not change it!
                // the actual Session ID is returned in the query parameter when your customer
                // is redirected to the success page.
                SuccessUrl         = "https://example.com/success.html?session_id={CHECKOUT_SESSION_ID}",
                CancelUrl          = "/checkout",
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                Mode      = "subscription",
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Price = req.PriceId,
                        // For metered billing, do not pass quantity
                        Quantity = 1,
                    },
                },
            };

            try
            {
                var session = await _sessionService.CreateAsync(options);

                return(Ok(new CreateCheckoutSessionResponse
                {
                    SessionId = session.Id,
                }));
            }
            catch (StripeException e)
            {
                _logger.LogInformation(e.StripeError.Message);
                return(BadRequest(new ErrorResponse
                {
                    ErrorMessage = new ErrorMessage
                    {
                        Message = e.StripeError.Message,
                    }
                }));
            }
        }
예제 #16
0
        public async Task <Session> CreateCheckoutSession(string customerId, string successUrl, string cancelUrl)
        {
            var options = new SessionCreateOptions {
                PaymentMethodTypes = new List <string> {
                    "card",
                },
                Mode       = "setup",
                Customer   = customerId,
                SuccessUrl = successUrl,
                CancelUrl  = cancelUrl,
            };

            var service = new SessionService();

            return(await service.CreateAsync(options));
        }
예제 #17
0
        public async Task <IActionResult> GetSessionAsync()
        {
            var options = new SessionCreateOptions
            {
                PaymentMethodTypes = new List <string> {
                    "card",
                },
                Mode       = "setup",
                SuccessUrl = "http://localhost:3000/success?session_id={CHECKOUT_SESSION_ID}",
                CancelUrl  = "http://localhost:3000/cancel",
            };

            var service = new SessionService();
            var session = await service.CreateAsync(options);

            return(Ok(session));
        }
        public async Task <IActionResult> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            var options = new SessionCreateOptions
            {
                SuccessUrl         = req.SuccessUrl,
                CancelUrl          = req.FailureUrl,
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                Mode      = "subscription",
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Price    = req.PriceId,
                        Quantity = 1,
                    },
                },
            };

            var service = new SessionService();

            service.Create(options);
            try
            {
                var session = await service.CreateAsync(options);

                return(Ok(new CreateCheckoutSessionResponse
                {
                    SessionId = session.Id,
                    PublicKey = _stripeSettings.PublicKey
                }));
            }
            catch (StripeException e)
            {
                Console.WriteLine(e.StripeError.Message);
                return(BadRequest(new ErrorResponse
                {
                    ErrorMessage = new ErrorMessage
                    {
                        Message = e.StripeError.Message,
                    }
                }));
            }
        }
예제 #19
0
        public async Task <IActionResult> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            Debug.WriteLine("path " + Request.Host);
            var options = new SessionCreateOptions
            {
                SuccessUrl         = $"https://{Request.Host}/home/success?session_id={{CHECKOUT_SESSION_ID}}",
                CancelUrl          = $"https://{Request.Host}/cancel.html",
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                Mode          = "subscription",
                CustomerEmail = User.Identity.Name,
                LineItems     = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Price    = req.PriceId,
                        Quantity = 1,
                    },
                },
            };
            var service = new SessionService(this.client);

            try
            {
                var session = await service.CreateAsync(options);

                return(Ok(new CreateCheckoutSessionResponse
                {
                    SessionId = session.Id,
                }));
            }
            catch (StripeException e)
            {
                Console.WriteLine(e.StripeError.Message);
                return(BadRequest(new ErrorResponse
                {
                    ErrorMessage = new ErrorMessage
                    {
                        Message = e.StripeError.Message,
                    }
                }));
            }
        }
예제 #20
0
        public async Task CreateAsync_SessionValidationSucceed_CreatesLoyaltyCard()
        {
            // Arrange
            var session  = new SessionUpdateModel();
            var expected = new Session();

            var sessionDAL = new Mock <ISessionDAL>();

            sessionDAL.Setup(x => x.InsertAsync(session)).ReturnsAsync(expected);

            var sessionService = new SessionService(sessionDAL.Object);

            // Act
            var result = await sessionService.CreateAsync(session);

            // Assert
            result.Should().Be(expected);
        }
예제 #21
0
        public async Task <IActionResult> GetSessionAsync()
        {
            StripeConfiguration.ApiKey = "sk_test_p9SPI9sPLAegWEXL6fZ5MIDm009gl2HLo5";

            var options = new SessionCreateOptions {
                PaymentMethodTypes = new List <string> {
                    "card",
                },
                Mode       = "setup",
                SuccessUrl = "http://localhost:3000/success?session_id={CHECKOUT_SESSION_ID}",
                CancelUrl  = "http://localhost:3000/cancel",
            };

            var service = new SessionService();
            var session = await service.CreateAsync(options);

            return(Ok(session));
        }
예제 #22
0
        private async Task <ActionResult> PayWithStripeCheckout(Sjop.Models.Order order)
        {
            // Read Stripe API key from config
            StripeConfiguration.ApiKey = _stripeSettings.SecretKey;

            // Add orderlines to Checkout session
            var lines = new List <SessionLineItemOptions>();

            foreach (var ol in order.OrderLines)
            {
                _logger.LogInformation($"linjepris: {ol.TotalPrice}");
                var newline = new SessionLineItemOptions
                {
                    Name        = ol.ProductName,
                    Description = ol.ProductDescription,
                    Amount      = Convert.ToInt64(ol.TotalPrice * 100),
                    Currency    = "nok",
                    Quantity    = ol.Quantity
                };
                lines.Add(newline);
            }
            var options = new SessionCreateOptions
            {
                ClientReferenceId  = order.Id.ToString(),
                CustomerEmail      = order.Customer.Email,
                Locale             = "nb",
                PaymentMethodTypes = new List <string> {
                    "card",
                },
                LineItems  = lines,
                SuccessUrl = _site.BaseUrl + "/PaymentSuccess?session_id={CHECKOUT_SESSION_ID}",
                CancelUrl  = _site.BaseUrl + "/PaymentFailed",
            };

            var     service = new SessionService();
            Session session = await service.CreateAsync(options);

            order.PaymentProviderSessionId = session.Id;
            _context.Update(order);
            await _context.SaveChangesAsync();

            return(Ok(session));
        }
예제 #23
0
        public async Task <IActionResult> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            var options = new SessionCreateOptions
            {
                SuccessUrl         = $"{this.options.Value.Domain}/Home/Success?session_id={{CHECKOUT_SESSION_ID}}",
                CancelUrl          = $"{this.options.Value.Domain}/Home/Index",
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                Mode      = "subscription",
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Price    = req.PriceId,
                        Quantity = 1,
                    },
                },
            };
            var service = new SessionService(this.client);

            try
            {
                var session = await service.CreateAsync(options);

                return(Ok(new CreateCheckoutSessionResponse
                {
                    SessionId = session.Id,
                }));
            }
            catch (StripeException e)
            {
                Console.WriteLine(e.StripeError.Message);
                return(BadRequest(new ErrorResponse
                {
                    ErrorMessage = new ErrorMessage
                    {
                        Message = e.StripeError.Message,
                    }
                }));
            }
        }
예제 #24
0
        public async Task <CreateCheckoutSessionResponse> CreateCheckoutSession()
        {
            // Pulled from environment variables in the `.env` file. In practice,
            // users often hard code this list of strings representing the types of
            // payment methods that are accepted.
            List <string> paymentMethodTypes = this.options.Value.PaymentMethodTypes;

            // Create new Checkout Session for the order
            // Other optional params include:
            //  [billing_address_collection] - to display billing address details on the page
            //  [customer] - if you have an existing Stripe Customer ID
            //  [customer_email] - lets you prefill the email input in the form
            //  For full details see https:#stripe.com/docs/api/checkout/sessions/create

            //  ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
            var options = new SessionCreateOptions
            {
                SuccessUrl         = $"{this.options.Value.Domain}/success.html?session_id={{CHECKOUT_SESSION_ID}}",
                CancelUrl          = $"{this.options.Value.Domain}/canceled.html",
                PaymentMethodTypes = paymentMethodTypes,
                Mode      = "payment",
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Quantity = 1,
                        Price    = this.options.Value.Price,
                    },
                },
            };

            var service = new SessionService(this.client);
            var session = await service.CreateAsync(options);

            return(new CreateCheckoutSessionResponse
            {
                SessionId = session.Id,
            });
        }
        public async Task <IActionResult> CreateCheckoutSession()
        {
            var options = new SessionCreateOptions
            {
                SuccessUrl = $"{this.options.Value.Domain}/success.html?session_id={{CHECKOUT_SESSION_ID}}",
                CancelUrl  = $"{this.options.Value.Domain}/canceled.html",
                Mode       = "subscription",
                LineItems  = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Price    = Request.Form["priceId"],
                        Quantity = 1,
                    },
                },
                // AutomaticTax = new SessionAutomaticTaxOptions { Enabled = true },
            };
            var service = new SessionService(this.client);

            try
            {
                var session = await service.CreateAsync(options);

                Response.Headers.Add("Location", session.Url);
                return(new StatusCodeResult(303));
            }
            catch (StripeException e)
            {
                Console.WriteLine(e.StripeError.Message);
                return(BadRequest(new ErrorResponse
                {
                    ErrorMessage = new ErrorMessage
                    {
                        Message = e.StripeError.Message,
                    }
                }));
            }
        }
예제 #26
0
        private async Task <ActionResult> PayWithStripeCheckout([FromBody] CustomerOrder order)
        {
            StripeConfiguration.ApiKey = StripeOptions.SecretKey;
            var lines = new List <SessionLineItemOptions>();

            foreach (var ol in order.orderItems)
            {
                var newline = new SessionLineItemOptions
                {
                    Name        = ol.Product.name,
                    Description = ol.Product.description,
                    Amount      = Convert.ToInt64(ol.total_payable),
                    Currency    = "usd",
                    Quantity    = ol.qty
                };
                lines.Add(newline);
            }
            var options = new SessionCreateOptions
            {
                ClientReferenceId  = order.order_id.ToString(),
                CustomerEmail      = order.customer.email,
                Locale             = "nb",
                PaymentMethodTypes = new List <string> {
                    "card",
                },
                LineItems  = lines,
                SuccessUrl = SiteBaseUrl + "/PaymentSuccess?session_id={CHECKOUT_SESSION_ID}",
                CancelUrl  = SiteBaseUrl + "/PaymentFailed",
            };

            var     service = new SessionService();
            Session session = await service.CreateAsync(options);

            order.PaymentProviderSessionId = session.Id;
            //_context.Update(order);
            //await _context.SaveChangesAsync();
            return(Ok(session));
        }
예제 #27
0
        public async Task <IActionResult> BuyAsync()
        {
            var options = new SessionCreateOptions
            {
                PaymentIntentData = new SessionPaymentIntentDataOptions
                {
                    CaptureMethod    = "manual",
                    SetupFutureUsage = "off_session",
                    ReceiptEmail     = "*****@*****.**",
                    Metadata         = new Dictionary <string, string>()
                    {
                        { "integration_check", "accept_a_payment" },
                        { "OrderId", "6735" },
                    }
                },
                Customer           = "cus_IJVSPOCEsKPVJW",
                PaymentMethodTypes = new List <string> {
                    "card",
                },
                LineItems = new List <SessionLineItemOptions> {
                    new SessionLineItemOptions {
                        Name        = "T-shirt",
                        Description = "Comfortable cotton t-shirt",
                        Amount      = 500,
                        Currency    = "usd",
                        Quantity    = 1,
                    },
                }
                ,
                SuccessUrl = "https://example.com/success",
                CancelUrl  = "https://example.com/cancel",
            };

            var     service = new SessionService();
            Session session = await service.CreateAsync(options);

            return(Ok(session));
        }
예제 #28
0
        public async Task <Session> CreateCheckoutSessionForCustomerAsync(string planId, string customerId, string cancelUrl = "")
        {
            var baseUrl = string.IsNullOrEmpty(cancelUrl) ? _appSettings.BaseUrl : cancelUrl;

            var options = new SessionCreateOptions
            {
                Customer           = customerId,
                PaymentMethodTypes = new List <string> {
                    "card"
                },
                SubscriptionData = new SessionSubscriptionDataOptions
                {
                    Items = new List <SessionSubscriptionDataItemOptions> {
                        new SessionSubscriptionDataItemOptions {
                            Plan = planId,
                        }
                    }
                },
                SuccessUrl = _settings.CheckoutSuccessRedirectUrl,
                CancelUrl  = baseUrl
            };

            return(await _sessionService.CreateAsync(options));
        }
예제 #29
0
        public Task <ResultWrapper <CustomerCreatePaymentSessionOutput> > Handle(CustomerCreatePaymentSessionCommand request, CancellationToken cancellationToken)
        {
            ResultWrapper <CustomerCreatePaymentSessionOutput> result = new ResultWrapper <CustomerCreatePaymentSessionOutput>();

            try
            {
                using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    TUser tUser = _dbContext.TUser.FirstOrDefault(x => x.FireBaseId == request.firebaseId);
                    if (tUser == null)
                    {
                        result.Status  = false;
                        result.Message = "cannot find customer!";
                        return(Task.FromResult(result));
                    }

                    if (!request.OrderItems.Any())
                    {
                        result.Status  = false;
                        result.Message = "invalid foods data!";
                        return(Task.FromResult(result));
                    }

                    TUser tSupplier = _dbContext.TFood
                                      .Include(x => x.TUser)
                                      .FirstOrDefault(x => x.Id == request.OrderItems.First().FoodId)?.TUser;
                    if (tSupplier == null)
                    {
                        result.Status  = false;
                        result.Message = "cannot find supplier!";
                        return(Task.FromResult(result));
                    }

                    string generatedCode   = "";
                    string generatedTitle  = "";
                    Guid   PaymentUniqueId = Guid.NewGuid();

                    TOrder tOrder = new TOrder()
                    {
                        Enabled           = true,
                        Code              = generatedCode,
                        Created           = DateTime.Now,
                        Date              = DateTime.Now,
                        Title             = generatedTitle,
                        TrackingCode      = PaymentUniqueId.ToString(),
                        TSupplierId       = tSupplier.Id,
                        TUserId           = tUser.Id,
                        TotalPayablePrice = 0,
                        Submited          = false
                    };
                    _dbContext.TOrder.Add(tOrder);
                    _dbContext.SaveChanges();

                    decimal TotalPayablePrice = 0;
                    foreach (var detail in request.OrderItems)
                    {
                        TFood food = _dbContext.TFood
                                     .FirstOrDefault(x => x.Id == detail.FoodId);

                        if (food == null)
                        {
                            result.Status  = false;
                            result.Message = "invalid food data!";
                            return(Task.FromResult(result));
                        }
                        TOrderDetail tOrderDetail = new TOrderDetail()
                        {
                            Enabled   = true,
                            Created   = DateTime.Now,
                            Amount    = detail.Amount,
                            TFoodId   = food.Id,
                            TUserId   = tSupplier.Id,
                            UnitPrice = food.Price,
                            RowPrice  = food.Price * detail.Amount,
                            TOrderId  = tOrder.Id
                        };
                        TotalPayablePrice += tOrderDetail.RowPrice;
                        _dbContext.TOrderDetail.Add(tOrderDetail);
                    }
                    _dbContext.SaveChanges();

                    tOrder.TotalPayablePrice = TotalPayablePrice;
                    _dbContext.TOrder.Update(tOrder);
                    _dbContext.SaveChanges();

                    string   SuccessUrl = request.SuccessUrl + "?UID=" + PaymentUniqueId;
                    TPayment tPayment   = new TPayment()
                    {
                        UniqueId = PaymentUniqueId,
                        UserId   = tUser.Id,
                        Amount   = TotalPayablePrice,
                        OrderId  = tOrder.Id,
                        Success  = false,
                        Used     = false,
                        Enabled  = true,
                        Created  = DateTime.Now,
                    };
                    _dbContext.TPayment.Add(tPayment);
                    _dbContext.SaveChanges();

                    transaction.Complete();

                    string secretKey = "sk_test_51JKejjB9j2pHQUNgVymkcotBwOhw64UhTOxrOWLn6QzpdIqmUOGh0lJCkozGMgWNLYQcg4XKriYmiNjfDRiwujnV00Lv2iKYgC";
                    StripeConfiguration.ApiKey = secretKey;
                    var options = new SessionCreateOptions()
                    {
                        PaymentMethodTypes = new List <String>()
                        {
                            "card"
                        },
                        LineItems = new List <SessionLineItemOptions>()
                        {
                        },
                        PaymentIntentData = new SessionPaymentIntentDataOptions()
                        {
                            ApplicationFeeAmount = 500,
                            TransferData         = new SessionPaymentIntentDataTransferDataOptions()
                            {
                                Destination = "acct_1JL9JuPUzKlkrnDH"
                            }
                        },
                        Mode       = "payment",
                        SuccessUrl = SuccessUrl,
                        CancelUrl  = request.CancelUrl
                    };
                    foreach (var item in request.OrderItems)
                    {
                        options.LineItems.Add(new SessionLineItemOptions()
                        {
                            Quantity  = item.Amount,
                            PriceData = new SessionLineItemPriceDataOptions()
                            {
                                Currency    = "usd",
                                UnitAmount  = item.Price,
                                ProductData = new SessionLineItemPriceDataProductDataOptions()
                                {
                                    Name = item.FoodId.ToString()
                                }
                            }
                        });
                    }
                    var            service = new SessionService();
                    Task <Session> session = service.CreateAsync(options);
                    session.Wait();
                    result = new ResultWrapper <CustomerCreatePaymentSessionOutput>()
                    {
                        Status = true,
                        Result = new CustomerCreatePaymentSessionOutput()
                        {
                            SessionId  = session.Result.Id,
                            SessionUrl = session.Result.Url
                        }
                    };
                }
            }
            catch (Exception ex)
            {
                result.Status  = false;
                result.Message = ex.Message;
            }
            return(Task.FromResult(result));
        }
예제 #30
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "inschrijving")] HttpRequest req,
            [CosmosDB(
                 databaseName: "sinterklaas",
                 collectionName: "inschrijvingen",
                 ConnectionStringSetting = "CosmosDBConnection")] IAsyncCollector <InschrijvingDataModel> inschrijvingenOut,
            ILogger log, ExecutionContext context)
        {
            try {
                log.LogInformation($"Add inschrijving triggered");

                var config = new ConfigurationBuilder().SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                log.LogInformation($"Deserializing inschrijving {requestBody}");

                var inschrijving = JsonConvert.DeserializeObject <InschrijvingViewModel>(requestBody);
                log.LogInformation($"Inschrijving deserialized for {inschrijving.Naam}");

                StripeConfiguration.ApiKey = config["Stripe:SecretKey"];

                var lineItems = CreateLineItemsFromInschrijving(inschrijving, log);

                log.LogInformation($"{lineItems.Count()} line items created");

                var frontendUrl = config["FrontendUrl"];

                var options = new SessionCreateOptions {
                    CustomerEmail      = inschrijving.Email,
                    Locale             = "nl",
                    PaymentMethodTypes = new List <string> {
                        "card",
                    },
                    LineItems  = lineItems.ToList(),
                    SuccessUrl = $"{frontendUrl}/success?session_id={{CHECKOUT_SESSION_ID}}",
                    CancelUrl  = $"{frontendUrl}/cancel"
                };

                log.LogInformation("Creating stripe session");

                var     service = new SessionService();
                Session session = await service.CreateAsync(options);

                var sessionId = session.Id;

                log.LogInformation($"Stripe session created {sessionId}");

                log.LogInformation("Save inschrijving to database");
                await inschrijvingenOut.AddAsync(MapToDataModel(inschrijving, sessionId,
                                                                options.LineItems.Where(l => l.Amount.HasValue).Sum(l => l.Amount.Value)));

                log.LogInformation("Inschrijving saved. Returning sessionId to consumer");

                return(new JsonResult(new {
                    sessionId = sessionId
                }));
            }
            catch (Exception e) {
                log.LogError(e, $"Something went wrong {e.Message}");
                return(new BadRequestObjectResult(
                           new {
                    InvocationId = context.InvocationId
                }
                           ));
            }
        }