mirror of
https://github.com/btcpayserver/btcpayserver.git
synced 2025-02-23 22:46:49 +01:00
66 lines
3.1 KiB
C#
66 lines
3.1 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using BTCPayServer.Data;
|
|
using BTCPayServer.Events;
|
|
using BTCPayServer.Logging;
|
|
using BTCPayServer.Payments;
|
|
|
|
namespace BTCPayServer.Services.Invoices
|
|
{
|
|
public static class InvoiceExtensions
|
|
{
|
|
|
|
public static async Task ActivateInvoicePaymentMethod(this InvoiceRepository invoiceRepository,
|
|
EventAggregator eventAggregator, BTCPayNetworkProvider btcPayNetworkProvider, PaymentMethodHandlerDictionary paymentMethodHandlerDictionary,
|
|
StoreData store,InvoiceEntity invoice, PaymentMethodId paymentMethodId)
|
|
{
|
|
var eligibleMethodToActivate = invoice.GetPaymentMethod(paymentMethodId);
|
|
if (!eligibleMethodToActivate.GetPaymentMethodDetails().Activated)
|
|
{
|
|
var payHandler = paymentMethodHandlerDictionary[paymentMethodId];
|
|
var supportPayMethod = invoice.GetSupportedPaymentMethod()
|
|
.Single(method => method.PaymentId == paymentMethodId);
|
|
var paymentMethod = invoice.GetPaymentMethod(paymentMethodId);
|
|
var network = btcPayNetworkProvider.GetNetwork(paymentMethodId.CryptoCode);
|
|
var prepare = payHandler.PreparePayment(supportPayMethod, store, network);
|
|
InvoiceLogs logs = new InvoiceLogs();
|
|
try
|
|
{
|
|
logs.Write($"{paymentMethodId}: Activating", InvoiceEventData.EventSeverity.Info);
|
|
var newDetails = await
|
|
payHandler.CreatePaymentMethodDetails(logs, supportPayMethod, paymentMethod, store, network,
|
|
prepare);
|
|
eligibleMethodToActivate.SetPaymentMethodDetails(newDetails);
|
|
await invoiceRepository.UpdateInvoicePaymentMethod(invoice.Id, eligibleMethodToActivate);
|
|
eventAggregator.Publish(new InvoicePaymentMethodActivated(paymentMethodId, invoice));
|
|
}
|
|
catch (PaymentMethodUnavailableException ex)
|
|
{
|
|
logs.Write($"{paymentMethodId}: Payment method unavailable ({ex.Message})", InvoiceEventData.EventSeverity.Error);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logs.Write($"{paymentMethodId}: Unexpected exception ({ex})", InvoiceEventData.EventSeverity.Error);
|
|
}
|
|
|
|
await invoiceRepository.AddInvoiceLogs(invoice.Id, logs);
|
|
eventAggregator.Publish(new InvoiceNeedUpdateEvent(invoice.Id));
|
|
}
|
|
}
|
|
|
|
public static PaymentMethodId GetDefaultPaymentId(
|
|
this InvoiceRepository invoiceRepository,
|
|
PaymentMethodId[] paymentMethodIds,
|
|
InvoiceEntity invoice
|
|
)
|
|
{
|
|
PaymentMethodId.TryParse(invoice.DefaultPaymentMethod, out var defaultPaymentId);
|
|
var chosen = paymentMethodIds.FirstOrDefault(f => f == defaultPaymentId) ??
|
|
paymentMethodIds.FirstOrDefault(f => f.CryptoCode == defaultPaymentId?.CryptoCode) ??
|
|
paymentMethodIds.FirstOrDefault();
|
|
return chosen;
|
|
}
|
|
|
|
}
|
|
}
|