public ActionResult CreateCheckoutSession() { try { // Get Product from Stripe e.g. "Funding Apple FCU Account" var product = _stripeProvider?.GetProduct().Result; // Get Price from Stripe e.g. "Funding Apple FCU Account Price" var price = _stripeProvider?.GetPrice().Result; var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = price?.UnitAmount, Currency = price?.Currency, ProductData = new SessionLineItemPriceDataProductDataOptions { Name = product?.Name, Images = product?.Images }, }, Quantity = 1, }, }, Mode = "payment", SuccessUrl = "https://example.com/success", CancelUrl = "https://example.com/cancel", }; var sessionService = new SessionService(_client); var session = sessionService?.Create(options); Console.WriteLine($"Checkout Session with ID {session?.Id} Completed"); return(Json(new { id = session?.Id })); } catch (Exception e) { Console.WriteLine(e); throw; } }
public IActionResult ProcessPayment() { var order = HttpContext.Session.GetObject <Models.Orders>("Orders"); //get the Stripe key from the configuration StripeConfiguration.ApiKey = _iconfiguration.GetSection("Stripe")["SecretKey"]; //create and submit Stripe payment var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = (long?)(order.Total * 100), Currency = "cad", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "Home Accessorie Purchase", }, }, Quantity = 1, }, }, Mode = "payment", SuccessUrl = "https://" + Request.Host + "/Shop/SaveOrder", CancelUrl = "https://" + Request.Host + "/Shop/Cart" }; var service = new SessionService(); Session session = service.Create(options); return(Json(new { id = session.Id })); }
public ActionResult ProcessPayment() { //get order from session variable var order = HttpContext.Session.GetObject <Models.Order>("Order"); //get stripe secret key from configuration StripeConfiguration.ApiKey = _configuration.GetSection("Stripe")["SecretKey"]; // .net integration code from: https://stripe.com/docs/checkout/integration-builder var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = (long?)(order.Total * 100), Currency = "cad", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "Comp 2084 Get Me A Game Purchase", }, }, Quantity = 1, }, }, Mode = "payment", SuccessUrl = "https://" + Request.Host + "/Shop/SaveOrder", CancelUrl = "https://" + Request.Host + "/Shop/Cart", }; var service = new SessionService(); Session session = service.Create(options); return(Json(new { id = session.Id })); }
public async Task <ActionResult> CreateCheckoutSessionAsync([FromBody] Reservation reservation) { var cinema = await _mediator.Send(new GetFirstCinemaQuery()); StripeConfiguration.ApiKey = cinema.GatewayApiSecretKey; var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = (long)reservation.Payment.TotalPrice, Currency = "eur", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = reservation.MovieShow.Movie.Title.ToString() }, }, Description = "Payment will expire at " + reservation.Payment.Created.AddMinutes(7).ToString(), Quantity = reservation.ReservationSeats.Count }, }, Mode = "payment", SuccessUrl = "https://" + _httpContextAccessor.HttpContext.Request.Host.Value + "/payment/" + reservation.PaymentId + "/success?sessionId={CHECKOUT_SESSION_ID}", CancelUrl = "https://" + _httpContextAccessor.HttpContext.Request.Host.Value + "/payment/" + reservation.PaymentId + "/cancel?sessionId={CHECKOUT_SESSION_ID}", }; var service = new SessionService(); Session session = service.Create(options); await _service.StartAsync(session.PaymentIntentId, reservation.ReservationId, cinema.GatewayApiSecretKey); return(Ok(JsonConvert.SerializeObject(new { id = session.Id, paymentIntent = session.PaymentIntentId }))); }
public ActionResult CustomerPortal(string customerId) { StripeConfiguration.ApiKey = API_KEY; Session session = new Session(); try { var options = new SessionCreateOptions { Customer = customerId, ReturnUrl = "http://thelifetimetalents-dev.us-east-1.elasticbeanstalk.com/Home/Products", }; var service = new SessionService(); session = service.Create(options); } catch { return(BadRequest()); } return(Content(session.Url)); }
public async Task <IActionResult> Index() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenantBilling)) { return(Unauthorized()); } var options = new SessionCreateOptions { CustomerEmail = User.Identity.Name, PaymentMethodTypes = new List <string> { "card" }, SubscriptionData = new SessionSubscriptionDataOptions { Items = new List <SessionSubscriptionDataItemOptions> { new SessionSubscriptionDataItemOptions { Plan = _options.StripePlanKey }, }, Metadata = new Dictionary <string, string>() { { "TenantId", _shellSettings["Secret"] }, { "TenantName", _shellSettings.Name } } }, SuccessUrl = $"https://{HttpContext.Request.Host.Value}/{_shellSettings.Name}/admin/LefeWareLearning.StripePayment/paymentsuccess?sessionid={{CHECKOUT_SESSION_ID}}", CancelUrl = $"https://{HttpContext.Request.Host.Value}/{_shellSettings.Name}/admin", }; var service = new SessionService(); var session = service.Create(options); ViewBag.SessionId = session.Id; ViewBag.StripePublicKey = _options.StripePublicKey; return(View()); }
// Create Checkout Session public JsonResult CreateCheckoutSession() { var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { Name = "Kavholm rental", Amount = 1000, Currency = "usd", Quantity = 1, }, }, PaymentIntentData = new SessionPaymentIntentDataOptions { ApplicationFeeAmount = 123, TransferData = new SessionPaymentIntentTransferDataOptions { Destination = "{{CONNECTED_STRIPE_ACCOUNT_ID}}", }, }, SuccessUrl = "https://example.com/success", CancelUrl = "https://example.com/failure", }; var service = new SessionService(); Session session = service.Create(options); return(new JsonResult(new { sessionId = session.Id })); }
// GET: Orders/Create public ActionResult Create(string price, string count) { StripeConfiguration.ApiKey = "sk_test_51IncNxGyQHQcbQ8NDormZm0pm33IAE6DrSXpJIewUngomj00pUyP5q6dWOhUg26YbRynK2f49e11MxIfSVAYIXnD00jwqzvSEx"; var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = int.Parse(price) * 100, Currency = "usd", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "Dari Furnitures", }, }, Quantity = 1, }, }, Mode = "payment", SuccessUrl = "https://localhost:44307" + Url.Action("Success"), CancelUrl = "https://localhost:44307" + Url.Action("Error"), }; var service = new SessionService(); Session session = service.Create(options); return(Json(new { id = session.Id }, JsonRequestBehavior.AllowGet)); }
public IActionResult Charge() { try { 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 = "eur", Quantity = 1, }, }, SuccessUrl = "https://localhost:5001/home/success", CancelUrl = "https://localhost:5001/home/cancel", }; var service = new SessionService(); Session session = service.Create(options); return(Ok(session)); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); return(Ok(new { Error = e.Message })); } }
public IActionResult ProcessPayment() { var bookingList = HttpContext.Session.GetObject <Models.BookingList>("BookingList"); StripeConfiguration.ApiKey = _iconfiguration.GetSection("Stripe")["SecretKey"]; var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = (long?)(bookingList.Total * 100), Currency = "cad", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "Rental Rides Booking", }, }, Quantity = 1, }, }, Mode = "payment", SuccessUrl = "https://" + Request.Host + "/BookingLists/Index", // /Store/SaveOrder CancelUrl = "https://" + Request.Host + "/Store/Cart", }; var service = new SessionService(); Session session = service.Create(options); return(Json(new { id = session.Id })); }
public ActionResult Create() { var domain = "http://localhost:57428"; var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = 1100, Currency = "usd", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "CommuneLetters", }, }, Quantity = 1, }, }, Mode = "payment", SuccessUrl = domain + "/Home/Success", CancelUrl = domain + "/Home/Cancel", }; var service = new SessionService(); Session session = service.Create(options); return(Json(new { id = session.Id })); }
public IActionResult Charge(int id) { Plata plata = _context.Plati.FirstOrDefault(x => x.PlataId == id); var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = (int)Math.Round(plata.Suma * 100), Currency = "ron", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "Plata Servicii Contsal", }, }, Quantity = 1, }, }, Mode = "payment", SuccessUrl = "https://localhost:44342" + "/order/success?session_id={CHECKOUT_SESSION_ID}&plata_id=" + id, CancelUrl = "https://localhost:44342" + "/order/declined?session_id={CHECKOUT_SESSION_ID}&plata_id=" + id, }; var service = new SessionService(); // create transaction on the credit/debit card Session session = service.Create(options); return(Json(new { id = session.Id })); }
public Session CreateSession(OrderReadOnly order, string continueUrl, string cancelUrl, StripeCheckoutSettings settings) { var secretKey = settings.TestMode ? settings.TestSecretKey : settings.LiveSecretKey; ConfigureStripe(secretKey); var currency = Vendr.Services.CurrencyService.GetCurrency(order.CurrencyId); var billingCountry = order.PaymentInfo.CountryId.HasValue ? Vendr.Services.CountryService.GetCountry(order.PaymentInfo.CountryId.Value) : null; Customer customer; var customerService = new CustomerService(); // If we've created a customer already, keep using it but update it incase // any of the billing details have changed if (!string.IsNullOrWhiteSpace(order.Properties["stripeCustomerId"])) { var customerOptions = new CustomerUpdateOptions { Name = $"{order.CustomerInfo.FirstName} {order.CustomerInfo.LastName}", Email = order.CustomerInfo.Email, Description = order.OrderNumber, Address = new AddressOptions { Line1 = !string.IsNullOrWhiteSpace(settings.BillingAddressLine1PropertyAlias) ? order.Properties[settings.BillingAddressLine1PropertyAlias] : "", Line2 = !string.IsNullOrWhiteSpace(settings.BillingAddressLine2PropertyAlias) ? order.Properties[settings.BillingAddressLine2PropertyAlias] : "", City = !string.IsNullOrWhiteSpace(settings.BillingAddressCityPropertyAlias) ? order.Properties[settings.BillingAddressCityPropertyAlias] : "", State = !string.IsNullOrWhiteSpace(settings.BillingAddressStatePropertyAlias) ? order.Properties[settings.BillingAddressStatePropertyAlias] : "", PostalCode = !string.IsNullOrWhiteSpace(settings.BillingAddressZipCodePropertyAlias) ? order.Properties[settings.BillingAddressZipCodePropertyAlias] : "", Country = billingCountry?.Code } }; // Pass billing country / zipcode as meta data as currently // this is the only way it can be validated via Radar // Block if ::customer:billingCountry:: != :card_country: customerOptions.Metadata = new Dictionary <string, string> { { "billingCountry", customerOptions.Address.Country }, { "billingZipCode", customerOptions.Address.PostalCode } }; customer = customerService.Update(order.Properties["stripeCustomerId"].Value, customerOptions); } else { var customerOptions = new CustomerCreateOptions { Name = $"{order.CustomerInfo.FirstName} {order.CustomerInfo.LastName}", Email = order.CustomerInfo.Email, Description = order.OrderNumber, Address = new AddressOptions { Line1 = !string.IsNullOrWhiteSpace(settings.BillingAddressLine1PropertyAlias) ? order.Properties[settings.BillingAddressLine1PropertyAlias] : "", Line2 = !string.IsNullOrWhiteSpace(settings.BillingAddressLine2PropertyAlias) ? order.Properties[settings.BillingAddressLine2PropertyAlias] : "", City = !string.IsNullOrWhiteSpace(settings.BillingAddressCityPropertyAlias) ? order.Properties[settings.BillingAddressCityPropertyAlias] : "", State = !string.IsNullOrWhiteSpace(settings.BillingAddressStatePropertyAlias) ? order.Properties[settings.BillingAddressStatePropertyAlias] : "", PostalCode = !string.IsNullOrWhiteSpace(settings.BillingAddressZipCodePropertyAlias) ? order.Properties[settings.BillingAddressZipCodePropertyAlias] : "", Country = billingCountry?.Code } }; // Pass billing country / zipcode as meta data as currently // this is the only way it can be validated via Radar // Block if ::customer:billingCountry:: != :card_country: customerOptions.Metadata = new Dictionary <string, string> { { "billingCountry", customerOptions.Address.Country }, { "billingZipCode", customerOptions.Address.PostalCode } }; customer = customerService.Create(customerOptions); } var metaData = new Dictionary <string, string> { { "orderReference", order.GenerateOrderReference() }, { "orderId", order.Id.ToString("D") }, { "orderNumber", order.OrderNumber } }; if (!string.IsNullOrWhiteSpace(settings.OrderProperties)) { foreach (var alias in settings.OrderProperties.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim()) .Where(x => !string.IsNullOrWhiteSpace(x))) { if (!string.IsNullOrWhiteSpace(order.Properties[alias])) { metaData.Add(alias, order.Properties[alias]); } } } var hasRecurringItems = false; long recurringTotalPrice = 0; long orderTotalPrice = AmountToMinorUnits(order.TransactionAmount.Value); var lineItems = new List <SessionLineItemOptions>(); foreach (var orderLine in order.OrderLines.Where(IsRecurringOrderLine)) { var orderLinePrice = AmountToMinorUnits(orderLine.TotalPrice.Value.WithTax); var lineItemOpts = new SessionLineItemOptions(); if (orderLine.Properties.ContainsKey("stripePriceId") && !string.IsNullOrWhiteSpace(orderLine.Properties["stripePriceId"])) { // NB: When using stripe prices there is an inherit risk that values may not // actually be in sync and so the price displayed on the site might not match // that in stripe and so this may cause inconsistant payments lineItemOpts.Price = orderLine.Properties["stripePriceId"].Value; // If we are using a stripe price, then assume the quantity of the line item means // the quantity of the stripe price you want to buy. lineItemOpts.Quantity = (long)orderLine.Quantity; } else { // We don't have a stripe price defined on the order line // so we'll create one on the fly using th order lines total // value var priceData = new SessionLineItemPriceDataOptions { Currency = currency.Code, UnitAmount = orderLinePrice, Recurring = new SessionLineItemPriceDataRecurringOptions { Interval = orderLine.Properties["stripeRecurringInterval"].Value.ToLower(), IntervalCount = long.TryParse(orderLine.Properties["stripeRecurringIntervalCount"], out var intervalCount) ? intervalCount : 1 } }; if (orderLine.Properties.ContainsKey("stripeProductId") && !string.IsNullOrWhiteSpace(orderLine.Properties["stripeProductId"])) { priceData.Product = orderLine.Properties["stripeProductId"].Value; } else { priceData.ProductData = new SessionLineItemPriceDataProductDataOptions { Name = orderLine.Name, Metadata = new Dictionary <string, string> { { "ProductReference", orderLine.ProductReference } } }; } lineItemOpts.PriceData = priceData; // For dynamic subscriptions, regardless of line item quantity, treat the line // as a single subscription item with one price being the line items total price lineItemOpts.Quantity = 1; } lineItems.Add(lineItemOpts); recurringTotalPrice += orderLinePrice; hasRecurringItems = true; } if (recurringTotalPrice < orderTotalPrice) { // If the total value of the order is not covered by the subscription items // then we add another line item for the remainder of the order value var lineItemOpts = new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { Currency = currency.Code, UnitAmount = orderTotalPrice - recurringTotalPrice, ProductData = new SessionLineItemPriceDataProductDataOptions { Name = hasRecurringItems ? !string.IsNullOrWhiteSpace(settings.OneTimeItemsHeading) ? settings.OneTimeItemsHeading : "One time items" : !string.IsNullOrWhiteSpace(settings.OrderHeading) ? settings.OrderHeading : "#" + order.OrderNumber, Description = hasRecurringItems || string.IsNullOrWhiteSpace(settings.OrderHeading) ? null : "#" + order.OrderNumber, } }, Quantity = 1 }; lineItems.Add(lineItemOpts); } // Add image to the first item (only if it's not a product link) if (!string.IsNullOrWhiteSpace(settings.OrderImage) && lineItems.Count > 0 && lineItems[0].PriceData?.ProductData != null) { lineItems[0].PriceData.ProductData.Images = new[] { settings.OrderImage }.ToList(); } var sessionOptions = new SessionCreateOptions { Customer = customer.Id, PaymentMethodTypes = new List <string> { "card", }, LineItems = lineItems, Mode = hasRecurringItems ? "subscription" : "payment", ClientReferenceId = order.GenerateOrderReference(), SuccessUrl = continueUrl, CancelUrl = cancelUrl, }; if (hasRecurringItems) { sessionOptions.SubscriptionData = new SessionSubscriptionDataOptions { Metadata = metaData }; } else { sessionOptions.PaymentIntentData = new SessionPaymentIntentDataOptions { CaptureMethod = settings.Capture ? "automatic" : "manual", Metadata = metaData }; } if (settings.SendStripeReceipt) { sessionOptions.PaymentIntentData.ReceiptEmail = order.CustomerInfo.Email; } var sessionService = new SessionService(); var session = sessionService.Create(sessionOptions); return(session); }
public IActionResult Purchase() { // get all items in the user's cart Guid userId = GetUserId(); List <CartItem> cartItems = _cartService.GetUsersCart(userId); if (cartItems.Count == 0) { return(BadRequest(new { err = "Your cart is empty" })); } // create a list of session line items to pass them to stripe var lineItems = new List <SessionLineItemOptions>(); cartItems.ForEach(item => { // get the product's price decimal productPrice = _productService.GetProductPrice(item.Product.ID); SessionLineItemOptions itemOptions = new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { // the unit amount is in cents, therefore, it needs to be multiplied by 100 UnitAmount = (int)(productPrice * 100), // add the name of the item ProductData = new SessionLineItemPriceDataProductDataOptions { Name = item.Product.Title }, Currency = "USD" }, Quantity = item.Quantity }; lineItems.Add(itemOptions); }); // create session options var options = new SessionCreateOptions { // attach user's id in metadata, so that the webhook can verify it later PaymentIntentData = new SessionPaymentIntentDataOptions { Metadata = new Dictionary <string, string> { { "userId", userId.ToString() } } }, PaymentMethodTypes = new List <string> { "card", }, LineItems = lineItems, Mode = "payment", // take the user to the client app's homepage if the payment is successful SuccessUrl = $"{Request.Scheme}://{Request.Host}", // take the user back to the checkout page if the payment was cancelled CancelUrl = $"{Request.Scheme}://{Request.Host}/checkout" }; var service = new SessionService(); Session session = service.Create(options); return(Ok(new { res = session.Id })); }
public async Task <ActionResult> CreateAsync() { string host = "https://" + HttpContext.Request.Host.ToString() + "/"; var CartList = await _context.Cart.Where(i => i.CustomUserId == _userManger.GetUserId(User) && !i.IsSold).Include(i => i.Category).Include(i => i.CustomUser).ToListAsync(); foreach (var items in CartList) { var saleOffId = _context.Item.FirstOrDefault(i => i.Id == items.ItemId).ItemSaleOffId; var price = _context.Item.FirstOrDefault(i => i.Id == items.ItemId).Price; var CurrentPrice = _context.Item.FirstOrDefault(i => i.Id == items.ItemId).ListPrice(_context, price, saleOffId); if (items.Price != CurrentPrice) { items.Price = CurrentPrice; _context.Update(items); await _context.SaveChangesAsync(); } } decimal total = 0; decimal TotalItem = 0; foreach (var items in CartList) { total += (Convert.ToDecimal(items.Price) * (decimal)items.Quantity); TotalItem += (decimal)items.Quantity; } total += (decimal)15; decimal faxFee = total * (decimal)7 / (decimal)100; decimal TotalGrand = total + faxFee; TotalGrand = TotalGrand * 100; var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = (long)TotalGrand, Currency = "usd", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "Lan's market", }, }, Quantity = 1, }, }, Mode = "payment", SuccessUrl = host + "Home/success", CancelUrl = host + "Carts", }; var service = new SessionService(); Session session = service.Create(options); return(Json(new { id = session.Id })); }
[Fact] // 7. async Task<bool> MarkPaymentAsCompletedAsync(Session session) public async void MarkPaymentAsCompletedAsync_WithGivenSession_() { // Arrange var country = CountryCreator.Create(); var city = CityCreator.Create(country.Id); var home1 = HomeCreator.CreateAny(city.Id); // rented var home2 = HomeCreator.CreateManagedHome(home1.Owner.Id, city.Id); // managed var tenant1 = UserCreator.Create("Debelin", "Dignibutov", "but4eto", "*****@*****.**"); int id1 = 1; var contract1 = ContractCreator.CreateRentalContract(id1); var rental1 = RentalCreator.Create(id1, country, city, tenant1, home1, contract1); var payment1 = PaymentCreator.CreateForTenant(home1.Owner, tenant1.Id, rental1.Id); var payment2 = PaymentCreator.CreateForManager(home1.Owner.Id, home2.Manager.Id, home2.Id); var id = Guid.NewGuid().ToString(); var toStripeAccountId = "acct_1GUy2RB3QW0Kx8nS"; var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { Quantity = 1, Amount = (long)payment1.Amount * 100, Currency = CurrencyUSD, Name = $"Rent Payment for {DateTime.UtcNow.ToString("MMMM")}/ {DateTime.UtcNow.Year}", }, }, PaymentIntentData = new SessionPaymentIntentDataOptions { ApplicationFeeAmount = (long)((payment1.Amount * 0.01m) * 100), CaptureMethod = "automatic", Description = payment1.Id, TransferData = new SessionPaymentIntentTransferDataOptions { Destination = toStripeAccountId, }, }, SuccessUrl = "https://homy.azurewebsites.net/checkout/success?sessionId={CHECKOUT_SESSION_ID}", CancelUrl = "https://homy.azurewebsites.net/checkout/cancel", }; var service = new SessionService(); Session session = service.Create(options, new RequestOptions { ApiKey = HomyTestSecretKey, }); var sessionForDb = new StripeCheckoutSession { Id = session.Id, PaymentId = payment1.Id, ToStripeAccountId = toStripeAccountId, }; await this.Context.Countries.AddAsync(country); await this.Context.Cities.AddAsync(city); await this.Context.Homes.AddRangeAsync(home1, home2); await this.Context.Users.AddAsync(tenant1); await this.Context.Rentals.AddAsync(rental1); await this.Context.Payments.AddRangeAsync(payment1, payment2); await this.Context.Contracts.AddRangeAsync(contract1); await this.Context.StripeCheckoutSessions.AddAsync(sessionForDb); await this.Context.SaveChangesAsync(); var testService = new PaymentCommonService(this.Context, null, null, null); // Act var result = await testService.MarkPaymentAsCompletedAsync(session); bool expected = await this.Context.Payments.Where(p => p.Id == payment1.Id) .AnyAsync(p => p.Status == PaymentStatus.Complete); // Assert result.Should().Equals(expected); result.Should().BeTrue(); }
public async Task <IActionResult> CreateCheckoutSession() { var products = cartLogic.GetProductInCartAsViewModel(HttpContext.Session); if (products == null) { RedirectToAction("Index", "Products"); } var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions>(), Mode = "payment", SuccessUrl = "https://example.com/success", CancelUrl = "https://example.com/cancel", }; foreach (var product in products) { options.LineItems.Add(new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmountDecimal = product.ProductPrice * 100, Currency = "rub", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = product.ProductName, Description = product.ProductDescription }, }, Quantity = product.Quantity }); } var service = new SessionService(); Session session = service.Create(options); var prodOrders = clientLogic.GetProductsAndOrderInfo(HttpContext.Session); await clientLogic.SaveOrder(new OrderInfoViewModel { AddressPrimary = prodOrders.ClientOrderInformatiomViewModel.AddressPrimary, AddressSecondary = prodOrders.ClientOrderInformatiomViewModel.AddressSecondary, City = prodOrders.ClientOrderInformatiomViewModel.City, Country = prodOrders.ClientOrderInformatiomViewModel.Country, EmailCustomer = prodOrders.ClientOrderInformatiomViewModel.EmailCustomer, FirstNameCustomer = prodOrders.ClientOrderInformatiomViewModel.FirstNameCustomer, LastNameCustomer = prodOrders.ClientOrderInformatiomViewModel.LastNameCustomer, OrderBuyerComment = prodOrders.ClientOrderInformatiomViewModel.OrderBuyerComment, PostCode = prodOrders.ClientOrderInformatiomViewModel.PostCode, Stocks = prodOrders.ProductsInCartViewModel.Select(x => new StockMinViewModel { Quantity = x.Quantity, StockId = x.StockId }), StripeOrderRef = session.ClientReferenceId, SessionId = HttpContext.Session.Id }); return(Json(new { id = session.Id })); }
public Session CreateSession(ApplicationUser user, IEnumerable <ProductDto> products) { var lineItems = new List <SessionLineItemOptions>(); foreach (var product in products) { lineItems.Add(new SessionLineItemOptions { PriceData = new Stripe.SessionLineItemPriceDataOptions { Currency = "usd", ProductData = new Stripe.SessionLineItemPriceDataProductDataOptions { Name = product.Name, Description = product.Description, Images = new List <string> { product.Image != null && product.Image != string.Empty ? product.Image : "https://via.placeholder.com/150" }, Metadata = new Dictionary <string, string> { { "AppId", product.Id.ToString() }, { "UserId", user.Id } } }, // Must include product tax to send to Stripe UnitAmount = Convert.ToInt64((product.Price * 100) + (costDetailsService.GetCostDetails(new List <Product> { ToProduct(product) }).Tax * 100)) }, Quantity = 1 }); } var list = new List <Product>(); foreach (var productDto in products) { list.Add(ToProduct(productDto)); } var shipping = costDetailsService.GetCostDetails(list).Shipping; // Required to add shipping to line items if (shipping > 0) { lineItems.Add(new SessionLineItemOptions { PriceData = new Stripe.SessionLineItemPriceDataOptions { Currency = "usd", ProductData = new Stripe.SessionLineItemPriceDataProductDataOptions { Name = "Shipping", Description = "Shipping", Images = new List <string> { "https://via.placeholder.com/150" }, Metadata = new Dictionary <string, string> { { "AppId", "-1" }, { "UserId", user.Id } } }, UnitAmount = Convert.ToInt64(decimal.Parse(configuration["Business:ShippingRate"]) * 100) }, Quantity = 1 }); } var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card" }, CustomerEmail = user.Email, LineItems = lineItems, Mode = "payment", SuccessUrl = "https://localhost:44301/success?session_id={CHECKOUT_SESSION_ID}", CancelUrl = "https://localhost:44301/cart" }; var service = new SessionService(); return(service.Create(options)); }
public SessionModel CreateCheckoutSession(OrderModel order) { _validator.ValidateOrder(order); bool isExisting = order.Id is not null; PaymentEntity payment = isExisting ? new PaymentEntity { Id = order.PaymentId } : null; if (!isExisting) { order.Status = Enums.OrderStatusType.Unpaid; order.Date = DateTime.UtcNow; payment = new PaymentEntity { TransactionId = string.Empty }; _paymentRepository.Insert(payment); } var dbOrder = _mapper.Map <OrderEntity>(order); if (!isExisting) { dbOrder.PaymentId = payment.Id; dbOrder.Total = order.CurrentItems.Sum(item => item.Price); _orderRepository.Insert(dbOrder); } var items = new List <SessionLineItemOptions>(); var editionIds = order.CurrentItems.Select(item => item.PrintingEditionId).ToList(); var editionFilter = new PrintingEditionFilterModel { EditionIds = editionIds }; var printingEditions = _printingEditionService.GetPrintingEditionsRange(editionFilter); var dbItems = _mapper.Map <List <OrderItemEntity> >(order.CurrentItems); dbItems.ForEach(item => item.OrderId = dbOrder.Id); foreach (var item in dbItems) { var printingEdition = printingEditions.Where(edition => edition.Id == item.PrintingEditionId).FirstOrDefault(); var lineItem = new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmountDecimal = printingEdition.Price * Constants.CENTMULTIPLIER, Currency = item.Currency.ToString(), ProductData = new SessionLineItemPriceDataProductDataOptions { Name = printingEdition.Title, Description = printingEdition.Description } }, Quantity = item.Amount }; items.Add(lineItem); } if (!isExisting) { _itemRepository.InsertRange(dbItems); } string successUrl = new UriBuilder { Scheme = _urlConfig.Scheme, Port = _urlConfig.Port, Host = _urlConfig.Host, Path = Constants.STRIPESUCCESSPATH }.ToString(); string cancelUrl = new UriBuilder { Scheme = _urlConfig.Scheme, Port = _urlConfig.Port, Host = _urlConfig.Host, Path = Constants.STRIPECANCELPATH }.ToString(); var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { Constants.DEFAULTPAYMENTMETHOD }, LineItems = items, Mode = Constants.DEFAULTPAYMENTMODE, SuccessUrl = successUrl, CancelUrl = cancelUrl }; var service = new SessionService(); Session session = service.Create(options); payment.TransactionId = session.PaymentIntentId; _paymentRepository.Update(payment); return(new SessionModel { Id = session.Id, PaymentIntentId = session.PaymentIntentId }); }
public async Task <IActionResult> CreateSession(string id) { var userId = this.userManager.GetUserId(this.User); var payment = await this.paymentService.GetPaymentDetailsAsync(id, userId); //// LOCALHOST LINKS // var successStringUrl = "https://localhost:44319/checkout/success?sessionId={CHECKOUT_SESSION_ID}"; // var cancelStringUrl = "https://localhost:44319/checkout/cancel"; // AZURE LINKS // LOCALHOST LINKS var successStringUrl = "https://homy.azurewebsites.net/checkout/success?sessionId={CHECKOUT_SESSION_ID}"; var cancelStringUrl = "https://homy.azurewebsites.net/checkout/cancel"; //// CONVEYOR LINKS // var successStringUrl = "https://rpm-web.conveyor.cloud/checkout/success?sessionId={CHECKOUT_SESSION_ID}"; // var cancelStringUrl = "https://rpm-web.conveyor.cloud/checkout/cancel"; var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { Quantity = 1, Amount = (long)payment.Amount * 100, Currency = CurrencyUSD, Name = $"Rent Payment for {DateTime.UtcNow.ToString("MMMM")}/ {DateTime.UtcNow.Year} at {payment.Address}", }, }, PaymentIntentData = new SessionPaymentIntentDataOptions { ApplicationFeeAmount = (long)((payment.Amount * 0.01m) * 100), CaptureMethod = "automatic", Description = payment.Id, TransferData = new SessionPaymentIntentTransferDataOptions { Destination = payment.ToStripeAccountId, }, }, SuccessUrl = successStringUrl, CancelUrl = cancelStringUrl, }; var service = new SessionService(); Session session = service.Create(options); // Create Checkout Session in Database to validate it the Webhook handler and in SuccessPage await this.paymentCommonService.CreateCheckoutSessionAsync(session.Id, payment.Id, payment.ToStripeAccountId); return(this.Json(session)); }
public async Task <string> SampleCheckout(SampleCheckoutCommand command) { try { //var domain = "https://localhost:5200"; var domain = _masterConfig.StripeConfig.Domain; var options = new SessionCreateOptions { CustomerEmail = command.Email, PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = command.Amount, Currency = "usd", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = command.ProductName, }, }, Quantity = 1, }, }, Mode = "payment", SuccessUrl = _masterConfig.StripeConfig.SuccessUrl, CancelUrl = _masterConfig.StripeConfig.CancelUrl, //SuccessUrl = domain + "/checkoutSampleSuccess", //CancelUrl = domain + "/checkoutSampleCancel", }; var service = new SessionService(); Session session = service.Create(options); return(session.Id); } catch (StripeException e) { string errorMessage = ""; switch (e.StripeError.Error) { case "card_error": errorMessage = $"Card Error occurred on {e.StripeError.PaymentIntent.Id}, Error: {e.StripeError.Error}, Error Code: {e.StripeError.Code}, Error Description: {e.StripeError.ErrorDescription}"; break; case "api_error": errorMessage = $"API Error occurred: {e.StripeError.Error}, Error Code: {e.StripeError.Code}, Error Description: {e.StripeError.ErrorDescription}"; break; case "api_connection_error": errorMessage = $"API Connection Error occurred: {e.StripeError.Error}, Error Code: {e.StripeError.Code}, Error Description: {e.StripeError.ErrorDescription}"; break; case "invalid_request_error ": errorMessage = $"Invalid request Error occurred: {e.StripeError.Error}, Error Code: {e.StripeError.Code}, Error Description: {e.StripeError.ErrorDescription}"; break; default: errorMessage = $"Some Error occurred: {e.StripeError.Error}, Error Code: {e.StripeError.Code}, Error Description: {e.StripeError.ErrorDescription}"; break; } throw new InvalidOperationException(errorMessage); } }
public async Task <Session> InitSessionAsync(PurchaseOrderRequest[] request) { var itemList = request.Join( _dataService.GetInventoryItems(), x => x.InventoryItemId, y => y.Id, (x, y) => new PurchaseOrderRequest() { InventoryItemId = x.InventoryItemId, Quantity = x.Quantity, Price = y.Price, Name = y.Name, Description = y.Description }); var po = new PurchaseOrder(itemList); var poId = await _dataService.InsertPurchaseOrder(po); // we had to convert InsertPurchaseOrder to async method because we need // to wait until the database saves and returns us an Id, so we use "await" to pause // the thread until the Task is complete. // metaValues, Stripe lets you add meta data to your sessions/payments/transactions. var metaValues = new Dictionary <string, string>(); metaValues.Add("PurchaseOrderId", $"{poId}"); var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", // other 2 options are ideal and FPT (appears to be country driven) }, LineItems = itemList.Select(x => { // first make a LineItem for each item in request list. return(new SessionLineItemOptions { Name = $"{x.Name}", Description = $"{x.Description}", Amount = (long)(x.Price * 100), // Stripe uses long for price Currency = "usd", Quantity = x.Quantity }); // after list is generated, we'll append the sales tax line }).Append(new SessionLineItemOptions { Name = "Sales Tax", Description = "9.00%", Amount = (long)(po.SalesTax * 100), Currency = "usd", Quantity = 1 }).ToList(), SuccessUrl = "http://localhost:4200/result?session_id={CHECKOUT_SESSION_ID}", CancelUrl = $"http://localhost:4200/checkout?cancel={poId}", Metadata = metaValues }; var session = sessions.Create(options); // Create session // Save sessionId in the purchase order request po.StripeCheckoutSessionId = session.Id; _dataService.SavePurchaseOrder(po); // return the session, could just respond with sessionId // So the Session knows the Purchase Order its referring to and the PO also has the sessionId. return(session); }
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); }
public ActionResult <Sessions> Create(Sessions session) { _service.Create(session); return(CreatedAtRoute("GetSession", new { id = session.Id.ToString() }, session)); }
public ActionResult Create() { var orderId = this.ordersService.GetProcessingOrderByUserId(this.userId).Id; var order = this.ordersService.GetById <OrderViewModel>(orderId); var items = new List <SessionLineItemOptions>(); foreach (var product in order.Products) { items.Add(new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = (long?)(product.Price * 100), Currency = "usd", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = product.ProductName, Images = new List <string> { this.domain + product.ImageUrl }, }, }, Quantity = product.Quantity, }); } // Add shipping price items.Add(new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = (long?)(order.DeliveryPrice * 100), Currency = "usd", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "Shipping", }, }, Quantity = 1, }); var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = items, Mode = "payment", SuccessUrl = this.domain + "/Orders/Complete", CancelUrl = this.domain + "/Orders/Create", Metadata = new Dictionary <string, string> { { "order_id", orderId } }, }; var service = new SessionService(); Session session = service.Create(options); return(this.Json(new { id = session.Id })); }
public ActionResult Index() { //StripeConfiguration.ApiKey = "sk_test_l5D3Gu5k6G00kaRnmy3deczM00zBvQf5OO"; //var options = new ChargeCreateOptions //{ // Amount = 999, // Currency = "usd", // Source = "tok_visa", // ReceiptEmail = "*****@*****.**", //}; //var service = new ChargeService(); //Charge charge = service.Create(options); //Console.WriteLine(charge); StripeConfiguration.ApiKey = "sk_test_l5D3Gu5k6G00kaRnmy3deczM00zBvQf5OO"; bool isCustomer = true; var customerOps = new SessionCreateOptions { CustomerEmail = "*****@*****.**", PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { Name = "T-shirt", Description = "Comfortable cotton t-shirt", Amount = 500, Currency = "gbp", Quantity = 1, }, }, SuccessUrl = "https://example.com/success", CancelUrl = "https://example.com/cancel", }; 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 = "gbp", Quantity = 1, }, }, SuccessUrl = "https://example.com/success", CancelUrl = "https://example.com/cancel", }; var chosenOps = isCustomer ? customerOps : options; var service = new SessionService(); Session session = service.Create(chosenOps); return(View(new Data { Sid = session.Id })); }
public override PaymentFormResult GenerateForm(OrderReadOnly order, string continueUrl, string cancelUrl, string callbackUrl, StripeCheckoutOneTimeSettings settings) { var secretKey = settings.TestMode ? settings.TestSecretKey : settings.LiveSecretKey; var publicKey = settings.TestMode ? settings.TestPublicKey : settings.LivePublicKey; ConfigureStripe(secretKey); var currency = Vendr.Services.CurrencyService.GetCurrency(order.CurrencyId); var billingCountry = order.PaymentInfo.CountryId.HasValue ? Vendr.Services.CountryService.GetCountry(order.PaymentInfo.CountryId.Value) : null; var customerOptions = new CustomerCreateOptions { Name = $"{order.CustomerInfo.FirstName} {order.CustomerInfo.LastName}", Email = order.CustomerInfo.Email, Description = order.OrderNumber, Address = new AddressOptions { Line1 = !string.IsNullOrWhiteSpace(settings.BillingAddressLine1PropertyAlias) ? order.Properties[settings.BillingAddressLine1PropertyAlias] : "", Line2 = !string.IsNullOrWhiteSpace(settings.BillingAddressLine1PropertyAlias) ? order.Properties[settings.BillingAddressLine2PropertyAlias] : "", City = !string.IsNullOrWhiteSpace(settings.BillingAddressCityPropertyAlias) ? order.Properties[settings.BillingAddressCityPropertyAlias] : "", State = !string.IsNullOrWhiteSpace(settings.BillingAddressStatePropertyAlias) ? order.Properties[settings.BillingAddressStatePropertyAlias] : "", PostalCode = !string.IsNullOrWhiteSpace(settings.BillingAddressZipCodePropertyAlias) ? order.Properties[settings.BillingAddressZipCodePropertyAlias] : "", Country = billingCountry?.Code } }; var customerService = new CustomerService(); var customer = customerService.Create(customerOptions); var sessionOptions = new SessionCreateOptions { Customer = customer.Id, PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { Name = !string.IsNullOrWhiteSpace(settings.OrderHeading) ? settings.OrderHeading : "#" + order.OrderNumber, Description = !string.IsNullOrWhiteSpace(settings.OrderHeading) ? "#" + order.OrderNumber : null, Amount = AmountToMinorUnits(order.TotalPrice.Value.WithTax), Currency = currency.Code, Quantity = 1 }, }, PaymentIntentData = new SessionPaymentIntentDataOptions { CaptureMethod = settings.Capture ? "automatic" : "manual", Metadata = new Dictionary <string, string> { { "orderReference", order.GenerateOrderReference() }, // Pass billing country / zipecode as meta data as currently // this is the only way it can be validated via Radar // Block if ::orderBillingCountry:: != :card_country: { "orderBillingCountry", billingCountry.Code?.ToUpper() }, { "orderBillingZipCode", customerOptions.Address.PostalCode } } }, Mode = "payment", ClientReferenceId = order.GenerateOrderReference(), SuccessUrl = continueUrl, CancelUrl = cancelUrl, }; if (!string.IsNullOrWhiteSpace(settings.OrderImage)) { sessionOptions.LineItems[0].Images = new[] { settings.OrderImage }.ToList(); } if (settings.SendStripeReceipt) { sessionOptions.PaymentIntentData.ReceiptEmail = order.CustomerInfo.Email; } var sessionService = new SessionService(); var session = sessionService.Create(sessionOptions); return(new PaymentFormResult() { Form = new PaymentForm(continueUrl, FormMethod.Post) .WithAttribute("onsubmit", "return handleStripeCheckout(event)") .WithJsFile("https://js.stripe.com/v3/") .WithJs(@" var stripe = Stripe('" + publicKey + @"'); window.handleStripeCheckout = function (e) { e.preventDefault(); stripe.redirectToCheckout({ sessionId: '" + session.Id + @"' }).then(function (result) { // If `redirectToCheckout` fails due to a browser or network // error, display the localized error message to your customer // using `result.error.message`. }); return false; } ") }); }
public override Task Execute(MessageData data) { string productId; try { productId = data.GetAs <string>(); } catch (Exception) { throw new CoflnetException("invaild_data", "Data should contain a product id as string"); } var product = GetProduct(productId); var price = GetPrice(productId); var domain = "https://sky.coflnet.com"; var options = new SessionCreateOptions { PaymentMethodTypes = new List <string> { "card", }, LineItems = new List <SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { UnitAmount = price.UnitAmount, Currency = "eur", Product = productId }, // Description = "Unlocks premium features: Subscribe to 100 Thrings, Search with multiple filters and you support the project :)", Quantity = 1, }, }, Metadata = product.Metadata, Mode = "payment", SuccessUrl = domain + "/success", CancelUrl = domain + "/cancel", ClientReferenceId = data.UserId.ToString() }; var service = new SessionService(); Session session; try { session = service.Create(options); } catch (Exception e) { Console.WriteLine(e.Message); throw new CoflnetException("internal_error", "service not working"); } using (var context = new HypixelContext()) { var user = data.User; context.Update(user); context.SaveChanges(); } return(data.SendBack(data.Create("checkoutSession", session.Id), false)); //return Json(new { id = session.Id }); }
public async System.Threading.Tasks.Task <Session> InitSessionAsync(PurchaseOrderItem[] items) { #region init ItemList // purchaseOrderitem has InventoryItemId // InventoryItems has Id var itemList = items.Join( // what are we joining with // property of first group // property of second group // result _dataService.GetInventoryItems(), x => x.InventoryItemId, y => y.Id, (x, y) => new PurchaseOrderRequest { Id = y.Id, Quantity = x.Quantity, Name = y.Name, Price = y.Price, Description = y.Description } ); #endregion var newPurchaseOrder = new PurchaseOrder(itemList); var poId = await _dataService.InsertPurchaseOrderAsync(newPurchaseOrder); var listLineItems = itemList.Select(x => { return(new SessionLineItemOptions { Name = x.Name, Description = x.Description, Amount = (long)(x.Price * 1000), Currency = "usd", Quantity = x.Quantity, }); }); var salesTax = listLineItems.Sum(x => x.Amount) * 08; listLineItems.Append(new SessionLineItemOptions { Name = "Sales Tax", Description = "CA 8%", Quantity = 1, Currency = "usd" }); var options = new SessionCreateOptions { SuccessUrl = "http://localhost:4200/result?session_id={CHECKOUT_SESSION_ID}", CancelUrl = "http://example.com/cancel", PaymentMethodTypes = new List <string> { "card" }, LineItems = listLineItems.ToList(), }; //var service = new SessionService(); Session session = sessions.Create(options); newPurchaseOrder.Id = poId; newPurchaseOrder.StripeSessionId = session.Id; _dataService.SavePurchaseOrder(newPurchaseOrder); return(session); }
public ActionResult Render(string tr) { var paymentIntent = PaymentService.GetPaymentIntentByTransactionRef(tr); StripeConfiguration.ApiKey = ConfigurationManager.AppSettings["Cashier:Stripe:Secret"]; string domain = $"{HttpContext.Request.Url.Scheme}://{HttpContext.Request.Url.Host}{(HttpContext.Request.Url.Port > 443 ? ":" + HttpContext.Request.Url.Port : "")}"; var sessionService = new SessionService(); var session = sessionService.Create(new SessionCreateOptions { SuccessUrl = domain + "/stripe-dd-success?sessionId={CHECKOUT_SESSION_ID}", CancelUrl = domain + "/stripe-dd-failure?sessionId={CHECKOUT_SESSION_ID}", Mode = "setup", PaymentMethodTypes = new List <string> { "bacs_debit" }, Metadata = new Dictionary <string, string> { { "TransactionRef", paymentIntent.TransactionReference } }, //PaymentIntentData = new SessionPaymentIntentDataOptions //{ // SetupFutureUsage = "off_session", // ReceiptEmail = paymentIntent.CustomerEmail //}, //CustomerEmail = paymentIntent.CustomerEmail, BillingAddressCollection = "auto", //LineItems = new List<SessionLineItemOptions> //{ // new SessionLineItemOptions // { // Amount = (long)paymentIntent.Amount * 100, // Description = paymentIntent.Description, // Quantity = 1, // Currency = "gbp", // Name = "Direct Debit - " + paymentIntent.Amount // //PriceData = new SessionLineItemPriceDataOptions // //{ // // UnitAmount = (long)paymentIntent.Amount * 100, // // Recurring = new SessionLineItemPriceDataRecurringOptions // // { // // Interval = "month" // // }, // // Currency = "gbp", // // ProductData = new SessionLineItemPriceDataProductDataOptions // // { // // Name = "Direct Debit - " + paymentIntent.Amount, // // Description = paymentIntent.Description // // } // //} // } //} }); ViewBag.StripeSessionId = session.Id; return(View("StripeDirectDebitPayment", CurrentPage)); }