diff --git a/Areas/Admin/Controllers/BTCPayServerController.cs b/Areas/Admin/Controllers/BTCPayServerController.cs index 8f24e72..56cfa00 100644 --- a/Areas/Admin/Controllers/BTCPayServerController.cs +++ b/Areas/Admin/Controllers/BTCPayServerController.cs @@ -1,5 +1,4 @@ using BTCPayServer.Client; -using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Common.Configuration; using Grand.Business.Core.Interfaces.Common.Localization; using Grand.Business.Core.Interfaces.Common.Logging; @@ -37,23 +36,23 @@ namespace Payments.BTCPayServer.Controllers private readonly IPermissionService _permissionService; private readonly LinkGenerator _linkGenerator; private readonly PaymentSettings _paymentSettings; - private readonly BtcPayService _btcPayService; + private readonly Func _btcPayService; private readonly ILogger _logger; #endregion #region Ctor - public BTCPayServerController(IWorkContext workContext, + public BTCPayServerController( + IWorkContext workContext, LinkGenerator linkGenerator, IStoreService storeService, ISettingService settingService, ITranslationService translationService, PaymentSettings settings, - IOrderService orderService, ILogger logger, IPermissionService permissionService, - IHttpClientFactory httpClientFactory) + Func btcPayService) { _linkGenerator = linkGenerator; _workContext = workContext; @@ -63,8 +62,7 @@ namespace Payments.BTCPayServer.Controllers _permissionService = permissionService; _paymentSettings = settings; _logger = logger; - - _btcPayService = new BtcPayService(orderService, null, logger, httpClientFactory); + _btcPayService = btcPayService; } @@ -75,8 +73,8 @@ namespace Payments.BTCPayServer.Controllers private async Task GetActiveStore() { var stores = await _storeService.GetAllStores(); - if (stores.Count < 2) - return stores.FirstOrDefault()?.Id; + if (stores.Count == 1) + return stores.FirstOrDefault()!.Id; var storeId = _workContext.CurrentCustomer.GetUserFieldFromEntity(SystemCustomerFieldNames.AdminAreaStoreScopeConfiguration); var store = await _storeService.GetStoreById(storeId); @@ -102,16 +100,15 @@ namespace Payments.BTCPayServer.Controllers AdditionalFeePercentage = btcPaySettings.AdditionalFeePercentage, StoreScope = storeScope }; + var store = await _storeService.GetStoreById(storeScope); - /* ViewBag.UrlWebHook = new Uri(new Uri(_storeService.GetStoreById(storeScope).Result.Url), - _linkGenerator.GetPathByAction("Process", "PaymentBTCPayServer"));*/ - ViewBag.UrlWebHook = new Uri(_storeService.GetStoreById(storeScope).Result.Url + "PaymentBTCPayServer/Process"); + ViewBag.UrlWebHook = (store.SslEnabled ? store.SecureUrl : store.Url) + "PaymentBTCPayServer/Process"; return View(model); } [HttpPost] - public async Task Configure(ConfigurationModel model, string command = null) + public async Task Configure(ConfigurationModel model, string? command = null) { if (!await _permissionService.Authorize(StandardPermission.ManagePaymentMethods)) return AccessDeniedView(); @@ -163,16 +160,9 @@ namespace Payments.BTCPayServer.Controllers return await Configure(); } - /*if (!ModelState.IsValid) - { - Error("Incorrect data"); - return await Configure(); - }*/ - - //save settings - settings.BtcPayUrl = model.BtcPayUrl.Trim(); + settings.BtcPayUrl = model.BtcPayUrl?.Trim(); settings.ApiKey = model.ApiKey?.Trim(); settings.BtcPayStoreID = model.BtcPayStoreID?.Trim(); settings.WebHookSecret = model.WebHookSecret?.Trim(); @@ -196,48 +186,35 @@ namespace Payments.BTCPayServer.Controllers [HttpPost] [IgnoreAntiforgeryToken] - public async Task GetAutomaticApiKeyConfig() + public async Task GetAutomaticApiKeyConfig(BtcPayConfigModel model) { var myStore = _workContext.CurrentStore; - Request.Query.TryGetValue("ssid", out var ssidx); - var ssid = ssidx.FirstOrDefault(); // ?? myStore.Id; - if (ssid != myStore.Id) + if (model.Ssid != myStore.Id) { await _logger.InsertLog(LogLevel.Error, "GetAutomaticApiKeyConfig(): NotFound"); return NotFound(); } - //var storeScope = await GetActiveStore(); - //var settings = _settingService.LoadSetting(storeScope); var settings = _settingService.LoadSetting(myStore.Id); try { - Request.Form.TryGetValue("apiKey", out var apiKey); - Request.Form.TryGetValue("permissions[]", out var permissions); - Permission.TryParse(permissions.FirstOrDefault(), out var permission); - if (Request.Query.TryGetValue("btcpayuri", out var btcpayUris) && - btcpayUris.FirstOrDefault() is { } stringbtcpayUri) - { - settings.BtcPayUrl = stringbtcpayUri; - } + settings.BtcPayUrl = model.Btcpayuri; + settings.ApiKey = model.ApiKey; + settings.BtcPayStoreID = model.Scope; - settings.ApiKey = apiKey; - settings.BtcPayStoreID = permission.Scope; try { - if (permission.Scope is null) + if (model.Scope is null) { - settings.BtcPayStoreID = await _btcPayService.GetStoreId(settings); + settings.BtcPayStoreID = await _btcPayService().GetStoreId(settings); } if (string.IsNullOrEmpty(settings.WebHookSecret)) { - var webhookUrl = new Uri(myStore.Url + "PaymentBTCPayServer/Process"); - /*new Uri(new Uri(myStore.Url), - _linkGenerator.GetPathByAction("Process", "PaymentBTCPayServer"));*/ - settings.WebHookSecret = await _btcPayService.CreateWebHook(settings, webhookUrl.ToString()); + var webhookUrl = (myStore.SslEnabled ? myStore.SecureUrl : myStore.Url) + "PaymentBTCPayServer/Process"; + settings.WebHookSecret = await _btcPayService().CreateWebHook(settings, webhookUrl.ToString()); } } catch (Exception ex) @@ -274,11 +251,9 @@ namespace Payments.BTCPayServer.Controllers var myStore = _workContext.CurrentStore; - //var adminUrl = new Uri(new Uri(myStore.Url), - //var adminUrl = new Uri(new Uri((Request.IsHttps ? "https://" : "http://") + Request.Host.Value), var adminUrl = new Uri(new Uri("https://" + Request.Host.Value), - _linkGenerator.GetPathByAction(HttpContext, "GetAutomaticApiKeyConfig", "BTCPayServer", - new { ssid = myStore.Id, btcpayuri = btcpayUri })); + _linkGenerator.GetPathByAction(HttpContext, "GetAutomaticApiKeyConfig", "PaymentBTCPayConfig", + new { ssid = myStore.Id, btcpayuri = btcpayUri, area = "" })); var uri = BTCPayServerClient.GenerateAuthorizeUri(btcpayUri, new[] { diff --git a/Areas/Admin/Views/BTCPayServer/Configure.cshtml b/Areas/Admin/Views/BTCPayServer/Configure.cshtml index 9c6685c..3f71c8e 100644 --- a/Areas/Admin/Views/BTCPayServer/Configure.cshtml +++ b/Areas/Admin/Views/BTCPayServer/Configure.cshtml @@ -62,7 +62,7 @@
- + diff --git a/BTCPayServerPaymentProvider.cs b/BTCPayServerPaymentProvider.cs index f60c8ad..08882fc 100644 --- a/BTCPayServerPaymentProvider.cs +++ b/BTCPayServerPaymentProvider.cs @@ -1,5 +1,4 @@ using Grand.Business.Core.Enums.Checkout; -using Grand.Business.Core.Interfaces.Catalog.Products; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Interfaces.Common.Directory; @@ -17,6 +16,8 @@ using Microsoft.Extensions.DependencyInjection; using Payments.BTCPayServer.Models; using Payments.BTCPayServer.Services; +#nullable enable + namespace Payments.BTCPayServer { public class BTCPayServerPaymentProvider : IPaymentProvider @@ -25,38 +26,34 @@ namespace Payments.BTCPayServer private readonly BtcPaySettings _btcPaySettings; private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IProductService _productService; private readonly IServiceProvider _serviceProvider; private readonly IWorkContext _workContext; private readonly ILogger _logger; private readonly IOrderService _orderService; private readonly LinkGenerator _linkGenerator; - private readonly BtcPayService _btcPayService; + private readonly Func _btcPayService; public BTCPayServerPaymentProvider( IHttpContextAccessor httpContextAccessor, ITranslationService translationService, - IProductService productService, IServiceProvider serviceProvider, IWorkContext workContext, BtcPaySettings btcPaySettings, LinkGenerator linkGenerator, IOrderService orderService, ILogger logger, - IHttpClientFactory httpClientFactory) + Func btcPayService) { _httpContextAccessor = httpContextAccessor; _translationService = translationService; - _productService = productService; _serviceProvider = serviceProvider; _workContext = workContext; _btcPaySettings = btcPaySettings; _linkGenerator = linkGenerator; _orderService = orderService; _logger = logger; - - _btcPayService = new BtcPayService(_orderService, null, logger, httpClientFactory); + _btcPayService = btcPayService; } public PaymentMethodType PaymentMethodType => PaymentMethodType.Redirection; @@ -135,9 +132,9 @@ namespace Payments.BTCPayServer } if (!(result > 0)) return result; - var currencyService = _serviceProvider.GetRequiredService(); - var workContext = _serviceProvider.GetRequiredService(); - result = await currencyService.ConvertFromPrimaryStoreCurrency(result, workContext.WorkingCurrency); + + var currencyService = _serviceProvider.GetRequiredService(); + result = await currencyService.ConvertFromPrimaryStoreCurrency(result, _workContext.WorkingCurrency); return result; } @@ -156,9 +153,11 @@ namespace Payments.BTCPayServer return await Task.FromResult(false); } - public async Task InitPaymentTransaction() + public Task InitPaymentTransaction() { - return await Task.FromResult(null); +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. + return Task.FromResult(null); +#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type. } public async Task ProcessPayment(PaymentTransaction paymentTransaction) @@ -186,7 +185,7 @@ namespace Payments.BTCPayServer Customer? myCustomer = _workContext.CurrentCustomer; - var invoice = await _btcPayService.CreateInvoice(_btcPaySettings, new PaymentDataModel() { + var invoice = await _btcPayService().CreateInvoice(_btcPaySettings, new PaymentDataModel() { CurrencyCode = paymentTransaction.CurrencyCode, Amount = (decimal)paymentTransaction.TransactionAmount, BuyerEmail = myCustomer.Email ?? (myCustomer.BillingAddress.Email ?? myCustomer.ShippingAddress.Email), @@ -225,9 +224,6 @@ namespace Payments.BTCPayServer DisplayToCustomer = true, CreatedOnUtc = DateTime.UtcNow }); - - _httpContextAccessor.HttpContext?.Response.Redirect(myStore.Url + "/badredirect"); - } } @@ -238,7 +234,7 @@ namespace Payments.BTCPayServer try { var order = await _orderService.GetOrderByGuid(refundPaymentRequest.PaymentTransaction.OrderGuid); - var sUrl = await _btcPayService.CreateRefund(_btcPaySettings, refundPaymentRequest); + var sUrl = await _btcPayService().CreateRefund(_btcPaySettings, refundPaymentRequest); if (sUrl == null) { throw new Exception("Refund : Error with BTCPay"); } result.NewTransactionStatus = refundPaymentRequest.IsPartialRefund ? TransactionStatus.PartiallyRefunded : TransactionStatus.Refunded; await _orderService.InsertOrderNote(new OrderNote { @@ -259,7 +255,9 @@ namespace Payments.BTCPayServer public async Task SavePaymentInfo(IDictionary model) { +#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. return await Task.FromResult(null); +#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type. } public async Task SkipPaymentInfo() @@ -301,13 +299,6 @@ namespace Payments.BTCPayServer public async Task> ValidatePaymentForm(IDictionary model) { - var warnings = new List(); - - /*if (form["Agree"] == "false") - { - var checkAgree = Task.Run(() => _localizationService.GetResourceAsync("Plugins.Payments.SwissBitcoinPay.CheckAgree")).Result; - warnings.Add(checkAgree); - }*/ return await Task.FromResult(new List()); } diff --git a/BtcPaySettings.cs b/BtcPaySettings.cs index a1726e0..4159fea 100644 --- a/BtcPaySettings.cs +++ b/BtcPaySettings.cs @@ -10,7 +10,7 @@ namespace Payments.BTCPayServer /// /// The url of your BTCPay instance /// - public string BtcPayUrl { get; set; } + public string? BtcPayUrl { get; set; } /// /// The API Key value generated in your BTCPay instance diff --git a/Controllers/PaymentBTCPayConfigController.cs b/Controllers/PaymentBTCPayConfigController.cs new file mode 100644 index 0000000..5cf9414 --- /dev/null +++ b/Controllers/PaymentBTCPayConfigController.cs @@ -0,0 +1,31 @@ +using BTCPayServer.Client; +using Grand.Web.Common.Controllers; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Payments.BTCPayServer.Models; + +namespace Payments.BTCPayServer.Controllers +{ + public class PaymentBTCPayConfigController : BaseController + { + + public PaymentBTCPayConfigController() + { + } + + + [AllowAnonymous] + [HttpPost] + [IgnoreAntiforgeryToken] + public IActionResult GetAutomaticApiKeyConfig(string ssid, string btcpayuri) + { + Request.Form.TryGetValue("apiKey", out var apiKey); + Request.Form.TryGetValue("permissions[]", out var permissions); + + Permission.TryParse(permissions.FirstOrDefault(), out var permission); + + var model = new BtcPayConfigModel(ssid, btcpayuri, permission.Scope, apiKey!); + return View(model); + } + } +} diff --git a/Controllers/PaymentBTCPayServerController.cs b/Controllers/PaymentBTCPayServerController.cs index 1699f5b..abfe591 100644 --- a/Controllers/PaymentBTCPayServerController.cs +++ b/Controllers/PaymentBTCPayServerController.cs @@ -1,6 +1,5 @@ using BTCPayServer.Client.Models; using Grand.Business.Core.Interfaces.Checkout.Orders; -using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Interfaces.Common.Configuration; using Grand.Business.Core.Interfaces.Common.Logging; using Grand.Domain.Logging; @@ -18,18 +17,17 @@ namespace BTCPayServer.Controllers private readonly ISettingService _settingService; private readonly IOrderService _orderService; private readonly ILogger _logger; - private readonly BtcPayService _btcPayService; + private readonly Func _btcPayService; public PaymentBTCPayServerController(IOrderService orderService, ISettingService settingService, ILogger logger, - IPaymentTransactionService paymentTransactionService, - IHttpClientFactory httpClientFactory) + Func btcPayService) { _settingService = settingService; _orderService = orderService; _logger = logger; - _btcPayService = new BtcPayService(orderService, paymentTransactionService, logger, httpClientFactory); + _btcPayService = btcPayService; } @@ -68,8 +66,8 @@ namespace BTCPayServer.Controllers return StatusCode(StatusCodes.Status400BadRequest); } - var invoice = await _btcPayService.GetInvoice(settings, webhookEvent.InvoiceId); - await _btcPayService.UpdateOrderWithInvoice(order, invoice, webhookEvent); + var invoice = await _btcPayService().GetInvoice(settings, webhookEvent.InvoiceId); + await _btcPayService().UpdateOrderWithInvoice(order, invoice, webhookEvent); return StatusCode(StatusCodes.Status200OK); diff --git a/EndpointProvider.cs b/EndpointProvider.cs index 9c2e8a4..a6a360f 100644 --- a/EndpointProvider.cs +++ b/EndpointProvider.cs @@ -11,7 +11,7 @@ namespace Payments.BTCPayServer endpointRouteBuilder.MapControllerRoute("Plugin.PaymentBTCPayServer", "Plugins/PaymentBTCPayServer/PaymentInfo", new { controller = "PaymentBTCPayServer", action = "PaymentInfo", area = "" } - ); + ); } public int Priority => 0; diff --git a/Models/BtcPayConfigModel.cs b/Models/BtcPayConfigModel.cs new file mode 100644 index 0000000..ff39052 --- /dev/null +++ b/Models/BtcPayConfigModel.cs @@ -0,0 +1,4 @@ + +namespace Payments.BTCPayServer.Models; + +public record BtcPayConfigModel(string Ssid, string Btcpayuri, string Scope, string ApiKey); diff --git a/Models/BtcPayHookModel.cs b/Models/BtcPayHookModel.cs index 276572e..0c0bfea 100644 --- a/Models/BtcPayHookModel.cs +++ b/Models/BtcPayHookModel.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + namespace Payments.BTCPayServer.Models { @@ -10,13 +6,9 @@ namespace Payments.BTCPayServer.Models { public bool enabled = true; public bool automaticRedelivery = true; - public string url; - public BtcPayHookAuthorizedEvents authorizedEvents = new BtcPayHookAuthorizedEvents(); - public string secret; - - public BtcPayHookModel() - { - } + public string? url; + public BtcPayHookAuthorizedEvents authorizedEvents = new(); + public string? secret; } public struct BtcPayHookAuthorizedEvents diff --git a/Models/BtcPayRefundModel.cs b/Models/BtcPayRefundModel.cs index 3258108..d510c06 100644 --- a/Models/BtcPayRefundModel.cs +++ b/Models/BtcPayRefundModel.cs @@ -2,15 +2,15 @@ { public class BtcPayRefundModel { - public string name; - public string description; - public string paymentMethod; - public string refundVariant; + public string? name; + public string? description; + public string? paymentMethod; + public string? refundVariant; } public class BtcPayRefundCustomModel : BtcPayRefundModel { public decimal customAmount; - public string customCurrency; + public string? customCurrency; } } diff --git a/Models/ConfigurationModel.cs b/Models/ConfigurationModel.cs index 9934a24..8513c61 100644 --- a/Models/ConfigurationModel.cs +++ b/Models/ConfigurationModel.cs @@ -11,9 +11,8 @@ namespace Payments.BTCPayServer.Models public string? StoreScope { get; set; } [GrandResourceDisplayName("Plugins.Payments.BTCPayServer.BtcPayUrl")] - //[Url] [Required] - public string BtcPayUrl { get; set; } + public string? BtcPayUrl { get; set; } [GrandResourceDisplayName("Plugins.Payments.BTCPayServer.ApiKey")] public string? ApiKey { get; set; } @@ -22,7 +21,6 @@ namespace Payments.BTCPayServer.Models public string? BtcPayStoreID { get; set; } [GrandResourceDisplayName("Plugins.Payments.BTCPayServer.WebHookSecret")] - //[PasswordPropertyText] public string? WebHookSecret { get; set; } diff --git a/Payments - Backup.BTCPayServer.csproj b/Payments - Backup.BTCPayServer.csproj deleted file mode 100644 index d1769ef..0000000 --- a/Payments - Backup.BTCPayServer.csproj +++ /dev/null @@ -1,71 +0,0 @@ - - - - true - net6.0 - enable - enable - - - - ..\..\Web\Grand.Web\Plugins\Payments.BTCPayServer\ - $(OutputPath) - - - - ..\..\Web\Grand.Web\Plugins\Payments.BTCPayServer\ - - $(OutputPath) - - - - - - false - - - false - - - false - - - false - - - false - - - false - - - false - - - false - - - false - - - false - - - false - - - false - - - false - - - false - - - - - - - - diff --git a/Payments.BTCPayServer.csproj b/Payments.BTCPayServer.csproj index 1d83b8e..2d4ef10 100644 --- a/Payments.BTCPayServer.csproj +++ b/Payments.BTCPayServer.csproj @@ -1,4 +1,4 @@ - + true @@ -24,34 +24,7 @@ - - false - - - false - - - false - - - false - - - false - - - false - - - false - - - false - - - false - - + false @@ -67,13 +40,22 @@ false - + + + + + + + + + + PreserveNewest - + diff --git a/Services/BtcPayService.cs b/Services/BtcPayService.cs index 8935e2d..02c0a34 100644 --- a/Services/BtcPayService.cs +++ b/Services/BtcPayService.cs @@ -1,6 +1,5 @@ using BTCPayServer.Client; using BTCPayServer.Client.Models; -using Grand.Business.Checkout.Services.Payments; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Interfaces.Common.Logging; @@ -19,11 +18,12 @@ namespace Payments.BTCPayServer.Services private readonly IHttpClientFactory _httpClientFactory; private readonly IOrderService _orderService; - private readonly IPaymentTransactionService? _paymentTransactionService; + private readonly IPaymentTransactionService _paymentTransactionService; private readonly ILogger _logger; - public BtcPayService(IOrderService orderService, - IPaymentTransactionService? paymentTransactionService, + public BtcPayService( + IOrderService orderService, + IPaymentTransactionService paymentTransactionService, ILogger logger, IHttpClientFactory httpClientFactory) { @@ -268,7 +268,7 @@ namespace Payments.BTCPayServer.Services public BTCPayServerClient GetClient(BtcPaySettings settings) { - return new BTCPayServerClient(new Uri(settings.BtcPayUrl), settings.ApiKey, + return new BTCPayServerClient(new Uri(settings.BtcPayUrl!), settings.ApiKey, _httpClientFactory.CreateClient("BTCPayServer")); } diff --git a/StartupApplication.cs b/StartupApplication.cs index 6eaf368..d112298 100644 --- a/StartupApplication.cs +++ b/StartupApplication.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Payments.BTCPayServer.Services; namespace Payments.BTCPayServer { @@ -12,6 +13,11 @@ namespace Payments.BTCPayServer public void ConfigureServices(IServiceCollection services, IConfiguration configuration) { services.AddScoped(); + services.AddScoped(); + services.AddScoped>(serviceProvider => + { + return () => serviceProvider.GetRequiredService(); + }); } public int Priority => 10; diff --git a/Views/PaymentBTCPayConfig/GetAutomaticApiKeyConfig.cshtml b/Views/PaymentBTCPayConfig/GetAutomaticApiKeyConfig.cshtml new file mode 100644 index 0000000..ee7a02b --- /dev/null +++ b/Views/PaymentBTCPayConfig/GetAutomaticApiKeyConfig.cshtml @@ -0,0 +1,19 @@ +@model Payments.BTCPayServer.Models.BtcPayConfigModel +@{ + Layout = ""; +} +
+
+ + + + + + +
+ \ No newline at end of file