private void AddPaymentMethods(StoreData store, StoreBlob storeBlob, StoreViewModel vm) { var excludeFilters = storeBlob.GetExcludedPaymentMethods(); var derivationByCryptoCode = store .GetSupportedPaymentMethods(_NetworkProvider) .OfType <DerivationSchemeSettings>() .ToDictionary(c => c.Network.CryptoCode.ToUpperInvariant()); var lightningByCryptoCode = store .GetSupportedPaymentMethods(_NetworkProvider) .OfType <LightningSupportedPaymentMethod>() .ToDictionary(c => c.CryptoCode.ToUpperInvariant()); foreach (var paymentMethodId in _paymentMethodHandlerDictionary.Distinct().SelectMany(handler => handler.GetSupportedPaymentMethods())) { switch (paymentMethodId.PaymentType) { case BitcoinPaymentType _: var strategy = derivationByCryptoCode.TryGet(paymentMethodId.CryptoCode); var network = _NetworkProvider.GetNetwork <BTCPayNetwork>(paymentMethodId.CryptoCode); var value = strategy?.ToPrettyString() ?? string.Empty; vm.DerivationSchemes.Add(new StoreViewModel.DerivationScheme() { Crypto = paymentMethodId.CryptoCode, WalletSupported = network.WalletSupported, Value = value, WalletId = new WalletId(store.Id, paymentMethodId.CryptoCode), Enabled = !excludeFilters.Match(paymentMethodId) && strategy != null, #if ALTCOINS Collapsed = network is ElementsBTCPayNetwork elementsBTCPayNetwork && elementsBTCPayNetwork.NetworkCryptoCode != elementsBTCPayNetwork.CryptoCode && string.IsNullOrEmpty(value) #endif }); break;
public static bool IsLightningEnabled(this StoreData storeData, BTCPayNetworkProvider networks) { var paymentMethods = storeData.GetSupportedPaymentMethods(networks); var lightningByCryptoCode = paymentMethods .OfType <LightningSupportedPaymentMethod>() .Where(method => method.PaymentId.PaymentType == LightningPaymentType.Instance) .ToDictionary(c => c.CryptoCode.ToUpperInvariant()); var excludeFilters = storeData.GetStoreBlob().GetExcludedPaymentMethods(); var isLightningEnabled = false; foreach (var paymentMethod in paymentMethods) { var paymentMethodId = paymentMethod.PaymentId; switch (paymentMethodId.PaymentType) { // LNURLPayPaymentType is a subclass of LightningPaymentType, skip it case LNURLPayPaymentType lnurlPayPaymentType: break; case LightningPaymentType _: var lightning = lightningByCryptoCode.TryGet(paymentMethodId.CryptoCode); isLightningEnabled = !excludeFilters.Match(paymentMethodId) && lightning != null; break; } } return(isLightningEnabled); }
public static PaymentMethodId[] GetEnabledPaymentIds(this StoreData storeData, BTCPayNetworkProvider networks) { var excludeFilter = storeData.GetStoreBlob().GetExcludedPaymentMethods(); var paymentMethodIds = storeData.GetSupportedPaymentMethods(networks).Select(p => p.PaymentId) .Where(a => !excludeFilter.Match(a)) .OrderByDescending(a => a.CryptoCode == "BTC") .ThenBy(a => a.CryptoCode) .ThenBy(a => a.PaymentType == PaymentTypes.LightningLike ? 1 : 0) .ToArray(); return(paymentMethodIds); }
public static IEnumerable <OnChainPaymentMethodData> GetOnChainPaymentMethods(StoreData store, BTCPayNetworkProvider networkProvider, bool?enabled) { var blob = store.GetStoreBlob(); var excludedPaymentMethods = blob.GetExcludedPaymentMethods(); return(store.GetSupportedPaymentMethods(networkProvider) .Where((method) => method.PaymentId.PaymentType == PaymentTypes.BTCLike) .OfType <DerivationSchemeSettings>() .Select(strategy => new OnChainPaymentMethodData(strategy.PaymentId.CryptoCode, strategy.AccountDerivation.ToString(), !excludedPaymentMethods.Match(strategy.PaymentId), strategy.Label, strategy.GetSigningAccountKeySettings().GetRootedKeyPath())) .Where((result) => enabled is null || enabled == result.Enabled) .ToList()); }
private LightningNetworkPaymentMethodData GetExistingLightningLikePaymentMethod(string cryptoCode, StoreData store = null) { store ??= Store; var storeBlob = store.GetStoreBlob(); var id = new PaymentMethodId(cryptoCode, PaymentTypes.LightningLike); var paymentMethod = store .GetSupportedPaymentMethods(_btcPayNetworkProvider) .OfType <LightningSupportedPaymentMethod>() .FirstOrDefault(method => method.PaymentId == id); var excluded = storeBlob.IsExcluded(id); return(paymentMethod == null ? null : new LightningNetworkPaymentMethodData(paymentMethod.PaymentId.CryptoCode, paymentMethod.GetLightningUrl().ToString(), !excluded)); }
public static bool IsLNUrlEnabled(this StoreData storeData, BTCPayNetworkProvider networks) { var paymentMethods = storeData.GetSupportedPaymentMethods(networks); var excludeFilters = storeData.GetStoreBlob().GetExcludedPaymentMethods(); var isLNUrlEnabled = false; foreach (var paymentMethod in paymentMethods) { var paymentMethodId = paymentMethod.PaymentId; if (paymentMethodId.PaymentType is LNURLPayPaymentType) { isLNUrlEnabled = !excludeFilters.Match(paymentMethodId); } } return(isLNUrlEnabled); }
public static LightningNetworkPaymentMethodData?GetExistingLightningLikePaymentMethod(BTCPayNetworkProvider btcPayNetworkProvider, string cryptoCode, StoreData store) { var storeBlob = store.GetStoreBlob(); var id = new PaymentMethodId(cryptoCode, PaymentTypes.LightningLike); var paymentMethod = store .GetSupportedPaymentMethods(btcPayNetworkProvider) .OfType <LightningSupportedPaymentMethod>() .FirstOrDefault(method => method.PaymentId == id); var excluded = storeBlob.IsExcluded(id); return(paymentMethod is null ? null : new LightningNetworkPaymentMethodData(paymentMethod.PaymentId.CryptoCode, paymentMethod.GetDisplayableConnectionString(), !excluded, paymentMethod.PaymentId.ToStringNormalized(), paymentMethod.DisableBOLT11PaymentOption)); }
private OnChainPaymentMethodData GetExistingBtcLikePaymentMethod(string cryptoCode, StoreData store = null) { store ??= Store; var storeBlob = store.GetStoreBlob(); var id = new PaymentMethodId(cryptoCode, PaymentTypes.BTCLike); var paymentMethod = store .GetSupportedPaymentMethods(_btcPayNetworkProvider) .OfType <DerivationSchemeSettings>() .FirstOrDefault(method => method.PaymentId == id); var excluded = storeBlob.IsExcluded(id); return(paymentMethod == null ? null : new OnChainPaymentMethodData(paymentMethod.PaymentId.CryptoCode, paymentMethod.AccountDerivation.ToString(), !excluded, paymentMethod.Label, paymentMethod.GetSigningAccountKeySettings().GetRootedKeyPath())); }
public static IEnumerable <LNURLPayPaymentMethodData> GetLNURLPayPaymentMethods(StoreData store, BTCPayNetworkProvider networkProvider, bool?enabled) { var blob = store.GetStoreBlob(); var excludedPaymentMethods = blob.GetExcludedPaymentMethods(); return(store.GetSupportedPaymentMethods(networkProvider) .Where((method) => method.PaymentId.PaymentType == PaymentTypes.LNURLPay) .OfType <LNURLPaySupportedPaymentMethod>() .Select(paymentMethod => new LNURLPayPaymentMethodData( paymentMethod.PaymentId.CryptoCode, !excludedPaymentMethods.Match(paymentMethod.PaymentId), paymentMethod.UseBech32Scheme, paymentMethod.EnableForStandardInvoices ) ) .Where((result) => enabled is null || enabled == result.Enabled) .ToList()); }
public static IEnumerable<LightningNetworkPaymentMethodData> GetLightningPaymentMethods(StoreData store, BTCPayNetworkProvider networkProvider, bool? enabled) { var blob = store.GetStoreBlob(); var excludedPaymentMethods = blob.GetExcludedPaymentMethods(); return store.GetSupportedPaymentMethods(networkProvider) .Where((method) => method.PaymentId.PaymentType == PaymentTypes.LightningLike) .OfType<LightningSupportedPaymentMethod>() .Select(paymentMethod => new LightningNetworkPaymentMethodData( paymentMethod.PaymentId.CryptoCode, paymentMethod.GetExternalLightningUrl()?.ToString() ?? paymentMethod.GetDisplayableConnectionString(), !excludedPaymentMethods.Match(paymentMethod.PaymentId) ) ) .Where((result) => enabled is null || enabled == result.Enabled) .ToList(); }
internal async Task <InvoiceEntity> CreateInvoiceCoreRaw(InvoiceEntity entity, StoreData store, IPaymentFilter?invoicePaymentMethodFilter, string[]?additionalSearchTerms = null, CancellationToken cancellationToken = default) { InvoiceLogs logs = new InvoiceLogs(); logs.Write("Creation of invoice starting", InvoiceEventData.EventSeverity.Info); var storeBlob = store.GetStoreBlob(); if (string.IsNullOrEmpty(entity.Currency)) { entity.Currency = storeBlob.DefaultCurrency; } entity.Currency = entity.Currency.Trim().ToUpperInvariant(); entity.Price = Math.Max(0.0m, entity.Price); var currencyInfo = _CurrencyNameTable.GetNumberFormatInfo(entity.Currency, false); if (currencyInfo != null) { entity.Price = entity.Price.RoundToSignificant(currencyInfo.CurrencyDecimalDigits); } if (entity.Metadata.TaxIncluded is decimal taxIncluded) { if (currencyInfo != null) { taxIncluded = taxIncluded.RoundToSignificant(currencyInfo.CurrencyDecimalDigits); } taxIncluded = Math.Max(0.0m, taxIncluded); taxIncluded = Math.Min(taxIncluded, entity.Price); entity.Metadata.TaxIncluded = taxIncluded; } var getAppsTaggingStore = _InvoiceRepository.GetAppsTaggingStore(store.Id); if (entity.Metadata.BuyerEmail != null) { if (!EmailValidator.IsEmail(entity.Metadata.BuyerEmail)) { throw new BitpayHttpException(400, "Invalid email"); } entity.RefundMail = entity.Metadata.BuyerEmail; } entity.Status = InvoiceStatusLegacy.New; HashSet <CurrencyPair> currencyPairsToFetch = new HashSet <CurrencyPair>(); var rules = storeBlob.GetRateRules(_NetworkProvider); var excludeFilter = storeBlob.GetExcludedPaymentMethods(); // Here we can compose filters from other origin with PaymentFilter.Any() if (invoicePaymentMethodFilter != null) { excludeFilter = PaymentFilter.Or(excludeFilter, invoicePaymentMethodFilter); } foreach (var network in store.GetSupportedPaymentMethods(_NetworkProvider) .Where(s => !excludeFilter.Match(s.PaymentId)) .Select(c => _NetworkProvider.GetNetwork <BTCPayNetworkBase>(c.PaymentId.CryptoCode)) .Where(c => c != null)) { currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, entity.Currency)); foreach (var paymentMethodCriteria in storeBlob.PaymentMethodCriteria) { if (paymentMethodCriteria.Value != null) { currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, paymentMethodCriteria.Value.Currency)); } } } var rateRules = storeBlob.GetRateRules(_NetworkProvider); var fetchingByCurrencyPair = _RateProvider.FetchRates(currencyPairsToFetch, rateRules, cancellationToken); var fetchingAll = WhenAllFetched(logs, fetchingByCurrencyPair); List <ISupportedPaymentMethod> supported = new List <ISupportedPaymentMethod>(); var paymentMethods = new PaymentMethodDictionary(); bool noNeedForMethods = entity.Type != InvoiceType.TopUp && entity.Price == 0m; if (!noNeedForMethods) { // This loop ends with .ToList so we are querying all payment methods at once // instead of sequentially to improve response time foreach (var o in store.GetSupportedPaymentMethods(_NetworkProvider) .Where(s => !excludeFilter.Match(s.PaymentId) && _paymentMethodHandlerDictionary.Support(s.PaymentId)) .Select(c => (Handler: _paymentMethodHandlerDictionary[c.PaymentId], SupportedPaymentMethod: c, Network: _NetworkProvider.GetNetwork <BTCPayNetworkBase>(c.PaymentId.CryptoCode))) .Where(c => c.Network != null) .Select(o => (SupportedPaymentMethod: o.SupportedPaymentMethod, PaymentMethod: CreatePaymentMethodAsync(fetchingByCurrencyPair, o.Handler, o.SupportedPaymentMethod, o.Network, entity, store, logs))) .ToList()) { var paymentMethod = await o.PaymentMethod; if (paymentMethod == null) { continue; } supported.Add(o.SupportedPaymentMethod); paymentMethods.Add(paymentMethod); } if (supported.Count == 0) { StringBuilder errors = new StringBuilder(); if (!store.GetSupportedPaymentMethods(_NetworkProvider).Any()) { errors.AppendLine( "Warning: No wallet has been linked to your BTCPay Store. See the following link for more information on how to connect your store and wallet. (https://docs.btcpayserver.org/WalletSetup/)"); } foreach (var error in logs.ToList()) { errors.AppendLine(error.ToString()); } throw new BitpayHttpException(400, errors.ToString()); } } entity.SetSupportedPaymentMethods(supported); entity.SetPaymentMethods(paymentMethods); foreach (var app in await getAppsTaggingStore) { entity.InternalTags.Add(AppService.GetAppInternalTag(app.Id)); } using (logs.Measure("Saving invoice")) { entity = await _InvoiceRepository.CreateInvoiceAsync(store.Id, entity, additionalSearchTerms); } _ = Task.Run(async() => { try { await fetchingAll; } catch (AggregateException ex) { ex.Handle(e => { logs.Write($"Error while fetching rates {ex}", InvoiceEventData.EventSeverity.Error); return(true); }); } await _InvoiceRepository.AddInvoiceLogs(entity.Id, logs); }); _EventAggregator.Publish(new Events.InvoiceEvent(entity, InvoiceEvent.Created)); return(entity); }
internal async Task <DataWrapper <InvoiceResponse> > CreateInvoiceCore(CreateInvoiceRequest invoice, StoreData store, string serverUrl, List <string> additionalTags = null, CancellationToken cancellationToken = default) { invoice.Currency = invoice.Currency?.ToUpperInvariant() ?? "USD"; InvoiceLogs logs = new InvoiceLogs(); logs.Write("Creation of invoice starting"); var entity = _InvoiceRepository.CreateNewInvoice(); var getAppsTaggingStore = _InvoiceRepository.GetAppsTaggingStore(store.Id); var storeBlob = store.GetStoreBlob(); EmailAddressAttribute emailValidator = new EmailAddressAttribute(); entity.ExpirationTime = invoice.ExpirationTime is DateTimeOffset v ? v : entity.InvoiceTime.AddMinutes(storeBlob.InvoiceExpiration); if (entity.ExpirationTime - TimeSpan.FromSeconds(30.0) < entity.InvoiceTime) { throw new BitpayHttpException(400, "The expirationTime is set too soon"); } entity.MonitoringExpiration = entity.ExpirationTime + TimeSpan.FromMinutes(storeBlob.MonitoringExpiration); entity.OrderId = invoice.OrderId; entity.ServerUrl = serverUrl; entity.FullNotifications = invoice.FullNotifications || invoice.ExtendedNotifications; entity.ExtendedNotifications = invoice.ExtendedNotifications; entity.NotificationURLTemplate = invoice.NotificationURL; entity.NotificationEmail = invoice.NotificationEmail; entity.BuyerInformation = Map <CreateInvoiceRequest, BuyerInformation>(invoice); entity.PaymentTolerance = storeBlob.PaymentTolerance; if (additionalTags != null) { entity.InternalTags.AddRange(additionalTags); } //Another way of passing buyer info to support FillBuyerInfo(invoice.Buyer, entity.BuyerInformation); if (entity?.BuyerInformation?.BuyerEmail != null) { if (!EmailValidator.IsEmail(entity.BuyerInformation.BuyerEmail)) { throw new BitpayHttpException(400, "Invalid email"); } entity.RefundMail = entity.BuyerInformation.BuyerEmail; } var taxIncluded = invoice.TaxIncluded.HasValue ? invoice.TaxIncluded.Value : 0m; var currencyInfo = _CurrencyNameTable.GetNumberFormatInfo(invoice.Currency, false); if (currencyInfo != null) { int divisibility = currencyInfo.CurrencyDecimalDigits; invoice.Price = invoice.Price.RoundToSignificant(ref divisibility); divisibility = currencyInfo.CurrencyDecimalDigits; invoice.TaxIncluded = taxIncluded.RoundToSignificant(ref divisibility); } invoice.Price = Math.Max(0.0m, invoice.Price); invoice.TaxIncluded = Math.Max(0.0m, taxIncluded); invoice.TaxIncluded = Math.Min(taxIncluded, invoice.Price); entity.ProductInformation = Map <CreateInvoiceRequest, ProductInformation>(invoice); entity.RedirectURLTemplate = invoice.RedirectURL ?? store.StoreWebsite; entity.RedirectAutomatically = invoice.RedirectAutomatically.GetValueOrDefault(storeBlob.RedirectAutomatically); entity.Status = InvoiceStatus.New; entity.SpeedPolicy = ParseSpeedPolicy(invoice.TransactionSpeed, store.SpeedPolicy); HashSet <CurrencyPair> currencyPairsToFetch = new HashSet <CurrencyPair>(); var rules = storeBlob.GetRateRules(_NetworkProvider); var excludeFilter = storeBlob.GetExcludedPaymentMethods(); // Here we can compose filters from other origin with PaymentFilter.Any() if (invoice.PaymentCurrencies?.Any() is true) { foreach (string paymentCurrency in invoice.PaymentCurrencies) { invoice.SupportedTransactionCurrencies.TryAdd(paymentCurrency, new InvoiceSupportedTransactionCurrency() { Enabled = true }); } } if (invoice.SupportedTransactionCurrencies != null && invoice.SupportedTransactionCurrencies.Count != 0) { var supportedTransactionCurrencies = invoice.SupportedTransactionCurrencies .Where(c => c.Value.Enabled) .Select(c => PaymentMethodId.TryParse(c.Key, out var p) ? p : null) .ToHashSet(); excludeFilter = PaymentFilter.Or(excludeFilter, PaymentFilter.Where(p => !supportedTransactionCurrencies.Contains(p))); } foreach (var network in store.GetSupportedPaymentMethods(_NetworkProvider) .Where(s => !excludeFilter.Match(s.PaymentId)) .Select(c => _NetworkProvider.GetNetwork <BTCPayNetworkBase>(c.PaymentId.CryptoCode)) .Where(c => c != null)) { currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, invoice.Currency)); //TODO: abstract if (storeBlob.LightningMaxValue != null) { currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, storeBlob.LightningMaxValue.Currency)); } if (storeBlob.OnChainMinValue != null) { currencyPairsToFetch.Add(new CurrencyPair(network.CryptoCode, storeBlob.OnChainMinValue.Currency)); } } var rateRules = storeBlob.GetRateRules(_NetworkProvider); var fetchingByCurrencyPair = _RateProvider.FetchRates(currencyPairsToFetch, rateRules, cancellationToken); var fetchingAll = WhenAllFetched(logs, fetchingByCurrencyPair); var supportedPaymentMethods = store.GetSupportedPaymentMethods(_NetworkProvider) .Where(s => !excludeFilter.Match(s.PaymentId) && _paymentMethodHandlerDictionary.Support(s.PaymentId)) .Select(c => (Handler: _paymentMethodHandlerDictionary[c.PaymentId], SupportedPaymentMethod: c, Network: _NetworkProvider.GetNetwork <BTCPayNetworkBase>(c.PaymentId.CryptoCode))) .Where(c => c.Network != null) .Select(o => (SupportedPaymentMethod: o.SupportedPaymentMethod, PaymentMethod: CreatePaymentMethodAsync(fetchingByCurrencyPair, o.Handler, o.SupportedPaymentMethod, o.Network, entity, store, logs))) .ToList(); List <ISupportedPaymentMethod> supported = new List <ISupportedPaymentMethod>(); var paymentMethods = new PaymentMethodDictionary(); foreach (var o in supportedPaymentMethods) { var paymentMethod = await o.PaymentMethod; if (paymentMethod == null) { continue; } supported.Add(o.SupportedPaymentMethod); paymentMethods.Add(paymentMethod); } if (supported.Count == 0) { StringBuilder errors = new StringBuilder(); if (!store.GetSupportedPaymentMethods(_NetworkProvider).Any()) { errors.AppendLine("Warning: No wallet has been linked to your BTCPay Store. See the following link for more information on how to connect your store and wallet. (https://docs.btcpayserver.org/getting-started/connectwallet)"); } foreach (var error in logs.ToList()) { errors.AppendLine(error.ToString()); } throw new BitpayHttpException(400, errors.ToString()); } entity.SetSupportedPaymentMethods(supported); entity.SetPaymentMethods(paymentMethods); entity.PosData = invoice.PosData; foreach (var app in await getAppsTaggingStore) { entity.InternalTags.Add(AppService.GetAppInternalTag(app.Id)); } using (logs.Measure("Saving invoice")) { entity = await _InvoiceRepository.CreateInvoiceAsync(store.Id, entity); } _ = Task.Run(async() => { try { await fetchingAll; } catch (AggregateException ex) { ex.Handle(e => { logs.Write($"Error while fetching rates {ex}"); return(true); }); } await _InvoiceRepository.AddInvoiceLogs(entity.Id, logs); }); _EventAggregator.Publish(new Events.InvoiceEvent(entity, 1001, InvoiceEvent.Created)); var resp = entity.EntityToDTO(); return(new DataWrapper <InvoiceResponse>(resp) { Facade = "pos/invoice" }); }