2020-06-29 04:44:35 +02:00
|
|
|
using System;
|
2017-09-25 18:31:43 +02:00
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.Linq;
|
|
|
|
using System.Net.Http;
|
|
|
|
using System.Text;
|
|
|
|
using System.Threading;
|
2020-06-28 10:55:27 +02:00
|
|
|
using System.Threading.Tasks;
|
2017-12-17 06:17:42 +01:00
|
|
|
using BTCPayServer.Events;
|
2018-02-19 15:13:23 +01:00
|
|
|
using BTCPayServer.Payments;
|
2019-01-16 11:14:45 +01:00
|
|
|
using BTCPayServer.Services;
|
2020-06-28 10:55:27 +02:00
|
|
|
using BTCPayServer.Services.Invoices;
|
|
|
|
using BTCPayServer.Services.Mails;
|
2020-08-28 18:23:46 +02:00
|
|
|
using BTCPayServer.Services.Stores;
|
2020-06-28 10:55:27 +02:00
|
|
|
using Microsoft.Extensions.Hosting;
|
2022-06-22 05:05:32 +02:00
|
|
|
using MimeKit;
|
2020-06-28 10:55:27 +02:00
|
|
|
using NBitpayClient;
|
|
|
|
using NBXplorer;
|
|
|
|
using Newtonsoft.Json;
|
|
|
|
using Newtonsoft.Json.Linq;
|
2017-09-25 18:31:43 +02:00
|
|
|
|
2018-01-07 18:36:41 +01:00
|
|
|
namespace BTCPayServer.HostedServices
|
2017-09-25 18:31:43 +02:00
|
|
|
{
|
2022-01-11 05:14:10 +01:00
|
|
|
public class BitpayIPNSender : IHostedService
|
2017-10-27 10:53:04 +02:00
|
|
|
{
|
2020-06-29 05:07:48 +02:00
|
|
|
readonly HttpClient _Client;
|
2017-09-25 18:31:43 +02:00
|
|
|
|
2017-10-27 10:53:04 +02:00
|
|
|
public class ScheduledJob
|
|
|
|
{
|
|
|
|
public int TryCount
|
|
|
|
{
|
|
|
|
get; set;
|
|
|
|
}
|
2017-09-25 18:31:43 +02:00
|
|
|
|
2019-01-30 05:40:08 +01:00
|
|
|
public InvoicePaymentNotificationEventWrapper Notification
|
2017-10-27 10:53:04 +02:00
|
|
|
{
|
|
|
|
get; set;
|
|
|
|
}
|
|
|
|
}
|
2017-09-25 18:31:43 +02:00
|
|
|
|
2022-01-11 06:48:45 +01:00
|
|
|
MultiProcessingQueue _Queue = new MultiProcessingQueue();
|
2020-06-29 05:07:48 +02:00
|
|
|
readonly IBackgroundJobClient _JobClient;
|
|
|
|
readonly EventAggregator _EventAggregator;
|
|
|
|
readonly InvoiceRepository _InvoiceRepository;
|
2019-01-06 15:53:37 +01:00
|
|
|
private readonly EmailSenderFactory _EmailSenderFactory;
|
2020-08-28 18:23:46 +02:00
|
|
|
private readonly StoreRepository _StoreRepository;
|
2023-04-19 14:13:31 +02:00
|
|
|
public const string NamedClient = "bitpay-ipn";
|
2022-01-11 05:14:10 +01:00
|
|
|
public BitpayIPNSender(
|
2019-04-05 07:31:09 +02:00
|
|
|
IHttpClientFactory httpClientFactory,
|
2017-10-27 10:53:04 +02:00
|
|
|
IBackgroundJobClient jobClient,
|
2017-12-17 06:17:42 +01:00
|
|
|
EventAggregator eventAggregator,
|
|
|
|
InvoiceRepository invoiceRepository,
|
2020-08-28 18:23:46 +02:00
|
|
|
StoreRepository storeRepository,
|
2019-01-06 15:53:37 +01:00
|
|
|
EmailSenderFactory emailSenderFactory)
|
2017-10-27 10:53:04 +02:00
|
|
|
{
|
2023-04-19 14:13:31 +02:00
|
|
|
_Client = httpClientFactory.CreateClient(NamedClient);
|
2017-10-27 10:53:04 +02:00
|
|
|
_JobClient = jobClient;
|
2017-12-17 06:17:42 +01:00
|
|
|
_EventAggregator = eventAggregator;
|
|
|
|
_InvoiceRepository = invoiceRepository;
|
2019-01-06 15:53:37 +01:00
|
|
|
_EmailSenderFactory = emailSenderFactory;
|
2020-08-28 18:23:46 +02:00
|
|
|
_StoreRepository = storeRepository;
|
2017-10-27 10:53:04 +02:00
|
|
|
}
|
2017-09-25 18:31:43 +02:00
|
|
|
|
2022-01-11 16:26:12 +01:00
|
|
|
async Task Notify(InvoiceEntity invoice, InvoiceEvent invoiceEvent, bool extendedNotification, bool sendMail)
|
2017-10-27 10:53:04 +02:00
|
|
|
{
|
2019-05-24 15:22:38 +02:00
|
|
|
var dto = invoice.EntityToDTO();
|
2019-01-30 05:40:08 +01:00
|
|
|
var notification = new InvoicePaymentNotificationEventWrapper()
|
|
|
|
{
|
|
|
|
Data = new InvoicePaymentNotification()
|
|
|
|
{
|
|
|
|
Id = dto.Id,
|
|
|
|
Currency = dto.Currency,
|
|
|
|
CurrentTime = dto.CurrentTime,
|
|
|
|
ExceptionStatus = dto.ExceptionStatus,
|
|
|
|
ExpirationTime = dto.ExpirationTime,
|
|
|
|
InvoiceTime = dto.InvoiceTime,
|
|
|
|
PosData = dto.PosData,
|
|
|
|
Price = dto.Price,
|
|
|
|
Status = dto.Status,
|
|
|
|
BuyerFields = invoice.RefundMail == null ? null : new Newtonsoft.Json.Linq.JObject() { new JProperty("buyerEmail", invoice.RefundMail) },
|
|
|
|
PaymentSubtotals = dto.PaymentSubtotals,
|
|
|
|
PaymentTotals = dto.PaymentTotals,
|
|
|
|
AmountPaid = dto.AmountPaid,
|
|
|
|
ExchangeRates = dto.ExchangeRates,
|
2020-06-03 12:04:05 +02:00
|
|
|
OrderId = dto.OrderId
|
2019-01-30 05:40:08 +01:00
|
|
|
},
|
|
|
|
Event = new InvoicePaymentNotificationEvent()
|
|
|
|
{
|
2020-11-06 14:23:10 +01:00
|
|
|
Code = (int)invoiceEvent.EventCode,
|
2019-01-30 05:40:08 +01:00
|
|
|
Name = invoiceEvent.Name
|
|
|
|
},
|
|
|
|
ExtendedNotification = extendedNotification,
|
2019-09-04 11:20:36 +02:00
|
|
|
NotificationURL = invoice.NotificationURL?.AbsoluteUri
|
2019-01-30 05:40:08 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
// For lightning network payments, paid, confirmed and completed come all at once.
|
|
|
|
// So despite the event is "paid" or "confirmed" the Status of the invoice is technically complete
|
|
|
|
// This confuse loggers who think their endpoint get duplicated events
|
|
|
|
// So here, we just override the status expressed by the notification
|
|
|
|
if (invoiceEvent.Name == InvoiceEvent.Confirmed)
|
|
|
|
{
|
2020-11-23 07:57:05 +01:00
|
|
|
notification.Data.Status = InvoiceState.ToString(InvoiceStatusLegacy.Confirmed);
|
2019-01-30 05:40:08 +01:00
|
|
|
}
|
|
|
|
if (invoiceEvent.Name == InvoiceEvent.PaidInFull)
|
|
|
|
{
|
2020-11-23 07:57:05 +01:00
|
|
|
notification.Data.Status = InvoiceState.ToString(InvoiceStatusLegacy.Paid);
|
2019-01-30 05:40:08 +01:00
|
|
|
}
|
|
|
|
//////////////////
|
|
|
|
|
|
|
|
// We keep backward compatibility with bitpay by passing BTC info to the notification
|
|
|
|
// we don't pass other info, as it is a bad idea to use IPN data for logic processing (can be faked)
|
2021-04-07 06:08:42 +02:00
|
|
|
var btcCryptoInfo = dto.CryptoInfo.FirstOrDefault(c => c.GetpaymentMethodId() == new PaymentMethodId("BTC", Payments.PaymentTypes.BTCLike) && !string.IsNullOrEmpty(c.Address));
|
2019-01-30 05:40:08 +01:00
|
|
|
if (btcCryptoInfo != null)
|
|
|
|
{
|
|
|
|
#pragma warning disable CS0618
|
|
|
|
notification.Data.Rate = dto.Rate;
|
|
|
|
notification.Data.Url = dto.Url;
|
|
|
|
notification.Data.BTCDue = dto.BTCDue;
|
|
|
|
notification.Data.BTCPaid = dto.BTCPaid;
|
|
|
|
notification.Data.BTCPrice = dto.BTCPrice;
|
|
|
|
#pragma warning restore CS0618
|
|
|
|
}
|
|
|
|
|
2022-06-22 05:05:32 +02:00
|
|
|
if (sendMail &&
|
|
|
|
invoice.NotificationEmail is String e &&
|
2022-06-23 06:41:52 +02:00
|
|
|
MailboxAddressValidator.TryParse(e, out MailboxAddress notificationEmail))
|
2018-10-12 03:09:13 +02:00
|
|
|
{
|
2020-08-28 18:23:46 +02:00
|
|
|
var json = NBitcoin.JsonConverters.Serializer.ToString(notification);
|
|
|
|
var store = await _StoreRepository.FindStore(invoice.StoreId);
|
|
|
|
var storeName = store.StoreName ?? "BTCPay Server";
|
|
|
|
var emailBody = $"Store: {storeName}<br>" +
|
|
|
|
$"Invoice ID: {notification.Data.Id}<br>" +
|
|
|
|
$"Status: {notification.Data.Status}<br>" +
|
|
|
|
$"Amount: {notification.Data.Price} {notification.Data.Currency}<br>" +
|
|
|
|
$"<br><details><summary>Details</summary><pre>{json}</pre></details>";
|
2019-01-06 15:53:37 +01:00
|
|
|
|
2021-07-27 14:08:54 +02:00
|
|
|
(await _EmailSenderFactory.GetEmailSender(invoice.StoreId)).SendEmail(
|
2022-06-22 05:05:32 +02:00
|
|
|
notificationEmail,
|
2020-08-28 18:23:46 +02:00
|
|
|
$"{storeName} Invoice Notification - ${invoice.StoreId}",
|
2019-01-06 15:53:37 +01:00
|
|
|
emailBody);
|
2018-10-12 03:09:13 +02:00
|
|
|
}
|
2020-02-24 13:21:03 +01:00
|
|
|
|
2019-09-04 11:01:26 +02:00
|
|
|
if (invoice.NotificationURL != null)
|
|
|
|
{
|
2022-01-11 06:48:45 +01:00
|
|
|
_Queue.Enqueue(invoice.Id, (cancellationToken) => NotifyHttp(new ScheduledJob() { TryCount = 0, Notification = notification }, cancellationToken));
|
2019-09-04 11:01:26 +02:00
|
|
|
}
|
2017-10-27 10:53:04 +02:00
|
|
|
}
|
2017-09-25 18:31:43 +02:00
|
|
|
|
2022-01-11 06:48:45 +01:00
|
|
|
public async Task NotifyHttp(ScheduledJob job, CancellationToken cancellationToken)
|
2017-10-27 10:53:04 +02:00
|
|
|
{
|
|
|
|
bool reschedule = false;
|
2022-01-11 16:26:12 +01:00
|
|
|
var aggregatorEvent = new InvoiceIPNEvent(job.Notification.Data.Id, job.Notification.Event.Code, job.Notification.Event.Name, job.Notification.ExtendedNotification);
|
2017-10-27 10:53:04 +02:00
|
|
|
try
|
|
|
|
{
|
2022-01-11 16:10:55 +01:00
|
|
|
using HttpResponseMessage response = await SendNotification(job.Notification, cancellationToken);
|
2018-03-07 20:22:02 +01:00
|
|
|
reschedule = !response.IsSuccessStatusCode;
|
2019-01-30 05:40:08 +01:00
|
|
|
aggregatorEvent.Error = reschedule ? $"Unexpected return code: {(int)response.StatusCode}" : null;
|
|
|
|
_EventAggregator.Publish<InvoiceIPNEvent>(aggregatorEvent);
|
2017-10-27 10:53:04 +02:00
|
|
|
}
|
2019-04-05 07:58:25 +02:00
|
|
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
|
|
|
{
|
2022-01-11 06:48:45 +01:00
|
|
|
_JobClient.Schedule((cancellation) => NotifyHttp(job, cancellation), TimeSpan.FromMinutes(10.0));
|
2019-04-05 07:58:25 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
catch (OperationCanceledException)
|
2017-10-27 10:53:04 +02:00
|
|
|
{
|
2019-01-30 05:40:08 +01:00
|
|
|
aggregatorEvent.Error = "Timeout";
|
|
|
|
_EventAggregator.Publish<InvoiceIPNEvent>(aggregatorEvent);
|
2018-01-14 14:06:06 +01:00
|
|
|
reschedule = true;
|
|
|
|
}
|
2019-01-16 11:30:03 +01:00
|
|
|
catch (Exception ex)
|
2018-01-14 14:06:06 +01:00
|
|
|
{
|
2017-10-27 10:53:04 +02:00
|
|
|
reschedule = true;
|
2018-01-18 12:56:55 +01:00
|
|
|
|
|
|
|
List<string> messages = new List<string>();
|
2018-02-18 08:09:09 +01:00
|
|
|
while (ex != null)
|
2018-01-18 12:56:55 +01:00
|
|
|
{
|
|
|
|
messages.Add(ex.Message);
|
|
|
|
ex = ex.InnerException;
|
|
|
|
}
|
|
|
|
string message = String.Join(',', messages.ToArray());
|
|
|
|
|
2019-01-30 05:40:08 +01:00
|
|
|
aggregatorEvent.Error = $"Unexpected error: {message}";
|
|
|
|
_EventAggregator.Publish<InvoiceIPNEvent>(aggregatorEvent);
|
2017-10-27 10:53:04 +02:00
|
|
|
}
|
2017-09-25 18:31:43 +02:00
|
|
|
|
2017-10-27 10:53:04 +02:00
|
|
|
job.TryCount++;
|
2017-09-25 18:31:43 +02:00
|
|
|
|
2017-10-27 10:53:04 +02:00
|
|
|
if (job.TryCount < MaxTry && reschedule)
|
|
|
|
{
|
2022-01-11 06:48:45 +01:00
|
|
|
_JobClient.Schedule((cancellation) => NotifyHttp(job, cancellation), TimeSpan.FromMinutes(10.0));
|
2017-10-27 10:53:04 +02:00
|
|
|
}
|
|
|
|
}
|
2017-09-25 18:31:43 +02:00
|
|
|
|
2018-01-18 12:56:55 +01:00
|
|
|
public class InvoicePaymentNotificationEvent
|
|
|
|
{
|
|
|
|
[JsonProperty("code")]
|
|
|
|
public int Code { get; set; }
|
|
|
|
[JsonProperty("name")]
|
|
|
|
public string Name { get; set; }
|
|
|
|
}
|
|
|
|
public class InvoicePaymentNotificationEventWrapper
|
|
|
|
{
|
|
|
|
[JsonProperty("event")]
|
|
|
|
public InvoicePaymentNotificationEvent Event { get; set; }
|
|
|
|
[JsonProperty("data")]
|
|
|
|
public InvoicePaymentNotification Data { get; set; }
|
2019-01-30 05:40:08 +01:00
|
|
|
[JsonProperty("extendedNotification")]
|
|
|
|
public bool ExtendedNotification { get; set; }
|
|
|
|
[JsonProperty(PropertyName = "notificationURL")]
|
|
|
|
public string NotificationURL { get; set; }
|
2018-01-18 12:56:55 +01:00
|
|
|
}
|
|
|
|
|
2020-06-29 05:07:48 +02:00
|
|
|
readonly Encoding UTF8 = new UTF8Encoding(false);
|
2019-04-05 07:58:25 +02:00
|
|
|
private async Task<HttpResponseMessage> SendNotification(InvoicePaymentNotificationEventWrapper notification, CancellationToken cancellationToken)
|
2017-12-17 06:17:42 +01:00
|
|
|
{
|
|
|
|
var request = new HttpRequestMessage();
|
|
|
|
request.Method = HttpMethod.Post;
|
|
|
|
|
2019-01-30 05:40:08 +01:00
|
|
|
var notificationString = NBitcoin.JsonConverters.Serializer.ToString(notification);
|
|
|
|
var jobj = JObject.Parse(notificationString);
|
2018-01-18 12:56:55 +01:00
|
|
|
|
2019-01-30 05:40:08 +01:00
|
|
|
if (notification.ExtendedNotification)
|
2018-01-18 12:56:55 +01:00
|
|
|
{
|
2019-01-30 05:40:08 +01:00
|
|
|
jobj.Remove("extendedNotification");
|
|
|
|
jobj.Remove("notificationURL");
|
|
|
|
notificationString = jobj.ToString();
|
2018-01-18 12:56:55 +01:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2019-01-30 05:40:08 +01:00
|
|
|
notificationString = jobj["data"].ToString();
|
2018-01-18 12:56:55 +01:00
|
|
|
}
|
|
|
|
|
2019-01-30 05:40:08 +01:00
|
|
|
request.RequestUri = new Uri(notification.NotificationURL, UriKind.Absolute);
|
2018-01-18 12:56:55 +01:00
|
|
|
request.Content = new StringContent(notificationString, UTF8, "application/json");
|
2022-01-11 16:10:55 +01:00
|
|
|
using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
|
|
|
cts.CancelAfter(TimeSpan.FromMinutes(1.0));
|
|
|
|
var response = await _Client.SendAsync(request, cts.Token);
|
2017-12-17 06:17:42 +01:00
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
2020-06-29 05:07:48 +02:00
|
|
|
readonly Dictionary<string, Task> _SendingRequestsByInvoiceId = new Dictionary<string, Task>();
|
2018-02-18 08:09:09 +01:00
|
|
|
|
2020-06-29 05:07:48 +02:00
|
|
|
readonly int MaxTry = 6;
|
|
|
|
readonly CompositeDisposable leases = new CompositeDisposable();
|
2022-01-11 06:48:45 +01:00
|
|
|
|
2017-12-17 06:17:42 +01:00
|
|
|
public Task StartAsync(CancellationToken cancellationToken)
|
|
|
|
{
|
2021-10-06 06:22:55 +02:00
|
|
|
leases.Add(_EventAggregator.SubscribeAsync<InvoiceEvent>(async e =>
|
2017-12-17 06:17:42 +01:00
|
|
|
{
|
2021-10-05 11:10:41 +02:00
|
|
|
if (e.EventCode == InvoiceEventCode.PaymentSettled)
|
|
|
|
{
|
|
|
|
//these are greenfield specific events
|
|
|
|
return;
|
|
|
|
}
|
2018-12-06 09:05:27 +01:00
|
|
|
var invoice = await _InvoiceRepository.GetInvoice(e.Invoice.Id);
|
2018-07-24 05:19:43 +02:00
|
|
|
if (invoice == null)
|
|
|
|
return;
|
2022-01-11 16:26:12 +01:00
|
|
|
bool sendMail = true;
|
2017-12-17 06:17:42 +01:00
|
|
|
// we need to use the status in the event and not in the invoice. The invoice might now be in another status.
|
|
|
|
if (invoice.FullNotifications)
|
|
|
|
{
|
2019-01-06 10:12:45 +01:00
|
|
|
if (e.Name == InvoiceEvent.Expired ||
|
|
|
|
e.Name == InvoiceEvent.PaidInFull ||
|
|
|
|
e.Name == InvoiceEvent.FailedToConfirm ||
|
|
|
|
e.Name == InvoiceEvent.MarkedInvalid ||
|
|
|
|
e.Name == InvoiceEvent.MarkedCompleted ||
|
|
|
|
e.Name == InvoiceEvent.FailedToConfirm ||
|
|
|
|
e.Name == InvoiceEvent.Completed ||
|
|
|
|
e.Name == InvoiceEvent.ExpiredPaidPartial
|
2017-12-17 06:17:42 +01:00
|
|
|
)
|
2022-01-11 16:26:12 +01:00
|
|
|
{
|
2022-01-17 04:55:35 +01:00
|
|
|
await Notify(invoice, e, false, sendMail);
|
2022-01-11 16:26:12 +01:00
|
|
|
sendMail = false;
|
|
|
|
}
|
2017-12-17 06:17:42 +01:00
|
|
|
}
|
2018-01-18 12:56:55 +01:00
|
|
|
|
2019-01-30 05:40:08 +01:00
|
|
|
if (e.Name == InvoiceEvent.Confirmed)
|
2017-12-17 06:17:42 +01:00
|
|
|
{
|
2022-01-17 04:55:35 +01:00
|
|
|
await Notify(invoice, e, false, sendMail);
|
2022-01-11 16:26:12 +01:00
|
|
|
sendMail = false;
|
2017-12-17 06:17:42 +01:00
|
|
|
}
|
2018-01-14 13:48:23 +01:00
|
|
|
|
2018-01-18 12:56:55 +01:00
|
|
|
if (invoice.ExtendedNotifications)
|
|
|
|
{
|
2022-01-17 04:55:35 +01:00
|
|
|
await Notify(invoice, e, true, sendMail);
|
2022-01-11 16:26:12 +01:00
|
|
|
sendMail = false;
|
2018-01-18 12:56:55 +01:00
|
|
|
}
|
2018-01-14 14:06:06 +01:00
|
|
|
}));
|
2017-12-17 06:17:42 +01:00
|
|
|
return Task.CompletedTask;
|
|
|
|
}
|
|
|
|
|
2022-01-11 06:48:45 +01:00
|
|
|
public async Task StopAsync(CancellationToken cancellationToken)
|
2017-12-17 06:17:42 +01:00
|
|
|
{
|
|
|
|
leases.Dispose();
|
2022-01-11 06:48:45 +01:00
|
|
|
await _Queue.Abort(cancellationToken);
|
2017-12-17 06:17:42 +01:00
|
|
|
}
|
2017-10-27 10:53:04 +02:00
|
|
|
}
|
2017-09-25 18:31:43 +02:00
|
|
|
}
|