public async Task <PaymentIntent> CreateChargeAsync(string accountId, string customerId, string paymentMethodId, string description, decimal amount, decimal applicationFeeAmount, Dictionary <string, string> metadata = null) { var accountService = new AccountService(); var account = await accountService.GetAsync(accountId); var options = new PaymentIntentCreateOptions { Description = description, Amount = (long)(amount * 100), ApplicationFeeAmount = (long)(applicationFeeAmount * 100), Currency = "usd", PaymentMethodTypes = new List <string> { "card" }, Customer = customerId, PaymentMethod = paymentMethodId, Confirm = true, OffSession = true, Metadata = metadata, TransferData = new PaymentIntentTransferDataOptions() { Destination = accountId } }; if (account.Capabilities.CardPayments == "active") { options.OnBehalfOf = accountId; } var service = new PaymentIntentService(); return(await service.CreateAsync(options)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddRazorPages(); services.AddMvc(option => option.EnableEndpointRouting = false); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration["DefaultConnection"])); services.AddSession(options => { options.Cookie.Name = "Cart"; options.Cookie.MaxAge = TimeSpan.FromDays(365); }); services.AddControllersWithViews().AddNewtonsoftJson(); //za stripe StripeConfiguration.ApiKey = "sk_test_lH5WHAKbN2YNRaBxd4HFx6JX00lZ5ZQEKd"; var service = new PaymentIntentService(); var options = new PaymentIntentCreateOptions { Amount = 1099, Currency = "eur", }; service.Create(options); }
public async Task <CustomerBasket> CreateOrUpdatePaymentIntent(string basketId) { StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"]; var basket = await _basketRepository.GetBasketAsync(basketId); if (basket == null) { return(null); } var shippingPrice = 0m; if (basket.DeliveryMethodId.HasValue) { var deliveryMethod = await _unitOfWork.Repository <DeliveryMethod>().GetByIdAsync((int)basket.DeliveryMethodId); shippingPrice = deliveryMethod.Price; } foreach (var item in basket.Items) { var productItem = await _unitOfWork.Repository <Core.Entities.Product>().GetByIdAsync(item.Id); if (item.Price != productItem.Price) { item.Price = productItem.Price; } } var service = new PaymentIntentService(); PaymentIntent intent; if (string.IsNullOrEmpty(basket.PaymentIntentId)) { var options = new PaymentIntentCreateOptions { Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100, Currency = "usd", PaymentMethodTypes = new List <string> { "card" } }; intent = await service.CreateAsync(options); basket.PaymentIntentId = intent.Id; basket.ClientSecret = intent.ClientSecret; } else { var options = new PaymentIntentUpdateOptions { Amount = (long)basket.Items.Sum(i => i.Quantity * (i.Price * 100)) + (long)shippingPrice * 100 }; await service.UpdateAsync(basket.PaymentIntentId, options); } await _basketRepository.UpdateBasketAsync(basket); return(basket); }
public override async Task <CreateStripePaymentIntentResponse> CreateStripePaymentIntent( CreateStripePaymentIntentRequest request, ServerCallContext context ) { var httpContext = context.GetHttpContext(); var paymentIntentService = new PaymentIntentService(); var options = new PaymentIntentCreateOptions { PaymentMethod = request.PaymentMethodId, Customer = httpContext.GetStripeCustomerId(), ReceiptEmail = httpContext.GetEmail(), Amount = request.Transaction.Currency.ToCents(), Currency = Options.Invoice.Currency, Metadata = new Dictionary <string, string> { ["UserId"] = httpContext.GetUserId(), ["TransactionId"] = request.Transaction.Id } }; var paymentIntent = await paymentIntentService.CreateAsync(options); var response = new CreateStripePaymentIntentResponse { ClientSecret = paymentIntent.ClientSecret }; var message = $"A new payment {paymentIntent.Id} for {paymentIntent.Amount} {paymentIntent.Currency} was created"; return(context.Ok(response, message)); }
private async Task <ActionResult> PayWithStripeElements(Sjop.Models.Order order) { // Read Stripe API key from config StripeConfiguration.ApiKey = _stripeSettings.SecretKey; var paymentIntentCreateOptions = new PaymentIntentCreateOptions { Customer = StripeCustomer(order).Id, Amount = Convert.ToInt32(order.OrderTotalprice * 100), Currency = "nok", PaymentMethodTypes = new List <string> { "card" }, Description = "Bestilling fra Losvik kommune", ReceiptEmail = order.Customer.Email, StatementDescriptor = "Losvik kommune", Metadata = new Dictionary <String, String>() { { "OrderId", order.Id.ToString() } } }; var service = new PaymentIntentService(); var intent = await service.CreateAsync(paymentIntentCreateOptions); return(Ok(intent)); }
public IActionResult Post([FromBody] IEnumerable <BasketProduct> basketProducts) { //var total = "0"; var paymentIntents = new PaymentIntentService(); var paymentIntent = paymentIntents.Create(new PaymentIntentCreateOptions { Amount = CalculateOrderAmount(basketProducts), Currency = "gbp", Metadata = new Dictionary <string, string> { { "OrderId", "6735" }, }, }); //var paymentIntent = paymentIntents.Create(new PaymentIntentCreateOptions //{ // Amount = 1099, // Currency = "gbp", //}); //var myCharge = new ChargeCreateOptions(); //myCharge.Source = chargeRequest.tokenId; ////Always decide how much to charge on the server side, a trusted environment, as opposed to the client. //myCharge.Amount = 150; //myCharge.Customer = chargeRequest.customer; //myCharge.Currency = "gbp"; //myCharge.Description = chargeRequest.productName; //myCharge.Metadata = new Dictionary<string, string>(); //myCharge.Metadata["OurRef"] = "OurRef-" + Guid.NewGuid().ToString(); //var service = new ChargeService(); //Charge stripeCharge = service.Create(myCharge); return(Json(new { clientSecret = paymentIntent.ClientSecret })); }
private void InitClient(Payment payment) { Client = new StripeClient(payment.PaymentMethod.GetProperty(SecretKey).GetValue().ToString()); ChargeService = new ChargeService(Client); PaymentIntentService = new PaymentIntentService(Client); RefundService = new RefundService(Client); }
public async Task <bool> CreateOrUpdatePaymentIntent(string userId) { StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"]; var carts = await _cartItemService.GetAll(userId); if (carts.Count == 0) { return(false); } var service = new PaymentIntentService(); int amount = 0; foreach (var item in carts) { amount += item.Quantity + item.ProductDetail.Product.Price; } var options = new PaymentIntentCreateOptions { Amount = amount * 100, Currency = "usd", PaymentMethodTypes = new List <string> { "card" } }; await service.CreateAsync(options); return(true); }
public async Task <IActionResult> OnPostAsync( string paymentId, [FromServices] CreateOrder createOrder, [FromServices] GetCart getCart, [FromServices] PaymentIntentService paymentIntentService, [FromServices] ILogger <Payment> logger) { var userId = User.GetUserId(); var cartId = await getCart.Id(userId); if (cartId == 0) { logger.LogWarning($"Cart not found for {userId} with payment id {paymentId}"); return(RedirectToPage("/Checkout/Error")); } var payment = await paymentIntentService.CaptureAsync(paymentId); if (payment == null) { logger.LogWarning($"Payment Intent not found {paymentId}"); return(RedirectToPage("/Checkout/Error")); } var order = new Domain.Models.Order { StripeReference = paymentId, CartId = cartId, }; await createOrder.Do(order); return(RedirectToPage("/Checkout/Success", new { orderId = order.Id })); }
public async Task <IActionResult> CreatePaymentIntent([FromBody] CreatePaymentIntentRequest req) { var options = new PaymentIntentCreateOptions { Amount = 1999, Currency = req.Currency, PaymentMethodTypes = new List <string> { req.PaymentMethodType, }, }; var service = new PaymentIntentService(this.client); try { var paymentIntent = await service.CreateAsync(options); return(Ok(new CreatePaymentIntentResponse { ClientSecret = paymentIntent.ClientSecret, })); } catch (StripeException e) { return(BadRequest(new { error = new { message = e.StripeError.Message } })); } catch (System.Exception) { return(BadRequest(new { error = new { message = "unknown failure: 500" } })); } }
public dynamic confirmPayment(ConfirmPaymentInfo confirmPaymentInfo) { string stripeRedirectUrl = String.IsNullOrEmpty(confirmPaymentInfo.RedirectUrl)? GetEnvironmentConfigVar(StripeConfigKey, this.configuration.GetValue <string>(StripeConfigRedirectUrl)) + "/Home/ConfirmPayment":confirmPaymentInfo.RedirectUrl; var paymentIntentService = new PaymentIntentService(); PaymentIntent paymentIntent = null; try { if (confirmPaymentInfo.PaymentIntentId != null) { paymentIntent = paymentIntentService.Get(confirmPaymentInfo.PaymentIntentId); if (paymentIntent.Status == "requires_payment_method") { generatePaymentResponse(paymentIntent); } else { var confirmOptions = new PaymentIntentConfirmOptions { ReturnUrl = stripeRedirectUrl }; paymentIntent = paymentIntentService.Confirm( confirmPaymentInfo.PaymentIntentId, confirmOptions ); } } } catch (StripeException e) { return(new { error = e.StripeError.Message }); } return(generatePaymentResponse(paymentIntent)); }
public async Task <string> MakePayment(string apiSecretKey, string currencyCode, double amount, string cardToken, string description, string memberName) { StripeClient client = new StripeClient(apiSecretKey); PaymentIntentService intentService = new PaymentIntentService(client); PaymentIntent intent = await intentService.CreateAsync(new PaymentIntentCreateOptions { Amount = (int)(amount * 100), Currency = currencyCode.ToLowerInvariant(), Description = $"{memberName}: {description}", ExtraParams = new Dictionary <string, object> { { "payment_method_data", new Dictionary <string, object> { { "type", "card" }, { "card", new Dictionary <string, object> { { "token", cardToken } } } } } } }); intent = await intentService.ConfirmAsync(intent.Id); return(intent.Id); }
private bool MakePayment() { try { StripeConfiguration.ApiKey = "sk_test_51HoUdtIMEgSAkndur6EU84kDlaZEkXD99KVaoaMCw2QpIZegb8I5YTnUbUDQ4xNR3x6JR3gyWaURvdJ4O2GFq7yW00dsG6QHEk"; var options = new PaymentIntentCreateOptions { Amount = (long?)model.Cijena * 100, Currency = "bam", PaymentMethod = ((Item)metodaPlacanja.SelectedItem).Id, OffSession = false, Confirm = true }; var service = new PaymentIntentService(); var intent = service.Create(options); return(true); } catch (Exception ex) { Application.Current.MainPage.DisplayAlert("Greska", ex.Message, "Ok"); } return(false); }
public async Task <IActionResult> CreateAndSave() { //Step 2 var options = new CustomerCreateOptions { }; var service = new CustomerService(); var customer = service.Create(options); //Step 3 var optionss = new PaymentIntentCreateOptions { Amount = 1099, Currency = "usd", Customer = customer.Id //"{{CUSTOMER_ID}}", }; var servicee = new PaymentIntentService(); var paymentIntent = servicee.Create(optionss); return(Ok(new SaveCustomerDetailsCommandResult() { ClientSecret = paymentIntent.ClientSecret })); }
private async Task <ActionResult> PayWithStripeElements([FromBody] AppZeroAPI.Entities.CustomerOrder order) { // Read Stripe API key from config StripeConfiguration.ApiKey = StripeOptions.SecretKey; var paymentIntentCreateOptions = new PaymentIntentCreateOptions { Customer = StripeCustomer(order).Id, Amount = Convert.ToInt32(order.total_payable), Currency = "usd", PaymentMethodTypes = new List <string> { "card" }, Description = "Bestilling fra Losvik kommune", ReceiptEmail = order.customer.email, StatementDescriptor = "Losvik kommune", Metadata = new Dictionary <String, String>() { { "OrderId", order.order_id.ToString() } } }; var service = new PaymentIntentService(); var intent = await service.CreateAsync(paymentIntentCreateOptions); return(Ok(intent)); }
public IActionResult createPaymentIntent([FromBody] JObject data) { var identity = HttpContext.User.Identity as ClaimsIdentity; var email = identity.Claims.FirstOrDefault().Value; var user = _context.User.FirstOrDefault(u => u.Email.Equals(email)); var products = JsonConvert.DeserializeObject <List <ProductOrder> >(data["products"].ToString()); int total = 0; foreach (ProductOrder p in products) { total += p.Quantity * p.Price; } var options = new PaymentIntentCreateOptions { Amount = total * 100, Currency = "ron", Customer = user.StripeId, }; var service = new PaymentIntentService(); var paymentIntent = service.Create(options); return(Ok(paymentIntent.ClientSecret)); }
public IActionResult PurchaseItem([FromBody] Order purchaseOrder) { //var tokenVar = purchaseOrder.tokenVar; //Item[] items = purchaseOrder.Items; //Get the customer id var customerId = "11111";// await GetCustomer(tokenVar); var pmlOptions = new PaymentMethodListOptions { Customer = customerId, Type = "card", }; //IF THERE ARENT ANY THAN THROW AN ERROR!!! var pmService = new PaymentMethodService(); var paymentMethods = pmService.List(pmlOptions); var paymentIntents = new PaymentIntentService(); var paymentIntent = paymentIntents.Create(new PaymentIntentCreateOptions { Customer = customerId, SetupFutureUsage = "off_session", Amount = 1000, Currency = "usd", PaymentMethod = paymentMethods.Data[0].Id, Description = "Name of items here" });;; return(Ok(new { client_secret = paymentIntent.ClientSecret })); }
public static string CreatePaymentIntent() { try { //create a payment intent var service = new PaymentIntentService(); var options = new PaymentIntentCreateOptions { Amount = 1400, Currency = "USD", PaymentMethodTypes = new List <string> { "card" }, }; var intent = service.Create(options); string clientSecret = intent.ClientSecret; return(clientSecret); } catch (Exception ex) { throw ex; // throw error message back to the client side and maybe do something with it } }
public string CreateStripePaymentIntent(decimal amount) { try { var options = new PaymentIntentCreateOptions { Amount = (long)amount, Currency = "usd", // Verify your integration in this guide by including this parameter Metadata = new Dictionary <string, string> { { "integration_check", "accept_a_payment" } }, }; var paymentIntent = new PaymentIntentService().Create(options); return(paymentIntent.ClientSecret); } catch (Exception ex) { } return(null); }
public async Task <IActionResult> CreatePaymentIntent(string id, [FromForm] PaymentRequest values) { StripeConfiguration.ApiKey = "sk_test_9lbV8iZ2EjD5TiOzTAFURm7H00TCPFae4M"; // Create new order here var options = new PaymentIntentCreateOptions { Amount = values.Amount, Currency = "vnd", }; var service = new PaymentIntentService(); var paymentIntent = service.Create(options); var user = await _userManager.FindByIdAsync(id); if (user != null) { var claims = await _userManager.GetClaimsAsync(user); var customer = _mapper.Map <IdentityUser, CustomerResponseDTO>( source: user, opts: opt => opt.Items["claims"] = claims ); return(Ok(new { clientSecret = paymentIntent.ClientSecret })); } else { return(NotFound()); } }
/// <summary> /// Creates a payment intent and returns the payment intent /// </summary> /// <param name="amount_cents"></param> /// <returns></returns> public async Task <PaymentResult> CreatePaymentIntentAsync(string paymentMethodId, int amount_cents = 300) { var paymentIntentService = new PaymentIntentService(); var options = new PaymentIntentCreateOptions() { Amount = amount_cents, Confirm = true, Currency = "usd", CaptureMethod = "manual", ConfirmationMethod = "manual", PaymentMethodId = paymentMethodId, StatementDescriptor = "NowLeave.com" }; //setup the request options var intent = await paymentIntentService.CreateAsync(options, GetRequestOptions()); var requiresClientAction = intent.Status == "requires_action" && intent.NextAction.Type == "use_stripe_sdk"; var res = new PaymentResult() { Success = requiresClientAction == true || intent.Status == "requires_capture" || intent.Status == "succeeded", ClientSecret = intent.ClientSecret, PaymentIntentId = intent.Id, RequiresClientAction = requiresClientAction }; return(res); }
public bool stripeTestFun() { bool result = true; try { var options = new PaymentIntentCreateOptions { Amount = 1000, Currency = "usd", PaymentMethodTypes = new List <string> { "card" }, ReceiptEmail = "*****@*****.**", }; var service = new PaymentIntentService(); PaymentIntent respone = service.Create(options); } catch (Exception ex) { logger.Error(ex.ToString()); result = false; } return(result); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var options = new PaymentIntentCreateOptions { Amount = 4000, Currency = "usd", PaymentMethodTypes = new List <string> { "card", }, }; var service = new PaymentIntentService(); var paymentIntent = service.Create(options); clientSecret = paymentIntent.ClientSecret; } else { ; } { } // continue your regular Page_load() processing... }
public async Task <string> Handle(Command request, CancellationToken cancellationToken) { var user = await _context.Users.SingleOrDefaultAsync(x => x.UserName == _userAccessor.GetCurrentUsername()); if (user.UserCart == null) { throw new RestException(HttpStatusCode.MethodNotAllowed, new { Cart = "Cannot checkout" }); } Dictionary <string, string> Metadata = new Dictionary <string, string>(); foreach (var item in user.UserCart.ItemsInCart) { Metadata.Add("Product", item.Title); Metadata.Add("Quantity", item.quantity.ToString()); } var options = new PaymentIntentCreateOptions { Amount = (long)user.UserCart.Total * 100, Currency = "USD", Description = "Purchace from Home County Plate", ReceiptEmail = user.Email, Metadata = Metadata }; var service = new PaymentIntentService(); var charge = service.Create(options); return(charge.ClientSecret); }
public ActionResult <ItemResponse <Stripe.PaymentIntent> > CreateIntentApi(PaymentIntentCreateOptions options) { int responseCode = 200; BaseResponse responseData = null; try { int userId = _authService.GetCurrentUserId(); // Set your secret key. Remember to switch to your live secret key in production! StripeConfiguration.ApiKey = _appKeys.StripeApiKey; var service = new PaymentIntentService(); var paymentIntent = service.Create(options); responseData = new ItemResponse <Stripe.PaymentIntent> { Item = paymentIntent }; } catch (Exception exception) { responseCode = 500; responseData = new ErrorResponse($"Generic Error: {exception.Message}"); base.Logger.LogError(exception.ToString()); } return(StatusCode(responseCode, responseData)); }
public OrderPaymentIntentDto CreatePaymentIntent(int orderId) { var order = _orderRepo.GetById(orderId); var customer = _customerRepo.GetById(order.CustomerId); StripeConfiguration.ApiKey = _config["StripeSettings:SecretKey"]; var service = new PaymentIntentService(); var options = new PaymentIntentCreateOptions { Amount = Convert.ToInt64(order.Total), Currency = "vnd", PaymentMethodTypes = new List <string> { "card" }, }; var intent = service.Create(options); order.PaymentIndentId = intent.Id; order.ClientSecret = intent.ClientSecret; _orderRepo.Update(order); var orderPaymentIntentDto = new OrderPaymentIntentDto(); orderPaymentIntentDto.PaymentIndentId = intent.Id; orderPaymentIntentDto.ClientSecret = intent.ClientSecret; return(orderPaymentIntentDto); }
public PaymentResponse InitPayment(CheckoutData data) { if (data.CurrentPaymentIntentId != null) { // TODO: If session is still valid, check if there is a need to update the payment intent (e.g. amount) return(GetExistingSession(data.CurrentPaymentIntentId)); } var service = new PaymentIntentService(); var intent = service.Create(new PaymentIntentCreateOptions { Amount = (long)(data.Amount * 100), Currency = data.Currency, PaymentMethodTypes = new List <string>(data.PaymentMethodTypes), StatementDescriptor = "ABC-Trading", Metadata = new Dictionary <string, string> { { "integration_check", "accept_a_payment" }, { "OrderId", data.OrderId } } }); return(new PaymentResponse() { Status = "OK", SuccessData = new Dictionary <string, object>() { { "paymentIntent", intent.ToJson() } } }); }
public async Task <IActionResult> StripeSessionTest() { var userUid = "2222"; if (userUid == string.Empty) { return(Unauthorized()); } string sessionId = ""; try { var options = new PaymentIntentCreateOptions { Amount = 1099, Currency = "usd", Metadata = new Dictionary <string, string>() { { "integration_check", "accept_a_payment" }, } }; var service = new PaymentIntentService(); var paymentIntent = await service.CreateAsync(options).ConfigureAwait(false); sessionId = paymentIntent.ClientSecret; } catch (Exception ex) { return(BadRequest()); } return(Ok(sessionId)); }
private string ProcessWebhookRequest(Order order, HttpRequest request, IDictionary <string, string> settings) { var apiKey = settings[settings["mode"] + "_secret_key"]; var webhookSecret = settings[settings["mode"] + "_webhook_secret"]; ConfigureStripe(apiKey); var stripeEvent = GetWebhookStripeEvent(request, webhookSecret); if (stripeEvent.Type == "payment_intent.amount_capturable_updated") // Occurs when payments are not auto captured and funds are authorized { var paymentIntent = (PaymentIntent)stripeEvent.Data.Object.Instance; FinalizeOrUpdateOrder(order, paymentIntent); } else if (stripeEvent.Type.StartsWith("charge.")) { var charge = (Charge)stripeEvent.Data.Object.Instance; if (!string.IsNullOrWhiteSpace(charge.PaymentIntentId)) { var paymentIntentService = new PaymentIntentService(); var paymentIntentGetOptions = new PaymentIntentGetOptions { }; var paymentIntent = paymentIntentService.Get(charge.PaymentIntentId, paymentIntentGetOptions); FinalizeOrUpdateOrder(order, paymentIntent); } } return(null); }
public async Task <IActionResult> Promote(PromoteBindingModel input) { if (!ModelState.IsValid) { return(Redirect($"/Advertisement/Promote?id={input.Id}")); } StripeConfiguration.ApiKey = configuration["Stripe:SecretKey"]; var prices = new Dictionary <string, int>() { { "1", 200 }, { "7", 600 }, { "14", 1000 }, { "30", 2000 } }; var service = new PaymentIntentService(); var options = new PaymentIntentCreateOptions { //amount is in cents Amount = prices[input.PromotedDays], Currency = "usd", // Verify your integration in this guide by including this parameter Metadata = new Dictionary <String, String>() { { "integration_check", "accept_a_payment" } } }; var payment = service.Create(options); await advertisementService.PromoteByIdAsync(input.Id, int.Parse(input.PromotedDays)); return(Redirect($"/User/Profile?page=1")); }