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)); }
protected PaymentState GetPaymentState(PaymentIntent paymentIntent) { // Possible PaymentIntent statuses: // - requires_payment_method // - requires_confirmation // - requires_action // - processing // - requires_capture // - canceled // - succeeded if (paymentIntent.Status == "canceled") { return(PaymentState.Cancelled); } if (paymentIntent.Status == "requires_capture") { return(PaymentState.Authorized); } if (paymentIntent.Status == "succeeded") { if (paymentIntent.Charges.Data.Any()) { return(GetPaymentState(paymentIntent.Charges.Data[0])); } else { return(PaymentState.Captured); } } return(PaymentState.Initialized); }
private IActionResult generatePaymentResponse(PaymentIntent intent) { // Note that if your API version is before 2019-02-11, 'requires_action' // appears as 'requires_source_action'. if (intent.Status == "requires_action" && intent.NextAction.Type == "use_stripe_sdk") { // Tell the client to handle the action return(Json(new { requires_action = true, payment_intent_client_secret = intent.ClientSecret })); } else if (intent.Status == "succeeded") { // The payment didn’t need any additional actions and completed! // Handle post-payment fulfillment return(Json(new { success = true })); } else { // Invalid status return(StatusCode(500, new { error = "Invalid PaymentIntent status" })); } }
public PaymentRequestBuilder WithMobilePayTestValues(string payeeId) { this.operation = Operation.Purchase; this.intent = PaymentIntent.Authorization; this.currency = new Currency("SEK"); this.description = "Test Description"; this.payerReference = "AB1234"; this.userAgent = "useragent"; this.language = new Language("sv-SE"); SetUrls(); this.payeeInfo = new PayeeInfo(payeeId, DateTime.Now.Ticks.ToString()) { PayeeName = "payeeName", ProductCategory = "productCategory" }; this.prefillInfo = new PrefillInfo(new Msisdn("+46701234567")); this.amount = new Amount(1600); this.vatAmount = new Amount(0); this.metadata = new Metadata { { "key1", "value1" }, { "key2", 2 }, { "key3", 3.1 }, { "key4", false } }; this.shopslogoUrl = new Uri("https://example.com"); this.prices = new List <IPrice> { new Price(this.amount, PriceType.Visa, this.vatAmount) }; return(this); }
public async Task <ActionResult> StripeWebHook() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], _configuration["StripeSettings:WhSecret"]); PaymentIntent intent = null; Order order = null; switch (stripeEvent.Type) { case "payment_intent.succeeded": intent = (PaymentIntent)stripeEvent.Data.Object; _logger.LogInformation("Paymnet succeed: " + intent.Id); //TODO: Update Order Status order = await _paymentService.UpdatePaymentIntentSucceeded(intent.Id); _logger.LogInformation("Payment Review with Order: " + order.Id); break; case "payment_intent.payment_failed": intent = (PaymentIntent)stripeEvent.Data.Object; _logger.LogInformation("Paymnet failed: " + intent.Id); //TODO: Update Order Status order = await _paymentService.UpdatePaymentIntentFailed(intent.Id); _logger.LogInformation("Payment Failed with Order: " + order.Id); break; } return(new EmptyResult()); }
/// <summary> /// Stripe Webhook /// </summary> /// <param name="paymentIntent"></param> /// <returns></returns> public async Task HandlePaymentIntentCanceled(PaymentIntent paymentIntent) { var clientSecret = paymentIntent.ClientSecret; var order = await GetOrderAsync(clientSecret); await HandlePaymentIntentNotSuccess(paymentIntent, order, OrderStatusEnum.CANCELED); }
/// <summary> /// Instantiates a <see cref="VippsPaymentRequestDetails"/> with the provided parameters. /// </summary> /// <param name="operation">The initial operation of this payment.</param> /// <param name="intent">The intent of this payment.</param> /// <param name="currency">The wanted currency of the payment.</param> /// <param name="prices">List of payment instrument prices.</param> /// <param name="description">Textual description of the payment.</param> /// <param name="payerReference">Merchant reference to the payer.</param> /// <param name="userAgent">The payers UserAgent string.</param> /// <param name="language">The payers prefered language.</param> /// <param name="urls">Object with relevant URLs for the payment.</param> /// <param name="payeeInfo">Object with information about the merchant.</param> protected internal VippsPaymentRequestDetails(Operation operation, PaymentIntent intent, Currency currency, IEnumerable <IPrice> prices, string description, string payerReference, string userAgent, Language language, IUrls urls, IPayeeInfo payeeInfo) { Operation = operation ?? throw new ArgumentNullException(nameof(operation)); Intent = intent; Currency = currency; Description = description; PayerReference = payerReference; UserAgent = userAgent; Language = language; Urls = urls; PayeeInfo = payeeInfo; foreach (var price in prices) { Prices.Add(price); } }
public async Task when_a_valid_intent_is_provided_it_is_successful_and_saved_to_the_database() { var eventStore = new EventStore(new InMemoryStorageEngine()); var factory = new WebApplicationFactory <Startup>().WithWebHostBuilder(configuration => { configuration.ConfigureTestServices(services => services.AddSingleton(eventStore)); }); var client = factory.CreateClient(); var paymentReference = Guid.NewGuid().ToString("D"); var paymentIntent = new PaymentIntent( new TransactionAmount(100m, "GBP") ); var result = await client.PostAsJsonAsync($"/payments/{paymentReference}", paymentIntent); var stream = await eventStore.ReadStreamForwards(paymentReference); Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.Single(stream); Assert.IsType <PaymentIntentAdded>(stream.Single().EventBody); }
public AuthorizeResponse Authorize(AuthorizeRequest authorizeRequest) { PaymentIntent paymentIntent = _adaptee.Authorize(authorizeRequest.Amount, authorizeRequest.IsHold, authorizeRequest.Email, authorizeRequest.OrdersNumber, authorizeRequest.FirstName, authorizeRequest.LastName, authorizeRequest.DescriptionPayment, authorizeRequest.PaymentMethod, authorizeRequest.MerchantId, authorizeRequest.TransactionIds, authorizeRequest.UserId, authorizeRequest.OrderId, authorizeRequest.TransactionId, authorizeRequest.CorrelationId); return(new AuthorizeResponse() { Status = paymentIntent.Status, PaymentId = paymentIntent.Id, PaymentDate = paymentIntent.Created, PaymentCardId = paymentIntent.PaymentMethodId, PaymentFee = paymentIntent.ApplicationFeeAmount }); }
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); }
private async Task HandlePaymentIntentNotSuccess(PaymentIntent paymentIntent, Data.Entities.Order order, OrderStatusEnum orderStatus) { var statusInformation = orderStatus == OrderStatusEnum.CANCELED ? paymentIntent.CancellationReason : paymentIntent.LastPaymentError?.Message; if (order == null) { order = new Data.Entities.Order { ExternalId = paymentIntent.ClientSecret, Amount = paymentIntent.Amount / 100m, Status = orderStatus, StatusInformation = statusInformation, PaymentMethod = PaymentMethodEnum.STRIPE, CreatedAt = DateTime.UtcNow, ModifiedAt = DateTime.UtcNow }; await _uow.OrderRepository.AddAsync(order); await _uow.CommitAsync(); } else { order.Status = orderStatus; order.StatusInformation = statusInformation; order.ModifiedAt = DateTime.UtcNow; await _uow.OrderRepository.UpdateAsync(order, order.Id); await _uow.CommitAsync(); } }
private IHttpActionResult ConfirmEntry(PaymentIntent paymentIntent) { var entry = _entryRepository.Get(paymentIntent.ClientSecret); if (entry == null) { Logger.Warn(this.GetType(), $"Unable to locate entry with client secret: {paymentIntent.ClientSecret}"); return(BadRequest()); } entry.OrderReference = paymentIntent.Id; entry.Paid = true; _entryRepository.Update(entry); var entryPage = Umbraco.TypedContentAtRoot().First().Children.FirstOrDefault(c => c.DocumentTypeAlias == "entry"); var subject = (string)entryPage?.GetProperty("confirmationEmailSubject")?.Value; var bodyProp = entryPage?.GetProperty("confirmationEmailBody")?.Value as HtmlString; var body = bodyProp.ToHtmlString().Replace("/{{Domain}}", "https://midsussextriathlon.com"); _emailService.SendConfirmationEmail(entry, subject, body); _emailService.SendAdminConfirmationEmail(entry); return(Ok()); }
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); }
protected override async Task BuildTransaction(string password, PaymentIntent payments, FeeStrategy feeStrategy, bool allowUnconfirmed = false, IEnumerable <OutPoint> allowedInputs = null) { BuildTransactionResult result = await Task.Run(() => Wallet.BuildTransaction(Password, payments, feeStrategy, allowUnconfirmed: true, allowedInputs: allowedInputs, GetPayjoinClient())); MainWindowViewModel.Instance.StatusBar.TryAddStatus(StatusType.SigningTransaction); SmartTransaction signedTransaction = result.Transaction; if (Wallet.KeyManager.IsHardwareWallet && !result.Signed) // If hardware but still has a privkey then it's password, then meh. { try { IsHardwareBusy = true; MainWindowViewModel.Instance.StatusBar.TryAddStatus(StatusType.AcquiringSignatureFromHardwareWallet); var client = new HwiClient(Global.Network); using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(3)); PSBT signedPsbt = null; try { try { signedPsbt = await client.SignTxAsync(Wallet.KeyManager.MasterFingerprint.Value, result.Psbt, cts.Token); } catch (PSBTException ex) when(ex.Message.Contains("NullFail")) { NotificationHelpers.Warning("Fall back to Unverified Inputs Mode, trying to sign again."); // Ledger Nano S hackfix https://github.com/MetacoSA/NBitcoin/pull/888 var noinputtx = result.Psbt.Clone(); foreach (var input in noinputtx.Inputs) { input.NonWitnessUtxo = null; } signedPsbt = await client.SignTxAsync(Wallet.KeyManager.MasterFingerprint.Value, noinputtx, cts.Token); } } catch (HwiException) { await PinPadViewModel.UnlockAsync(); signedPsbt = await client.SignTxAsync(Wallet.KeyManager.MasterFingerprint.Value, result.Psbt, cts.Token); } signedTransaction = signedPsbt.ExtractSmartTransaction(result.Transaction); } finally { MainWindowViewModel.Instance.StatusBar.TryRemoveStatus(StatusType.AcquiringSignatureFromHardwareWallet); IsHardwareBusy = false; } } MainWindowViewModel.Instance.StatusBar.TryAddStatus(StatusType.BroadcastingTransaction); await Task.Run(async() => await Global.TransactionBroadcaster.SendTransactionAsync(signedTransaction)); ResetUi(); }
public async Task <IActionResult> PaymentIntentSuccess(PaymentIntent paymentIntent) { //TODO: This should be a webhook, but multi tenancy brings on challenges var paymentSuccessEventHandlers = _serviceProvider.GetRequiredService <IEnumerable <IPaymentSuccessEventHandler> >(); await paymentSuccessEventHandlers.InvokeAsync(x => x.PaymentSuccess(paymentIntent.Id, "Stripe", paymentIntent.Metadata), _logger); return(Ok()); }
private PaymentIntent GetPaymentIntent(string paymentIntentId) { StripeConfiguration.ApiKey = ApiSecretKey; var service = new PaymentIntentService(); PaymentIntent intent = service.Get(paymentIntentId); return(intent); }
/// <summary> /// Instantiates a new Verify request for a card payment. /// </summary> /// <param name="intent"></param> /// <param name="currency"></param> /// <param name="description"></param> /// <param name="userAgent"></param> /// <param name="language"></param> /// <param name="urls"></param> /// <param name="payeeInfo"></param> public CardPaymentVerifyRequestDetails(PaymentIntent intent, Currency currency, string description, string userAgent, Language language, IUrls urls, IPayeeInfo payeeInfo) { Intent = intent; Currency = currency; Description = description; UserAgent = userAgent; Language = language; Urls = urls; PayeeInfo = payeeInfo; }
/// <summary> /// Instantiates a new <see cref="CardPaymentRequest"/> using the provided parameters. /// </summary> /// <param name="intent">The initial intent of this payment.</param> /// <param name="currency">The wanted <seealso cref="Currency"/> for the payment to be paid in.</param> /// <param name="description">A textual description of the payment.</param> /// <param name="userAgent">The payers UserAgent.</param> /// <param name="language">The prefered <seealso cref="Language"/> of the payer.</param> /// <param name="urls">Object holding relevant <seealso cref="IUrls"/> for the payment.</param> /// <param name="payeeInfo">Object identifying the payee.</param> public CardPaymentVerifyRequest(PaymentIntent intent, Currency currency, string description, string userAgent, Language language, IUrls urls, IPayeeInfo payeeInfo) { Payment = new CardPaymentVerifyRequestDetails(intent, currency, description, userAgent, language, urls, payeeInfo); }
// GET: JobBids/Pay/5 public ActionResult Pay(int id) { var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); var foundUser = _repo.Trucker.FindByCondition(a => a.IdentityUserId == userId).SingleOrDefault(); var jobBid = _repo.JobBid.FindByCondition(a => a.JobId == id).SingleOrDefault(); jobBid.Job = _repo.Job.FindByCondition(a => a.JobId == jobBid.JobId).SingleOrDefault(); var intent = new PaymentIntent(); return(View(jobBid)); }
public IActionResult Post([FromBody] PaymentIntent intent, string paymentReference) { if (!ModelState.IsValid) { return(new ValidationErrorResult(ModelState)); } eventStore.AppendToStream(paymentReference, 0, new EventData(Guid.NewGuid(), new PaymentIntentAdded())); return(Ok()); }
public CancelResponse Cancel(CancelRequest cancelRequest) { PaymentIntent paymentIntent = _adaptee.Cancel(cancelRequest.PaymentId, cancelRequest.UserId, cancelRequest.OrderId, cancelRequest.TransactionId, cancelRequest.CorrelationId); return(new CancelResponse() { Status = paymentIntent.Status }); }
public async Task <Holiday> PaymentSuccessful(PaymentIntent paymentIntent) { var pendingBooking = await _repo.GetPendingBookingByPaymentIntentId(paymentIntent.Id); if (pendingBooking == null) { return(null); } var holiday = await _bookingService.UpdatesForNewBooking(pendingBooking, paymentIntent); return(holiday); }
protected override async Task BuildTransaction(string password, PaymentIntent payments, FeeStrategy feeStrategy, bool allowUnconfirmed = false, IEnumerable <OutPoint> allowedInputs = null) { BuildTransactionResult result = await Task.Run(() => Wallet.BuildTransaction(Password, payments, feeStrategy, allowUnconfirmed: true, allowedInputs: allowedInputs)); var txviewer = new TransactionViewerViewModel(); IoC.Get <IShell>().AddDocument(txviewer); IoC.Get <IShell>().Select(txviewer); txviewer.Update(result); ResetUi(); NotificationHelpers.Success("Transaction was built."); }
public async Task <IActionResult> GetIntent(string subscriptionName) { string userId = ""; try { // Il faut utiliser le Claim pour retrouver l'identifiant de l'utilisateur userId = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").SingleOrDefault().Value; } catch (Exception) { return(BadRequest("No user found")); } AspNetUser user = _LoveMirroringcontext.AspNetUsers.Where(u => u.Id == userId).SingleOrDefault(); Models.Subscription subscription = await _LoveMirroringcontext.Subscriptions. Where(s => s.SubscriptionName == subscriptionName). SingleOrDefaultAsync(); if (subscription != null) { StripeConfiguration.ApiKey = Configuration["Stripe:ApiKey"]; PaymentIntentCreateOptions options = new PaymentIntentCreateOptions { // 10 chf = 1000 dans Stripe Amount = (long?)(subscription.SubscriptionPrice * 100), Currency = "chf", ReceiptEmail = user.Email, // Verify your integration in this guide by including this parameter Metadata = new Dictionary <string, string> { { "integration_check", "accept_a_payment" }, }, }; options.Metadata.Add("SubscriptionName", subscription.SubscriptionName); options.Metadata.Add("UserName", user.Firstname + " " + user.LastName); options.Metadata.Add("UserId", userId); PaymentIntentService service = new PaymentIntentService(); PaymentIntent paymentIntent = service.Create(options); return(Ok(paymentIntent)); } else { return(BadRequest("No subscription price available")); } }
/// <summary> /// Instantiates a new <see cref="InvoicePaymentAuthorizationRequest"/>. /// </summary> /// <param name="operation">The initial API operation for this invoice request.</param> /// <param name="intent">The initial payment intent for this invoice.</param> /// <param name="currency">The <seealso cref="Currency"/> this payment will be paid in.</param> /// <param name="prices">A list of objects detailing price differences between different payment instruments.</param> /// <param name="description">A textual description of what is being paid.</param> /// <param name="userAgent">The payers UserAgent string.</param> /// <param name="language">The payers prefered <seealso cref="Language"/>.</param> /// <param name="urls">Object containing relevant URLs for this payment.</param> /// <param name="payeeInfo">Object with merchant information.</param> /// <param name="invoiceType">Specifies the invoice type, country, of the invoice.</param> public InvoicePaymentAuthorizationRequest(Operation operation, PaymentIntent intent, Currency currency, IEnumerable <IPrice> prices, string description, string userAgent, Language language, IUrls urls, IPayeeInfo payeeInfo, InvoiceType invoiceType) { Payment = new InvoicePaymentRequestDetails(operation, intent, currency, prices, description, userAgent, language, urls, payeeInfo); Invoice = new InvoicePaymentRequestData(invoiceType); }
/// <summary> /// Instantiates a <see cref="VippsPaymentRequest"/> with the provided parameters. /// </summary> /// <param name="operation">The initial operation of this payment.</param> /// <param name="intent">The intent of this payment.</param> /// <param name="currency">The wanted currency of the payment.</param> /// <param name="prices">List of payment instrument prices.</param> /// <param name="description">Textual description of the payment.</param> /// <param name="payerReference">Merchant reference to the payer.</param> /// <param name="userAgent">The payers UserAgent string.</param> /// <param name="language">The payers prefered language.</param> /// <param name="urls">Object with relevant URLs for the payment.</param> /// <param name="payeeInfo">Object with information about the merchant.</param> public VippsPaymentRequest(Operation operation, PaymentIntent intent, Currency currency, IEnumerable <IPrice> prices, string description, string userAgent, Language language, IUrls urls, IPayeeInfo payeeInfo, string payerReference) { Payment = new VippsPaymentRequestDetails(operation, intent, currency, prices, description, payerReference, userAgent, language, urls, payeeInfo); }
public async Task <ActionResult> Webhook() { Console.WriteLine("webhook run"); const string secret = "whsec_9Ylk3AV0pn6IML69W9g83fiQAZq5Y612"; try { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], secret); PaymentIntent intent = null; switch (stripeEvent.Type) { case "payment_intent.succeeded": intent = (PaymentIntent)stripeEvent.Data.Object; _logger.LogInformation("Succeeded: {ID}", intent.Id); // Fulfil the customer's purchase Console.WriteLine("webhook run success"); await _bus.Publish(new PaymentOrderSuccessMessage { PaymentIntentId = intent.Id }); break; case "payment_intent.payment_failed": intent = (PaymentIntent)stripeEvent.Data.Object; _logger.LogInformation("Failure: {ID}", intent.Id); // Notify the customer that payment failed break; default: // Handle other event types break; } return(new EmptyResult()); } catch (StripeException) { // Invalid Signature return(BadRequest()); } }
// GET: Donation/CardPayment public ActionResult CardPayment(int?id) { if (id == null) { //change to redirect to return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } //Debug Purpose to see if we are getting the id Debug.WriteLine("I'm pulling data of " + id.ToString()); //Get the specific department Donation donation = db.Donations.Find(id); //Could not find the specific department if (donation == null) { return(HttpNotFound()); } StripeConfiguration.ApiKey = "sk_test_T3BF2ap8TTDpmetCKxF038r400HAf7zrj8"; //Create a Payment Intent from Payment API PaymentIntentCreateOptions options = new PaymentIntentCreateOptions { Amount = donation.donationAmount, Currency = "usd", // Verify your integration in this guide by including this parameter Metadata = new Dictionary <string, string> { { "integration_check", "accept_a_payment" }, } }; PaymentIntentService service = new PaymentIntentService(); PaymentIntent paymentIntent = service.Create(options); ViewData["id"] = id; ViewData["clientSecret"] = paymentIntent.ClientSecret; ViewData["clientName"] = db.Donations.Find(id).donationName; //Add the id for the payment in the Stripe API (Unique identifier for the object) db.Donations.Find(id).donationReceiptId = paymentIntent.Id; //Save the changes in the database db.SaveChanges(); return(View()); }
//Stripe Response --> Move from here to result private IActionResult GeneratePaymentResponse(PaymentIntent intent) { // Note that if your API version is before 2019-02-11, 'requires_action' // appears as 'requires_source_action'. if (intent.Status == "requires_action" && intent.NextAction.Type == "use_stripe_sdk") { // Tell the client to handle the action return(Json(new { requires_action = true, payment_intent_client_secret = intent.ClientSecret })); } else if (intent.Status == "succeeded") { var order = _context.InitiatedOrders.Find(intent.Id); if (order == null) { return(StatusCode(500, new { error = "Error" })); } switch (order.Reason) { // case EnumList.PaymentReason.Register when CompleteRegistration(order.UserId, order.CourseId, order.Reason, EnumList.PaymentMethod.Stripe, order.Id, // order.PayAllNow, new UserDevice()).Result: case EnumList.PaymentReason.Register when CompleteRegistration(order.Id).Result: // return Ok(new {result = EnumList.PaymentResult.Success.ToString(), message = "success", order.CourseId, order.InvoiceNumber,reason = order.Reason.ToString()}); return(Ok(new { orderId = order.Id })); case EnumList.PaymentReason.Invoice when CompleteInvoicePayment(order.Id).Result: return(Ok(new { orderId = order.Id })); case EnumList.PaymentReason.Empty: case EnumList.PaymentReason.Donate: case EnumList.PaymentReason.Other: default: // The payment didn’t need any additional actions and completed! // Handle post-payment fulfillment return(StatusCode(500, new { error = "Error" })); } } else { // Invalid status return(StatusCode(500, new { error = "Invalid PaymentIntent status" })); } }
public PrivacyControlViewModel(Wallet wallet, TransactionInfo transactionInfo, TransactionBroadcaster broadcaster) { _wallet = wallet; _pocketSource = new SourceList <PocketViewModel>(); _pocketSource.Connect() .Bind(out _pockets) .Subscribe(); var selected = _pocketSource.Connect() .AutoRefresh() .Filter(x => x.IsSelected); var selectedList = selected.AsObservableList(); selected.Sum(x => x.TotalBtc) .Subscribe(x => { StillNeeded = transactionInfo.Amount.ToDecimal(MoneyUnit.BTC) - x; EnoughSelected = StillNeeded <= 0; }); StillNeeded = transactionInfo.Amount.ToDecimal(MoneyUnit.BTC); NextCommand = ReactiveCommand.Create( () => { var coins = selectedList.Items.SelectMany(x => x.Coins); var intent = new PaymentIntent( transactionInfo.Address, transactionInfo.Amount, subtractFee: false, transactionInfo.Labels); var transactionResult = _wallet.BuildTransaction( _wallet.Kitchen.SaltSoup(), intent, FeeStrategy.CreateFromFeeRate(transactionInfo.FeeRate), true, coins.Select(x => x.OutPoint)); Navigate().To(new TransactionPreviewViewModel(wallet, transactionInfo, broadcaster, transactionResult)); }, this.WhenAnyValue(x => x.EnoughSelected)); }