public IActionResult StripePost() { StripeConfiguration.ApiKey = "sk_test_51HKKyiJ1Wp4jNKPf1hA7WpHr2ABtPVe9l7gXmuWxOzjpkrmxVKVBVgwVQfP12P1fLLxaTVMFEY3LfY9fnJVCC1Af00N5Clyfht"; var options = new PaymentIntentCreateOptions { Amount = 2000, Currency = "bgn", PaymentMethodTypes = new List <string> { "card", } , }; var service = new PaymentIntentService(); service.Create(options); return(View()); }
public async Task <IActionResult> StartDeposit([FromBody] DepositCreationDto depositCreationDto) { if (!ModelState.IsValid) { return(BadRequest(new { message = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage) })); } try { StripeConfiguration.ApiKey = ServiceKey; var transferGroup = Guid.NewGuid().ToString(); var service = new PaymentIntentService(); var options = new PaymentIntentCreateOptions { Amount = depositCreationDto.Amount, Currency = "usd", PaymentMethodTypes = new List <string> { "card" }, Metadata = new Dictionary <string, string>() { { "UserId", User.FindFirstValue(ClaimTypes.Name) } }, TransferData = new PaymentIntentTransferDataOptions { Destination = (await _accountsRepository.GetByUserId(User.FindFirstValue(ClaimTypes.Name))).StripeUserId } }; var intent = service.Create(options); ; return(Ok(new PaymentIntentCreatedDto { ClientSecret = intent.ClientSecret })); } catch (Exception e) { return(BadRequest(new MessageObj(e.Message))); } }
public IActionResult InitiatePaymentIntent([FromBody] JsonElement body) { // Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys try { StripeConfiguration.ApiKey = _apiKey; var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var response = JsonSerializer.Deserialize <PaymentIntentRequest>(body.ToString(), options); var user = _merchantService.GetMerchantInfo(response.CompanyName); if (user == null) { return(NotFound("Merchant not found")); } var createOptions = new PaymentIntentCreateOptions { PaymentMethodTypes = new List <string> { "ideal", "card" }, Amount = response.Amount, Currency = "eur", ApplicationFeeAmount = 1, TransferData = new PaymentIntentTransferDataOptions { Destination = user.StripeAccountId } }; var service = new PaymentIntentService(); var intent = service.Create(createOptions); return(Ok(new { client_secret = intent.ClientSecret })); } catch (Exception e) { Log.Error($"{e}"); return(BadRequest()); } }
public AuthoriseResponse Authorise(AuthoriseRequest request) { AuthoriseResponse response = new AuthoriseResponse(); var options = new PaymentIntentCreateOptions { Amount = Convert.ToInt64(request.amount * 100), Currency = request.currency, PaymentMethodTypes = new List <string> { "card", }, CaptureMethod = "manual", //Metadata = request.metadata as Dictionary<string, string>, }; var service = new PaymentIntentService(); service.Create(options); return(response); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.activity_main); //StripeConfiguration.SetApiKey(""); //var options = new ConnectionTokenCreateOptions { }; //var service = new ConnectionTokenService(); //ConnectionToken connectionToken = service.Create(options); Terminal.InitTerminal(Android.App.Application.Context, Com.Stripe.Stripeterminal.LogLevel.Verbose, new ConnectionTokenProvider(), new TerminalListener()); DiscoveryConfiguration config = new DiscoveryConfiguration(0, DeviceType.Chipper2x, true); Terminal.Instance.DiscoverReaders(config, new DiscoveryListener(), new Callback()); Com.Stripe.Stripeterminal.Reader reader = DiscoveryListener.readers[0]; Terminal.Instance.ConnectReader(reader, new ReaderCallback()); var paymentIntentService = new PaymentIntentService(); var paymentIntentOptions = new PaymentIntentCreateOptions { Amount = 1000, Currency = "usd", PaymentMethodTypes = new List <string> { "card_present" }, CaptureMethod = "manual", }; Terminal.Instance.RetrievePaymentIntent( paymentIntentService.Create(paymentIntentOptions).ClientSecret, new PaymentIntentCallback()); Cancelable cancelable = Terminal.Instance.CollectPaymentMethod(PaymentIntentCallback.paymentIntent, new ReaderListener(), new PaymentIntentCallback()); Terminal.Instance.ProcessPayment(PaymentIntentCallback.paymentIntent, new PaymentIntentCallback()); var intent = paymentIntentService.Capture(PaymentIntentCallback.paymentIntent.Id, new PaymentIntentCaptureOptions()); }
public async Task <IActionResult> Pay() { StripeConfiguration.ApiKey = "sk_test_sd6hLSzaaSdWchuLII5rcYI700nJV5t5ee"; var options = new PaymentIntentCreateOptions { Amount = 1099, Currency = "gbp", // Verify your integration in this guide by including this parameter Metadata = new Dictionary <String, String> () { { "integration_check", "accept_a_payment" }, } }; var service = new PaymentIntentService(); var paymentIntent = service.Create(options); return(Ok(new { client_secret = paymentIntent.ClientSecret, id = paymentIntent.Id })); }
public IActionResult Index() { var cartIdCookie = GetEncryptedShopCookie("CART_ID"); if (cartIdCookie != null) { // if so, cast the cartId string into an int and provide it to the PopulateViewData method PopulateShopData(Convert.ToInt32(cartIdCookie)); } else { // no cart, so pass null for the cartId PopulateShopData(null); } var cartItems = (List <CartItem>)ViewData["CartItems"]; var totalAmount = cartItems.Sum(ci => ci.Quantity * ci.Product.Price); //decimal totalAmount = 0; //foreach (var cartItem in cartItems) //{ // var itemTotal = cartItem.Quantity * cartItem.Product.Price; // totalAmount = totalAmount + itemTotal; //} // Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys StripeConfiguration.ApiKey = "sk_test_2VH9I2XjnubbxPyiLOQR7VMJ"; var options = new PaymentIntentCreateOptions { Amount = Convert.ToInt64(totalAmount * 100), Currency = "aud", }; var service = new PaymentIntentService(); var paymentIntent = service.Create(options); ViewData["ClientSecret"] = paymentIntent.ClientSecret; return(View()); }
public Task <PaymentIntent> CreatePaymentIntent(string stripeSecretKey, long cost, string currency, Dictionary <string, string> metadata) { StripeConfiguration.ApiKey = stripeSecretKey; var options = new PaymentIntentCreateOptions { Amount = cost, Currency = currency, PaymentMethodTypes = new List <string>() { "card" }, Metadata = metadata }; var service = new PaymentIntentService(); var paymentIntent = service.Create(options); return(Task.FromResult <PaymentIntent>(paymentIntent)); }
public async Task <PaymentIntent> CreatePaymentIntent(PaymentPart paymentPart) { StripeConfiguration.ApiKey = ""; var options = new PaymentIntentCreateOptions { Amount = (long)paymentPart.Cost, Currency = "usd", // Verify your integrationsws in this guide by including this parameter Metadata = new Dictionary <string, string> { { "integration_checkk", "accept_a_paymentt" }, }, }; var service = new PaymentIntentService(); var paymentIntent = service.Create(options); return(paymentIntent); }
public async Task <IActionResult> Payment([FromBody][Required] int?price) { StripeConfiguration.ApiKey = "sk_test_DMFHsAZpG7JjAgLSAaWxCEE800SyfwhfoA"; var options = new PaymentIntentCreateOptions { Amount = price, Currency = "vnd", // Verify your integration in this guide by including this parameter Metadata = new Dictionary <string, string> { { "integration_check", "accept_a_payment" }, }, }; var service = new PaymentIntentService(); var paymentIntent = service.Create(options); return(Ok(new { scuccess = true, message = "Success", paymentIntent = paymentIntent })); }
private PaymentIntent createPaymentIntent(string paymentMethodId, int paymentAmount) { var paymentIntentService = new PaymentIntentService(); PaymentIntent paymentIntent = null; if (paymentMethodId != null) { // Create the PaymentIntent var createOptions = new PaymentIntentCreateOptions { PaymentMethodId = paymentMethodId, Amount = paymentAmount, Currency = "usd", ConfirmationMethod = "manual", Confirm = true, }; paymentIntent = paymentIntentService.Create(createOptions); } return(paymentIntent); }
public string Init(Entry entry) { if (entry.Cost == 0) { return("Unable to complete entry as cost can not be calculated, please contact support."); } entry.Paid = false; entry.DateOfBirth = DateTime.ParseExact(entry.DateOfBirthString, "dd/MM/yyyy", CultureInfo.InvariantCulture); string apiKey = ConfigurationManager.AppSettings["stripeSecretKey"]; StripeConfiguration.ApiKey = apiKey; int cost = entry.Cost * 100; var options = new PaymentIntentCreateOptions { Amount = cost, Currency = "gbp", ReceiptEmail = entry.Email, Description = $"{entry.RaceType} Entry", // Verify your integration in this guide by including this parameter Metadata = new Dictionary <string, string> { { "integration_check", "accept_a_payment" }, }, }; var service = new PaymentIntentService(); PaymentIntent paymentIntent = service.Create(options); entry.ClientSecret = paymentIntent.ClientSecret; string entryString = JsonConvert.SerializeObject(entry); Logger.Info(this.GetType(), "New entry request: {0}", () => entryString); entry = _entryRepository.Create(entry); return(paymentIntent.ClientSecret); }
public async Task <IActionResult> CreatePaymentIntent(long amount, string currency, string customerid) { var service = new PaymentIntentService(); var options = new PaymentIntentCreateOptions { Amount = amount, Currency = currency, PaymentMethodTypes = new List <string> { "card" }, Customer = customerid, Metadata = new Dictionary <string, string> { { "integration_check", "accept_a_payment" }, }, }; PaymentIntent PaymentIntent = service.Create(options); var response = await Task.FromResult(PaymentIntent); return(Ok(response)); }
//[HttpPost("create-payment-intent")] public async Task <IActionResult> Checkout() { var optionss = new PaymentIntentCreateOptions { Amount = ProductAmount /*1099*/, Currency = "usd", SetupFutureUsage = "off_session", //Customer = CustomerId }; var servicee = new PaymentIntentService(); var paymentIntent = servicee.Create(optionss); //return null; return(Ok(new { PublicKey, ClientSecret = paymentIntent.ClientSecret, Id = paymentIntent.Id })); }
public string Get(int total, string currency, string customer) { total = 50000; currency = "CAD"; customer = "cus_HWhZwYCqBmCxoU"; var intent = new PaymentIntentCreateOptions { Amount = total, Currency = currency, Customer = customer, SetupFutureUsage = "on_session", PaymentMethodTypes = new List <string> { "card" }, PaymentMethod = "pm_1GxeAPITcigAAz2yPakJ4Ce7" }; var service = new PaymentIntentService(); var paymentIntent = service.Create(intent); var options = new PaymentIntentConfirmOptions { PaymentMethod = "pm_1GxeAPITcigAAz2yPakJ4Ce7", }; var payment = new PaymentIntentService(); payment.Confirm( paymentIntent.Id, options ); var myClient = new clientSecret() { client_secret = paymentIntent.ClientSecret }; return(JsonSerializer.Serialize <clientSecret>(myClient)); }
protected PaymentIntent CreateStripeCharge(IStripeCharge stripeChargeParameters) { var service = new PaymentIntentService(); var transferOptions = new List <TransferCreateOptions>(); var chargeOptions = _stripeConnectCharger.StripePaymentIntentCreateOptions(stripeChargeParameters, GetStripeToken(stripeChargeParameters), ref transferOptions); PaymentIntent paymentIntent = service.Create(chargeOptions, new RequestOptions { ApiKey = GetStripeToken(stripeChargeParameters) }); try { //add transfers to DB scheduled for future. Cronjob will set those up daily. if (paymentIntent.Charges.Data.Count() > 0) { _stripeConnectCharger.AddFutureTransfers( transferOptions, stripeChargeParameters, paymentIntent.Charges.First().Id, chargeOptions.Currency, (FIL.Contracts.Enums.Channels)stripeChargeParameters.ChannelId); } } catch (Exception e) { _logger.Log(LogCategory.Error, new Exception("stripe connect future transfer", e)); } _transactionPaymentDetailRepository.Save(new TransactionPaymentDetail { TransactionId = Convert.ToInt64(stripeChargeParameters.TransactionId), PaymentOptionId = PaymentOptions.CreditCard, PaymentGatewayId = PaymentGateway.Stripe, RequestType = "Charge requesting", Amount = stripeChargeParameters.Amount.ToString(), PayConfNumber = "", UserCardDetailId = stripeChargeParameters.UserCardDetailId, PaymentDetail = "{\"Request\": {\"Amount\": \"" + chargeOptions.Amount + "\",\"Currency\": \"" + chargeOptions.Currency + "\",\"Description\": \"" + chargeOptions.Description + "\",\"SourceTokenOrExistingSourceId\": \"" + chargeOptions.SourceId + "\",\"StatementDescriptor\": \"" + chargeOptions.StatementDescriptor + "\"}}", }); return(paymentIntent); }
public ActionResult CheckOut(int submitId) { // return View(); StripeConfiguration.ApiKey = "sk_test_51H4bEIAVJDEhYcbP8AniC54IhmNxi8AOAkQpTgSCdwJjXwd8eoYEZmpBdZPOn7mpkBhQWkuzYYIFUv1y8Y3ncnKO008t1vsMSK"; var service = new PaymentIntentService(); var createOptions = new PaymentIntentCreateOptions() { PaymentMethodTypes = new List <string> { "card" }, Amount = CalculateOrderAmount(submitId) * 100, Currency = "usd", ApplicationFeeAmount = CalculateApplicationFee(submitId) * 100, TransferData = new PaymentIntentTransferDataOptions { Destination = "TutorAccountId", } }; service.Create(createOptions); return(RedirectToAction("Schedule", "User")); }
public IActionResult PaymentIntent(string emailCreator, int fee) { try { var accountResponse = _stripeService.GetByEmail(emailCreator); if (!accountResponse.DidError) { StripeConfiguration.ApiKey = "sk_test_51HvkPWGZgacNuBfZVUQCM2e3KO5iuMqwmIKnqujztMX0UvbkCyFJWhccLBPjKXxck92QwyMiVun9s7AS6zie6uFs00XbjswQBt"; var service = new PaymentIntentService(); var createOptions = new PaymentIntentCreateOptions { PaymentMethodTypes = new List<string> { "card", }, Amount = fee, Currency = "eur", ApplicationFeeAmount = (long?)(fee * 0.05), TransferData = new PaymentIntentTransferDataOptions { Destination = accountResponse.DTO.StripeAccountId, }, }; var serviceReponse = service.Create(createOptions); return Ok(serviceReponse.ClientSecret); } else { return BadRequest(); } } catch (Exception ex) { return BadRequest(ex.Message); } }
public PaymentIntent Authorize(decimal payAmount, bool isHold, string email, string ordersNumber, string firstName, string lastName, string descriptionPayment, string paymentMethod, string externalId, string transactionIds, string userId, long orderId, long transactionId, Guid correlationId) { var options = new PaymentIntentCreateOptions { Amount = (long)(payAmount * 100), Currency = "USD", CaptureMethod = isHold ? "manual" : "automatic", Confirm = true, ReceiptEmail = email, Description = $"Checkout order {ordersNumber}- Customer {firstName} {lastName} - {descriptionPayment}", PaymentMethod = paymentMethod, Customer = externalId, Metadata = new Dictionary <string, string> { { "TransactionIds", transactionIds } } }; var service = new PaymentIntentService(); PaymentIntent paymentIntent = service.Create(options); return(paymentIntent); }
private void HandleStripePaymentIfPaymentMethodIsStripe( Entities.PaymentMethod chosenPaymentMethod, Order order, string stripeSecretKey ) { if (chosenPaymentMethod.Method == MethodOfPayment.Stripe) { /** If payment by Stripe */ StripeConfiguration.ApiKey = stripeSecretKey; var options = new PaymentIntentCreateOptions { Amount = (long?)order.TotalAmount, Currency = "vnd", }; var stripeService = new PaymentIntentService(); var paymentIntent = stripeService.Create(options); order.PaymentIntentId = paymentIntent.Id; order.StripeClientSecret = paymentIntent.ClientSecret; } }
public ActionResult Index() { // Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys StripeConfiguration.ApiKey = "sk_test_51Gy9HFFpAeHvoOJGeTIYoZ6tQsbY30DbGfY6OOu38CuNTuf6tykHW5eChnLi50Aa1HJhusgG8QNnqenqOTLD7PCM00FAoO8sEP"; var options = new PaymentIntentCreateOptions { Amount = 1099, Currency = "sgd", // Verify your integration in this guide by including this parameter Metadata = new Dictionary <string, string> { { "integration_check", "accept_a_payment" }, }, }; var service = new PaymentIntentService(); var intent = service.Create(options); ViewData["ClientSecret"] = intent.ClientSecret; return(View()); }
public IActionResult Index([FromBody] ConfirmPaymentRequest request) { var paymentIntentService = new PaymentIntentService(); PaymentIntent paymentIntent = null; try { if (request.PaymentMethodId != null) { // Create the PaymentIntent var createOptions = new PaymentIntentCreateOptions { PaymentMethodId = request.PaymentMethodId, Amount = 1099, Currency = "gbp", ConfirmationMethod = "manual", Confirm = true, }; paymentIntent = paymentIntentService.Create(createOptions); } if (request.PaymentIntentId != null) { var confirmOptions = new PaymentIntentConfirmOptions { }; paymentIntent = paymentIntentService.Confirm( request.PaymentIntentId, confirmOptions ); } } catch (StripeException e) { return(Json(new { error = e.StripeError.Message })); } return(generatePaymentResponse(paymentIntent)); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // Create a payment intent, expose it's client secret publicly. var options = new PaymentIntentCreateOptions { Amount = 10000, Currency = "usd", PaymentMethodTypes = new List <string> { "card", }, }; var service = new PaymentIntentService(); var paymentIntent = service.Create(options); clientSecret = paymentIntent.ClientSecret; } else { // Handle post request from form submission // Put payment information in the database } }
public void create_payment_intent() { // Set your secret key. Remember to switch to your live secret key in production! // See your keys here: https://dashboard.stripe.com/account/apikeys StripeConfiguration.ApiKey = "sk_test_OqgRgzijpOeoqyZzh7TWFYuH00ic6FnP88"; var service = new PaymentIntentService(); var createOptions = new PaymentIntentCreateOptions { PaymentMethodTypes = new List <string> { "card", }, Amount = 2000, Currency = "usd", ApplicationFeeAmount = 123, TransferData = new PaymentIntentTransferDataOptions { Destination = "{{CONNECTED_STRIPE_ACCOUNT_ID}}", }, }; service.Create(createOptions); }
private string ProcessCaptureRequest(Order order, HttpRequest request, IDictionary <string, string> settings) { var apiKey = settings[settings["mode"] + "_secret_key"]; ConfigureStripe(apiKey); try { var capture = settings.ContainsKey("capture") && settings["capture"].Trim().ToLower() == "true"; PaymentIntent intent; var intentService = new PaymentIntentService(); var paymentIntentId = request.Form["stripePaymentIntentId"]; // If we don't have a stripe payment intent passed in then we create a payment // and try to create / capture it if (string.IsNullOrWhiteSpace(paymentIntentId)) { var intentOptions = new PaymentIntentCreateOptions { PaymentMethod = request.Form["stripePaymentMethodId"], Amount = DollarsToCents(order.TotalPrice.Value.WithVat), Currency = CurrencyService.Instance.Get(order.StoreId, order.CurrencyId).IsoCode, Description = $"{order.CartNumber} - {order.PaymentInformation.Email}", Metadata = new Dictionary <string, string> { { "orderId", order.Id.ToString() }, { "cartNumber", order.CartNumber } }, ConfirmationMethod = "manual", Confirm = true, CaptureMethod = capture ? "automatic" : "manual" }; if (settings.ContainsKey("send_stripe_receipt") && settings["send_stripe_receipt"] == "true") { intentOptions.ReceiptEmail = order.PaymentInformation.Email; } intent = intentService.Create(intentOptions); order.Properties.AddOrUpdate(new CustomProperty("stripePaymentIntentId", intent.Id) { ServerSideOnly = true }); order.TransactionInformation.PaymentState = PaymentState.Initialized; if (intent.Status != "succeeded") { order.Save(); } } // If we have a stripe payment intent then it means it wasn't confirmed first time around // so just try and confirm it again else { intent = intentService.Confirm(request.Form["stripePaymentIntentId"], new PaymentIntentConfirmOptions { PaymentMethod = request.Form["stripePaymentMethodId"] }); } if (intent.Status == "succeeded") { FinalizeOrUpdateOrder(order, intent); return(JsonConvert.SerializeObject(new { success = true })); } else if (intent.Status == "requires_action" && intent.NextAction.Type == "use_stripe_sdk") { return(JsonConvert.SerializeObject(new { requires_card_action = true, payment_intent_client_secret = intent.ClientSecret })); } return(JsonConvert.SerializeObject(new { error = "Invalid payment intent status" })); } catch (Exception ex) { LoggingService.Instance.Error <Stripe>("Stripe(" + order.CartNumber + ") - ProcessCaptureRequest", ex); return(JsonConvert.SerializeObject(new { error = ex.Message })); } }
public async Task <ActionResult <StripeResult> > Post([FromBody] StripeCharge request) { StripeConfiguration.ApiKey = StripeApiKey; PaymentIntentService service = new PaymentIntentService(); PaymentIntent paymentIntent; StripeResult result = new StripeResult(); Order order = _context.orders.Find(request.CartId); // First pass if (request.PaymentMethodId != null) { PaymentIntentCreateOptions options = new PaymentIntentCreateOptions { PaymentMethod = request.PaymentMethodId, Amount = request.TotalCost, Currency = "nok", Description = "Purchase from VippsCase.", ConfirmationMethod = "manual", Confirm = true, }; try { paymentIntent = service.Create(options, new RequestOptions { IdempotencyKey = order.IdempotencyToken }); // Check the user making the purchase User user; if (request.UserId == -1) { // Adding a new customer if one was not specified in the request user = new User { Name = request.CustomerDetails.FullName, AddressLineOne = request.CustomerDetails.AddressLineOne, AddressLineTwo = request.CustomerDetails.AddressLineTwo, County = request.CustomerDetails.County, PostalCode = request.CustomerDetails.PostalCode, City = request.CustomerDetails.City, Country = request.CustomerDetails.Country, PhoneNumber = request.CustomerDetails.PhoneNumber, Email = request.CustomerDetails.Email }; // Storing our customer details. _context.users.Add(user); } else { // Find the user matching the userId and add them to the order. user = _context.users.Find(request.UserId); } // Setting the user and charge to the user we just made and the charge token. order.StripeChargeToken = paymentIntent.Id; order.UserId = user.UserId; // Saving all of our changes. await _context.SaveChangesAsync(); } catch (StripeException exception) { // Idempotency special handling if (exception.StripeError.ErrorType == "idempotency_error" || exception.StripeError.DeclineCode == "duplicate_transaction" || exception.StripeError.Code == "duplicate_transaction") { result.Success = true; } else { // When an order fails due to an issue with stripe, // we'll assign the order a new idempotency key to prevent the "idempotency_error" from stripe. order.IdempotencyToken = Guid.NewGuid().ToString(); await _context.SaveChangesAsync(); // Return the error message to the user. result.Success = false; result.Error = _stripeErrorHandler.ErrorHandler(exception); } return(result); } } // Second pass else { PaymentIntentConfirmOptions options = new PaymentIntentConfirmOptions { }; try { paymentIntent = service.Confirm(request.PaymentIntentId, options); } catch (StripeException exception) { // When an order fails due to an issue with stripe, // we'll assign the order a new idempotency key to prevent the "idempotency_error" from stripe. order.IdempotencyToken = Guid.NewGuid().ToString(); await _context.SaveChangesAsync(); // Return the error message to the user. result.Success = false; result.Error = _stripeErrorHandler.ErrorHandler(exception); return(result); } } switch (paymentIntent.Status) { case "requires_action" when paymentIntent.NextAction.Type == "use_stripe_sdk": // Tell the client to handle the action result.Data = new { requires_action = true, payment_intent_client_secret = paymentIntent.ClientSecret }; result.Success = false; break; case "succeeded": // The payment didn't need any additional actions and completed! // Handle post-payment fulfillment result.Success = true; break; default: // Invalid status // TODO: Change this error message to be user-friendly result.Error = "Invalid PaymentIntent status"; result.Success = false; break; } return(result); }
public ActionResult PotvrdiUplatu(PaymentIntentConfirmRequest request) { var narudzba = _context.Rezervacija.Where(x => x.RezervacijaId == request.RezervacijaId && x.StanjeRezervacije == Data.EntityModels.StanjeRezervacije.ekanje_uplate).FirstOrDefault(); if (narudzba == null) { return(new JsonResult(new { error = "Narudžba nije u ispravnom stanju." })); } var narudzba_iznos = (int)narudzba.UkupniIznos * 100; if (narudzba_iznos == 0) { return(new JsonResult(new { error = "Iznos narudžbe je neispravan." })); } var paymentIntents = new PaymentIntentService(); var paymentIntent = paymentIntents.Create(new PaymentIntentCreateOptions { Amount = narudzba_iznos, Currency = "usd", Confirm = true, Metadata = new Dictionary <string, string>(), PaymentMethod = request.PaymentMethodId }); paymentIntent.Metadata["RezervacijaId"] = request.RezervacijaId.ToString(); if (paymentIntent.Amount == narudzba_iznos && paymentIntent.Status == "succeeded") { narudzba.StanjeRezervacije = Data.EntityModels.StanjeRezervacije.U_obradi; if (narudzba.DatumUplate is null) { narudzba.DatumUplate = DateTime.Now; } _context.SaveChanges(); bool IsServisRezervacija = narudzba.RezervacijaServis.Any(), IsTerminRezervacija = narudzba.RezervacijaIznajmljenaBicikla.Any(); if (IsServisRezervacija || IsTerminRezervacija || narudzba.NacinPlacanja == "online") { var zaposlenici = _context.Zaposlenik.Where(x => x.Korisnik.Aktivan == true).ToList(); foreach (var zaposlenik in zaposlenici) { var notifikacija = new Data.EntityModels.Notifikacija { ZaposlenikId = zaposlenik.Id, Rezervacija = narudzba, DatumVrijeme = DateTime.Now }; if (IsServisRezervacija) { notifikacija.Tip = Data.EntityModels.TipNotifikacije.Novi_Servis; } else if (IsTerminRezervacija) { notifikacija.Tip = Data.EntityModels.TipNotifikacije.Novi_Termin; } else { notifikacija.Tip = Data.EntityModels.TipNotifikacije.Nova_Narudzba; } _context.Notifikacija.Add(notifikacija); } } return(new JsonResult(new { clientSecret = paymentIntent.ClientSecret })); } return(new JsonResult(new { error = paymentIntent.Status })); }
public async Task <IActionResult> Confirmar(int?id, int opcionElegida) { Usuario usuario = await _usuariosService.GetUsuarioByActiveIdentityUser(_userManager.GetUserId(User)); Producto producto = await _productosService.GetProductoById(id); List <OpcionProducto> opciones = await _opcionesProductosService.GetOpcionProductoById(id); OpcionProducto opcion = opciones[opcionElegida - 1]; ProductoVendedor productoVendedor = producto.ProductoVendedor[0]; Vendedor vendedor = await _vendedoresService.GetVendedorById(productoVendedor.VendedorId); UsuarioProductoVM modelo = new UsuarioProductoVM { producto = producto, usuario = usuario, opcion = opcion }; int precioFinal = Convert.ToInt32(opcion.PrecioFinal * 100); float fee = vendedor.Fee; int helduFee = Convert.ToInt32(precioFinal * (fee / 100)); StripeConfiguration.ApiKey = "sk_test_51GvJEQL9UURBAADxXJtmn6ZmPepnp0Bkt4Hwl3y53I7rjWCQKa4wj3FSfkm2V4ZOIV67I6LQDmfvPmZ16eMh9LcE0057FViwnl"; var service = new PaymentIntentService(); var createOptions = new PaymentIntentCreateOptions { PaymentMethodTypes = new List <string> { "card", }, Amount = precioFinal, Currency = "eur", ApplicationFeeAmount = helduFee, ReceiptEmail = "*****@*****.**", Metadata = new Dictionary <string, string> { { "ProductoId", Convert.ToString(producto.Id) }, { "Producto", producto.Titulo }, { "OpcionId", opcion.Id.ToString() }, { "Opcion", opcion.Descripcion }, { "PrecioOriginal", opcion.PrecioInicial.ToString() }, { "UsuarioId", Convert.ToString(usuario.Id) }, { "Usuario", usuario.NombreUsuario }, { "VendedorId", vendedor.Id.ToString() }, { "Vendedor", vendedor.NombreDeEmpresa } }, TransferData = new PaymentIntentTransferDataOptions() { Destination = "acct_1H08zjLhTBm3kv5q" }, //TransferData = new PaymentIntentTransferDataOptions //{ // Destination = "acct_1H08zjLhTBm3kv5q", //}, }; var intent = service.Create(createOptions); ViewData["ClientSecret"] = intent.ClientSecret; return(View(modelo)); }
public JsonResult Stripe(string order_id, string pi_id) { try { StripeConfiguration.ApiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; if (String.IsNullOrEmpty(pi_id)) { var options = new PaymentIntentCreateOptions { Amount = 2000, Currency = "usd", //CaptureMethod = "manual", PaymentMethodTypes = new List <string> { "card", }, PaymentMethodOptions = new PaymentIntentPaymentMethodOptionsOptions { Card = new PaymentIntentPaymentMethodOptionsCardOptions { RequestThreeDSecure = "any" } }, ReceiptEmail = "*****@*****.**" }; var service = new PaymentIntentService(); var create = service.Create(options); return(Json(new { status = "Success", response = create })); } else { /* * var service = new PaymentIntentService(); * var options = new PaymentIntentCaptureOptions * { * //ReturnUrl = "https://example.com/return_url", * }; * var intent = service.Capture(pi_id, options); * return Json(new { status = "Success", response = intent }); */ var options = new ChargeListOptions { Limit = 100, PaymentIntent = pi_id }; var service = new ChargeService(); StripeList <Charge> charges = service.List(options); return(Json(new { status = "Success", response = charges })); } } catch (StripeException se) { Response.StatusCode = (int)se.HttpStatusCode; return(Json(new { status = "Failure", code = se.HttpStatusCode, message = se.Message, data = se.Data, error = se.StripeError, response = se.StripeResponse })); } }
public async Task <IActionResult> Stripe([FromBody] ConfirmPaymentRequest request) { var paymentIntentService = new PaymentIntentService(); PaymentIntent paymentIntent = null; try { if (request.PaymentMethodId != null) { //Needed objects var course = _courseService.GetCourse(request.CourseId); var invoice = _paymentService.GetInvoice(request.InvoiceNumber); var user = await _context.Users.FindAsync(_access.GetUserId(User)); var description = ""; // if (user == null) // return BadRequest(new {result = EnumList.PaymentResult.Failed.ToString(), message = "error", courseId, invoiceNumber,reason = reason.ToString()}); //ToDo :: Handle the return of bad request decimal amountToPay = 0; switch (request.Reason) { case EnumList.PaymentReason.Register: //Check if course null if (course == null) // ToDo :: Handle bad request return { return(BadRequest(new { userId = user.Id, result = EnumList.PaymentResult.Failed.ToString(), message = "error", request.CourseId, request.InvoiceNumber, reason = request.Reason.ToString() })); } //Get on register invoice var registerInvoice = _paymentService.CreateOnRegisterInvoices(request.CourseId, user) .SingleOrDefault(x => x.Reason == EnumList.InvoiceReason.Registration); //Determine the amount user wants to pay now if (request.PayAllNow) { amountToPay = course.Price; } else { amountToPay = registerInvoice?.Amount ?? 0; } description = $"Charge for {user.FirstName} {user.LastName} - {user.Email} For Course {course.Subject}-{course.Code} Payment: {amountToPay} kr"; break; case EnumList.PaymentReason.Invoice: //Check if invoice is null if (invoice == null || !invoice.ActiveInvoice()) { return(BadRequest(new { userId = user.Id, result = EnumList.PaymentResult.Failed.ToString(), message = "error", request.CourseId, request.InvoiceNumber, reason = request.Reason.ToString() })); } amountToPay = invoice.CurrentAmount; description = $"Betaling av {user.FirstName} {user.LastName} - Fakturanummer: {invoice.Number} - KID-nummer: {invoice.CIDNumber}"; break; case EnumList.PaymentReason.Empty: case EnumList.PaymentReason.Donate: case EnumList.PaymentReason.Other: default: return(BadRequest(new { userId = user.Id, result = EnumList.PaymentResult.Failed.ToString(), message = "error", request.CourseId, request.InvoiceNumber, reason = request.Reason.ToString() })); } //ToDo :: If amount to pay is 0 return Bad Request var customerOptions = new CustomerCreateOptions { Description = $"{user.FirstName +" "+ user.LastName}", Name = $"{user.FirstName +" "+ user.LastName}", PaymentMethod = request.PaymentMethodId, Email = $"{user.Email}", Metadata = new Dictionary <string, string> { { "UniqueId", $"USERID-{user.Id}-COURSE-{course.Id}-{Format.NorwayDateTimeNow().Year}" } } }; var customerService = new CustomerService(); var customer = customerService.Create(customerOptions); // Create the PaymentIntent var createOptions = new PaymentIntentCreateOptions { Amount = (int)amountToPay * 100, Currency = "nok", Description = description, Customer = customer.Id, ReceiptEmail = $"{user.Email}", PaymentMethod = request.PaymentMethodId, ConfirmationMethod = "manual", Confirm = true, }; paymentIntent = paymentIntentService.Create(createOptions); var initiatedOrder = new InitiatedOrder { Id = paymentIntent.Id, User = user, CourseId = request.CourseId, InvoiceNumber = request.InvoiceNumber, Amount = amountToPay, PaymentMethod = EnumList.PaymentMethod.Stripe, Reason = request.Reason, Status = EnumList.OrderStatus.Initiated, Ip = request.Ip, OperatingSystem = request.OperatingSystem, DeviceType = request.DeviceType, AuthCookies = request.AuthCookies, PayAllNow = request.PayAllNow }; await _context.AddAsync(initiatedOrder); await _context.SaveChangesAsync(); } if (request.PaymentIntentId != null) { var confirmOptions = new PaymentIntentConfirmOptions { }; paymentIntent = paymentIntentService.Confirm( request.PaymentIntentId, confirmOptions ); } } catch (StripeException e) { return(Json(new { error = e.StripeError.Message })); } return(GeneratePaymentResponse(paymentIntent)); }