Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Implementation of Stripe Checkout as a Replacement for PayPal Plugin #460 (#465)
Krzysztof Pajak073d7eb67358
diff --git a/.github/workflows/grandnode.yml b/.github/workflows/grandnode.ymlindex dd7d6a622..d913ae380 100644--- a/.github/workflows/grandnode.yml+++ b/.github/workflows/grandnode.yml@@ -1,5 +1,5 @@name: Build and deploy .NET Core app to Linux WebApp grandnode-on:+on:push:branches: [ "main" ]@@ -8,7 +8,7 @@ env:AZURE_WEBAPP_PACKAGE_PATH: src/Web/Grand.Web/publishAZURE_WEBAPP_PUBLISH_PROFILE: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }}CONFIGURATION: Release- DOTNET_CORE_VERSION: 8.0.x+ DOTNET_CORE_VERSION: 8.0.101WORKING_DIRECTORY: src/Web/Grand.Webjobs:build-and-deploy:diff --git a/Dockerfile b/Dockerfileindex 004af1039..349faaaf7 100644--- a/Dockerfile+++ b/Dockerfile@@ -15,7 +15,7 @@ RUN dotnet build /app/Plugins/DiscountRules.Standard -c Release -p:SourceRevisioRUN dotnet build /app/Plugins/ExchangeRate.McExchange -c Release -p:SourceRevisionId=$GIT_COMMIT -p:GitBranch=$GIT_BRANCHRUN dotnet build /app/Plugins/Payments.BrainTree -c Release -p:SourceRevisionId=$GIT_COMMIT -p:GitBranch=$GIT_BRANCHRUN dotnet build /app/Plugins/Payments.CashOnDelivery -c Release -p:SourceRevisionId=$GIT_COMMIT -p:GitBranch=$GIT_BRANCH-RUN dotnet build /app/Plugins/Payments.PayPalStandard -c Release -p:SourceRevisionId=$GIT_COMMIT -p:GitBranch=$GIT_BRANCH+RUN dotnet build /app/Plugins/Payments.StripeCheckout -c Release -p:SourceRevisionId=$GIT_COMMIT -p:GitBranch=$GIT_BRANCHRUN dotnet build /app/Plugins/Shipping.ByWeight -c Release -p:SourceRevisionId=$GIT_COMMIT -p:GitBranch=$GIT_BRANCHRUN dotnet build /app/Plugins/Shipping.FixedRateShipping -c Release -p:SourceRevisionId=$GIT_COMMIT -p:GitBranch=$GIT_BRANCHRUN dotnet build /app/Plugins/Shipping.ShippingPoint -c Release -p:SourceRevisionId=$GIT_COMMIT -p:GitBranch=$GIT_BRANCHdiff --git a/GrandNode.sln b/GrandNode.slnindex e232deef3..c3c609fcc 100644--- a/GrandNode.sln+++ b/GrandNode.sln@@ -61,8 +61,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tax.CountryStateZip", "src\EndProjectProject("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExchangeRate.McExchange", "src\Plugins\ExchangeRate.McExchange\ExchangeRate.McExchange.csproj", "{67844BF0-10DC-4C0A-B913-FCEF3F7FDC8C}"EndProject-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Payments.PayPalStandard", "src\Plugins\Payments.PayPalStandard\Payments.PayPalStandard.csproj", "{74F49DFE-6682-4390-8314-AF5E3E50D5E4}"-EndProjectProject("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Shipping.ShippingPoint", "src\Plugins\Shipping.ShippingPoint\Shipping.ShippingPoint.csproj", "{B98D0EE8-F3E3-4B9F-AB50-BD33CA8EE5C5}"EndProjectProject("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Widgets.FacebookPixel", "src\Plugins\Widgets.FacebookPixel\Widgets.FacebookPixel.csproj", "{DD3F159F-B858-49AD-8DEF-CB7A3FA47B94}"@@ -135,6 +133,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grand.SharedUIResources", "EndProjectProject("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Theme.Modern", "src\Plugins\Theme.Modern\Theme.Modern.csproj", "{9DAAD56A-8DB7-4A41-BAF3-9486D617AB05}"EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Payments.StripeCheckout", "src\Plugins\Payments.StripeCheckout\Payments.StripeCheckout.csproj", "{8AD9B827-7FB6-4581-85BB-82D7F298DE1A}"+EndProjectGlobalGlobalSection(SolutionConfigurationPlatforms) = preSolutionDebug|Any CPU = Debug|Any CPU@@ -237,10 +237,6 @@ Global{67844BF0-10DC-4C0A-B913-FCEF3F7FDC8C}.Debug|Any CPU.Build.0 = Debug|Any CPU{67844BF0-10DC-4C0A-B913-FCEF3F7FDC8C}.Release|Any CPU.ActiveCfg = Release|Any CPU{67844BF0-10DC-4C0A-B913-FCEF3F7FDC8C}.Release|Any CPU.Build.0 = Release|Any CPU- {74F49DFE-6682-4390-8314-AF5E3E50D5E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU- {74F49DFE-6682-4390-8314-AF5E3E50D5E4}.Debug|Any CPU.Build.0 = Debug|Any CPU- {74F49DFE-6682-4390-8314-AF5E3E50D5E4}.Release|Any CPU.ActiveCfg = Release|Any CPU- {74F49DFE-6682-4390-8314-AF5E3E50D5E4}.Release|Any CPU.Build.0 = Release|Any CPU{B98D0EE8-F3E3-4B9F-AB50-BD33CA8EE5C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU{B98D0EE8-F3E3-4B9F-AB50-BD33CA8EE5C5}.Debug|Any CPU.Build.0 = Debug|Any CPU{B98D0EE8-F3E3-4B9F-AB50-BD33CA8EE5C5}.Release|Any CPU.ActiveCfg = Release|Any CPU@@ -356,6 +352,10 @@ Global{9DAAD56A-8DB7-4A41-BAF3-9486D617AB05}.Debug|Any CPU.Build.0 = Debug|Any CPU{9DAAD56A-8DB7-4A41-BAF3-9486D617AB05}.Release|Any CPU.ActiveCfg = Release|Any CPU{9DAAD56A-8DB7-4A41-BAF3-9486D617AB05}.Release|Any CPU.Build.0 = Release|Any CPU+ {8AD9B827-7FB6-4581-85BB-82D7F298DE1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {8AD9B827-7FB6-4581-85BB-82D7F298DE1A}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {8AD9B827-7FB6-4581-85BB-82D7F298DE1A}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {8AD9B827-7FB6-4581-85BB-82D7F298DE1A}.Release|Any CPU.Build.0 = Release|Any CPUEndGlobalSectionGlobalSection(SolutionProperties) = preSolutionHideSolutionNode = FALSE@@ -384,7 +384,6 @@ Global{7FB9D801-F924-4AEE-94F6-B95997077FA3} = {F6F48227-B3C5-4A51-B33F-FF9AD96352DB}{6B0F6DFC-89FD-47AD-B793-C595ED134AD9} = {F6F48227-B3C5-4A51-B33F-FF9AD96352DB}{67844BF0-10DC-4C0A-B913-FCEF3F7FDC8C} = {F6F48227-B3C5-4A51-B33F-FF9AD96352DB}- {74F49DFE-6682-4390-8314-AF5E3E50D5E4} = {F6F48227-B3C5-4A51-B33F-FF9AD96352DB}{B98D0EE8-F3E3-4B9F-AB50-BD33CA8EE5C5} = {F6F48227-B3C5-4A51-B33F-FF9AD96352DB}{DD3F159F-B858-49AD-8DEF-CB7A3FA47B94} = {F6F48227-B3C5-4A51-B33F-FF9AD96352DB}{9757F07A-8B94-4C0C-9BC3-16C34DB8E12A} = {F6F48227-B3C5-4A51-B33F-FF9AD96352DB}@@ -415,6 +414,7 @@ Global{1A6A0104-F610-4DD3-88BE-C4029034E5DA} = {BF4543A8-0731-4FDD-BB6B-0ADB9561F981}{09958AAA-44BC-42DE-86D1-0E39EF3C0C68} = {BF4543A8-0731-4FDD-BB6B-0ADB9561F981}{9DAAD56A-8DB7-4A41-BAF3-9486D617AB05} = {F6F48227-B3C5-4A51-B33F-FF9AD96352DB}+ {8AD9B827-7FB6-4581-85BB-82D7F298DE1A} = {F6F48227-B3C5-4A51-B33F-FF9AD96352DB}EndGlobalSectionGlobalSection(ExtensibilityGlobals) = postSolutionSolutionGuid = {88B478F4-FD3B-4C24-9E84-4FAAF0254397}diff --git a/README.md b/README.mdindex eb48567c4..45774e56a 100644--- a/README.md+++ b/README.md@@ -106,7 +106,7 @@ dotnet restore GrandNode.sln```Now it's time to rebuild all of our plugins and publish application (command is pretty long because we've combined all commands in a single line, to ease up your work):```-sudo dotnet build src/Plugins/Authentication.Facebook && sudo dotnet build src/Plugins/Authentication.Google && sudo dotnet build src/Plugins/DiscountRules.Standard && sudo dotnet build src/Plugins/ExchangeRate.McExchange && sudo dotnet build src/Plugins/Payments.BrainTree && sudo dotnet build src/Plugins/Payments.CashOnDelivery && sudo dotnet build src/Plugins/Payments.PayPalStandard && sudo dotnet build src/Plugins/Shipping.ByWeight && sudo dotnet build src/Plugins/Shipping.FixedRateShipping && sudo dotnet build src/Plugins/Shipping.ShippingPoint && sudo dotnet build src/Plugins/Tax.CountryStateZip && sudo dotnet build src/Plugins/Tax.FixedRate && sudo dotnet build src/Plugins/Widgets.FacebookPixel && sudo dotnet build src/Plugins/Widgets.GoogleAnalytics && sudo dotnet build src/Plugins/Widgets.Slider && sudo dotnet build src/Plugins/Theme.Modern && sudo dotnet publish src/Web/Grand.Web -c Release -o /var/webapps/grandnode+sudo dotnet build src/Plugins/Authentication.Facebook && sudo dotnet build src/Plugins/Authentication.Google && sudo dotnet build src/Plugins/DiscountRules.Standard && sudo dotnet build src/Plugins/ExchangeRate.McExchange && sudo dotnet build src/Plugins/Payments.BrainTree && sudo dotnet build src/Plugins/Payments.CashOnDelivery && sudo dotnet build src/Plugins/Payments.StripeCheckout && sudo dotnet build src/Plugins/Shipping.ByWeight && sudo dotnet build src/Plugins/Shipping.FixedRateShipping && sudo dotnet build src/Plugins/Shipping.ShippingPoint && sudo dotnet build src/Plugins/Tax.CountryStateZip && sudo dotnet build src/Plugins/Tax.FixedRate && sudo dotnet build src/Plugins/Widgets.FacebookPixel && sudo dotnet build src/Plugins/Widgets.GoogleAnalytics && sudo dotnet build src/Plugins/Widgets.Slider && sudo dotnet build src/Plugins/Theme.Modern && sudo dotnet publish src/Web/Grand.Web -c Release -o /var/webapps/grandnode```Optional: Create the service file, to automatically restart your application.```diff --git a/src/Business/Grand.Business.System/Services/Installation/InstallDataSettings.cs b/src/Business/Grand.Business.System/Services/Installation/InstallDataSettings.csindex c14de45c2..c822a7267 100644--- a/src/Business/Grand.Business.System/Services/Installation/InstallDataSettings.cs+++ b/src/Business/Grand.Business.System/Services/Installation/InstallDataSettings.cs@@ -427,7 +427,7 @@ namespace Grand.Business.System.Services.Installationawait _settingService.SaveSetting(new PaymentSettings {ActivePaymentProviderSystemNames = ["Payments.CashOnDelivery",- "Payments.PayPalStandard",+ "Payments.StripeCheckout","Payments.BrainTree"],AllowRePostingPayments = true,diff --git a/src/Plugins/Payments.PayPalStandard/Areas/Admin/Controllers/PayPalStandardController.cs b/src/Plugins/Payments.PayPalStandard/Areas/Admin/Controllers/PayPalStandardController.csdeleted file mode 100644index 0382219b4..000000000--- a/src/Plugins/Payments.PayPalStandard/Areas/Admin/Controllers/PayPalStandardController.cs+++ /dev/null@@ -1,111 +0,0 @@-using Grand.Business.Core.Interfaces.Common.Configuration;-using Grand.Business.Core.Interfaces.Common.Localization;-using Grand.Business.Core.Interfaces.Common.Security;-using Grand.Business.Core.Interfaces.Common.Stores;-using Grand.Business.Core.Utilities.Common.Security;-using Grand.Domain.Common;-using Grand.Domain.Customers;-using Grand.Infrastructure;-using Grand.Web.Common.Controllers;-using Grand.Web.Common.Filters;-using Grand.Web.Common.Security.Authorization;-using Microsoft.AspNetCore.Mvc;-using Payments.PayPalStandard.Models;--namespace Payments.PayPalStandard.Areas.Admin.Controllers-{- [AuthorizeAdmin]- [Area("Admin")]- [PermissionAuthorize(PermissionSystemName.PaymentMethods)]- public class PayPalStandardController : BasePaymentController- {- private readonly IWorkContext _workContext;- private readonly IStoreService _storeService;- private readonly ISettingService _settingService;- private readonly ITranslationService _translationService;- private readonly IPermissionService _permissionService;-- public PayPalStandardController(IWorkContext workContext,- IStoreService storeService,- ISettingService settingService,- ITranslationService translationService,- IPermissionService permissionService)- {- _workContext = workContext;- _storeService = storeService;- _settingService = settingService;- _translationService = translationService;- _permissionService = permissionService;- }-- private async Task<string> GetActiveStore()- {- var stores = await _storeService.GetAllStores();- if (stores.Count < 2)- return stores.FirstOrDefault()?.Id;-- var storeId = _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.AdminAreaStoreScopeConfiguration);- var store = await _storeService.GetStoreById(storeId);-- return store != null ? store.Id : "";- }-- public async Task<IActionResult> Configure()- {- if (!await _permissionService.Authorize(StandardPermission.ManagePaymentMethods))- return AccessDeniedView();-- //load settings for a chosen store scope- var storeScope = await GetActiveStore();- var payPalStandardPaymentSettings = _settingService.LoadSetting<PayPalStandardPaymentSettings>(storeScope);-- var model = new ConfigurationModel {- UseSandbox = payPalStandardPaymentSettings.UseSandbox,- BusinessEmail = payPalStandardPaymentSettings.BusinessEmail,- PdtToken = payPalStandardPaymentSettings.PdtToken,- PdtValidateOrderTotal = payPalStandardPaymentSettings.PdtValidateOrderTotal,- AdditionalFee = payPalStandardPaymentSettings.AdditionalFee,- AdditionalFeePercentage = payPalStandardPaymentSettings.AdditionalFeePercentage,- PassProductNamesAndTotals = payPalStandardPaymentSettings.PassProductNamesAndTotals,- DisplayOrder = payPalStandardPaymentSettings.DisplayOrder,- StoreScope = storeScope- };-- return View(model);- }-- [HttpPost]- public async Task<IActionResult> Configure(ConfigurationModel model)- {- if (!await _permissionService.Authorize(StandardPermission.ManagePaymentMethods))- return AccessDeniedView();-- if (!ModelState.IsValid)- return await Configure();-- //load settings for a chosen store scope- var storeScope = await GetActiveStore();- var payPalStandardPaymentSettings = _settingService.LoadSetting<PayPalStandardPaymentSettings>(storeScope);-- //save settings- payPalStandardPaymentSettings.UseSandbox = model.UseSandbox;- payPalStandardPaymentSettings.BusinessEmail = model.BusinessEmail;- payPalStandardPaymentSettings.PdtToken = model.PdtToken;- payPalStandardPaymentSettings.PdtValidateOrderTotal = model.PdtValidateOrderTotal;- payPalStandardPaymentSettings.AdditionalFee = model.AdditionalFee;- payPalStandardPaymentSettings.AdditionalFeePercentage = model.AdditionalFeePercentage;- payPalStandardPaymentSettings.PassProductNamesAndTotals = model.PassProductNamesAndTotals;- payPalStandardPaymentSettings.DisplayOrder = model.DisplayOrder;-- await _settingService.SaveSetting(payPalStandardPaymentSettings, storeScope);-- //now clear settings cache- await _settingService.ClearCache();-- Success(_translationService.GetResource("Admin.Plugins.Saved"));-- return await Configure();- }-- }-}\ No newline at end of filediff --git a/src/Plugins/Payments.PayPalStandard/Areas/Admin/Views/PayPalStandard/Configure.cshtml b/src/Plugins/Payments.PayPalStandard/Areas/Admin/Views/PayPalStandard/Configure.cshtmldeleted file mode 100644index 6aa7db1e4..000000000--- a/src/Plugins/Payments.PayPalStandard/Areas/Admin/Views/PayPalStandard/Configure.cshtml+++ /dev/null@@ -1,105 +0,0 @@-@{- Layout = "_ConfigurePlugin";-}-@model ConfigurationModel-@using Payments.PayPalStandard.Models;-@await Component.InvokeAsync("StoreScope")--<form asp-area="Admin" asp-controller="PayPalStandard" asp-action="Configure" method="post">-- <div class="form-horizontal">- <div class="form-body">- <div class="form-group">- <div class="col-md-3 col-sm-3 text-right">- <admin-label asp-for="UseSandbox" class="control-label" />- </div>- <div class="col-md-9 col-sm-9">- <label class="mt-checkbox mt-checkbox-outline control control-checkbox">- <admin-input asp-for="UseSandbox" />- <div class="control__indicator"></div>- </label>- <span asp-validation-for="UseSandbox"></span>- </div>- </div>- <div class="form-group">- <div class="col-md-3 col-sm-3 text-right">- <admin-label asp-for="BusinessEmail" class="control-label" />- </div>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="BusinessEmail" />- <span asp-validation-for="BusinessEmail"></span>- </div>- </div>- <div class="form-group">- <div class="col-md-3 col-sm-3 text-right">- <admin-label asp-for="PdtToken" class="control-label" />- </div>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="PdtToken" />- <span asp-validation-for="PdtToken"></span>- </div>- </div>- <div class="form-group">- <div class="col-md-3 col-sm-3 text-right">- <admin-label asp-for="PdtValidateOrderTotal" class="control-label" />- </div>- <div class="col-md-9 col-sm-9">- <label class="mt-checkbox mt-checkbox-outline control control-checkbox">- <admin-input asp-for="PdtValidateOrderTotal" />- <div class="control__indicator"></div>- </label>- <span asp-validation-for="PdtValidateOrderTotal"></span>- </div>- </div>- <div class="form-group">- <div class="col-md-3 col-sm-3 text-right">- <admin-label asp-for="AdditionalFee" class="control-label" />- </div>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="AdditionalFee" />- <span asp-validation-for="AdditionalFee"></span>- </div>- </div>- <div class="form-group">- <div class="col-md-3 col-sm-3 text-right">- <admin-label asp-for="AdditionalFeePercentage" class="control-label" />- </div>- <div class="col-md-9 col-sm-9">- <label class="mt-checkbox mt-checkbox-outline control control-checkbox">- <admin-input asp-for="AdditionalFeePercentage" />- <div class="control__indicator"></div>- </label>- <span asp-validation-for="AdditionalFeePercentage"></span>- </div>- </div>- <div class="form-group">- <div class="col-md-3 col-sm-3 text-right">- <admin-label asp-for="PassProductNamesAndTotals" class="control-label" />- </div>- <div class="col-md-9 col-sm-9">- <label class="mt-checkbox mt-checkbox-outline control control-checkbox">- <admin-input asp-for="PassProductNamesAndTotals" />- <div class="control__indicator"></div>- </label>- <span asp-validation-for="PassProductNamesAndTotals"></span>- </div>- </div>- <div class="form-group">- <div class="col-md-3 col-sm-3 text-right">- <admin-label asp-for="DisplayOrder" class="control-label" />- </div>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="DisplayOrder" />- <span asp-validation-for="DisplayOrder"></span>- </div>- </div>- </div>- <div class="form-actions">- <div class="row">- <div class="offset-md-3 offset-sm-3 col-md-9 col-sm-9">- <input type="submit" name="save" class="btn green" value="@Loc["Admin.Common.Save"]" />- </div>- </div>- </div>- </div>-</form>diff --git a/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs b/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.csdeleted file mode 100644index 9a588f60e..000000000--- a/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs+++ /dev/null@@ -1,397 +0,0 @@-using Grand.Business.Core.Commands.Checkout.Orders;-using Grand.Business.Core.Extensions;-using Grand.Business.Core.Interfaces.Checkout.Orders;-using Grand.Business.Core.Interfaces.Checkout.Payments;-using Grand.Business.Core.Queries.Checkout.Orders;-using Grand.Domain.Orders;-using Grand.Domain.Payments;-using Grand.Infrastructure;-using Grand.SharedKernel;-using Grand.Web.Common.Controllers;-using MediatR;-using Microsoft.AspNetCore.Mvc;-using Microsoft.Extensions.Logging;-using Microsoft.Extensions.Primitives;-using Payments.PayPalStandard.Services;-using System.Globalization;--namespace Payments.PayPalStandard.Controllers-{-- public class PaymentPayPalStandardController : BasePaymentController- {- private readonly IWorkContext _workContext;- private readonly IPaymentService _paymentService;- private readonly IOrderService _orderService;- private readonly ILogger<PaymentPayPalStandardController> _logger;- private readonly IMediator _mediator;- private readonly IPaymentTransactionService _paymentTransactionService;- private readonly IPaypalHttpClient _paypalHttpClient;-- private readonly PaymentSettings _paymentSettings;- private readonly PayPalStandardPaymentSettings _payPalStandardPaymentSettings;-- public PaymentPayPalStandardController(- IWorkContext workContext,- IPaymentService paymentService,- IOrderService orderService,- ILogger<PaymentPayPalStandardController> logger,- IMediator mediator,- IPaymentTransactionService paymentTransactionService,- IPaypalHttpClient paypalHttpClient,- PayPalStandardPaymentSettings payPalStandardPaymentSettings,- PaymentSettings paymentSettings)- {- _workContext = workContext;- _paymentService = paymentService;- _orderService = orderService;- _logger = logger;- _mediator = mediator;- _paymentTransactionService = paymentTransactionService;- _paypalHttpClient = paypalHttpClient;- _payPalStandardPaymentSettings = payPalStandardPaymentSettings;- _paymentSettings = paymentSettings;- }--- private string QueryString(string name)- {- return StringValues.IsNullOrEmpty(HttpContext.Request.Query[name]) ? default : HttpContext.Request.Query[name].ToString();- }-- public async Task<IActionResult> PDTHandler()- {- var tx = QueryString("tx");-- if (_paymentService.LoadPaymentMethodBySystemName("Payments.PayPalStandard") is not PayPalStandardPaymentProvider processor ||- !processor.IsPaymentMethodActive(_paymentSettings))- throw new GrandException("PayPal Standard module cannot be loaded");-- var (status, values, _) = await _paypalHttpClient.GetPdtDetails(tx);-- if (status)- {- values.TryGetValue("custom", out var orderNumber);- Guid orderNumberGuid = Guid.Empty;- try- {- if (orderNumber != null) orderNumberGuid = new Guid(orderNumber);- }- catch- {- // ignored- }-- Order order = await _orderService.GetOrderByGuid(orderNumberGuid);- if (order != null)- {- var paymentTransaction = await _paymentTransactionService.GetOrderByGuid(orderNumberGuid);-- double mc_gross = 0;- try- {- mc_gross = double.Parse(values["mc_gross"], new CultureInfo("en-US"));- }- catch (Exception exc)- {- _logger.LogError(exc, "PayPal PDT. Error getting mc_gross");- }-- values.TryGetValue("payer_status", out var payer_status);- values.TryGetValue("payment_status", out var payment_status);- values.TryGetValue("pending_reason", out var pending_reason);- values.TryGetValue("mc_currency", out var mc_currency);- values.TryGetValue("txn_id", out var txn_id);- values.TryGetValue("payment_type", out var payment_type);- values.TryGetValue("payer_id", out var payer_id);- values.TryGetValue("receiver_id", out var receiver_id);- values.TryGetValue("invoice", out var invoice);- values.TryGetValue("payment_fee", out var payment_fee);-- var sb = new StringBuilder();- sb.AppendLine("Paypal PDT:");- sb.AppendLine("mc_gross: " + mc_gross);- sb.AppendLine("Payer status: " + payer_status);- sb.AppendLine("Payment status: " + payment_status);- sb.AppendLine("Pending reason: " + pending_reason);- sb.AppendLine("mc_currency: " + mc_currency);- sb.AppendLine("txn_id: " + txn_id);- sb.AppendLine("payment_type: " + payment_type);- sb.AppendLine("payer_id: " + payer_id);- sb.AppendLine("receiver_id: " + receiver_id);- sb.AppendLine("invoice: " + invoice);- sb.AppendLine("payment_fee: " + payment_fee);-- var newPaymentStatus = PaypalHelper.GetPaymentStatus(payment_status, pending_reason);- sb.AppendLine("New payment status: " + newPaymentStatus);-- //order note- await _orderService.InsertOrderNote(new OrderNote {- Note = sb.ToString(),- DisplayToCustomer = false,- OrderId = order.Id- });-- //load settings for a chosen store scope- //validate order total- if (_payPalStandardPaymentSettings.PdtValidateOrderTotal && !Math.Round(mc_gross, 2).Equals(Math.Round(order.OrderTotal * order.CurrencyRate, 2)))- {- var errorStr =- $"PayPal PDT. Returned order total {mc_gross} doesn't equal order total {order.OrderTotal * order.CurrencyRate}. Order# {order.OrderNumber}.";- _logger.LogError(errorStr);-- //order note- await _orderService.InsertOrderNote(new OrderNote {- Note = errorStr,- OrderId = order.Id,- DisplayToCustomer = false- });-- return RedirectToAction("Index", "Home", new { area = "" });- }-- //mark order as paid- if (newPaymentStatus == PaymentStatus.Paid)- {- if (await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransaction = paymentTransaction }))- {- paymentTransaction.AuthorizationTransactionId = txn_id;- await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);- await _mediator.Send(new MarkAsPaidCommand { PaymentTransaction = paymentTransaction });- }- }- }-- return RedirectToRoute("CheckoutCompleted", new { orderId = order.Id });- }- else- {- var custom = QueryString("custom");- Guid orderNumberGuid = Guid.Empty;- try- {- orderNumberGuid = new Guid(custom);- }- catch- {- // ignored- }-- Order order = await _orderService.GetOrderByGuid(orderNumberGuid);- if (order != null)- {- return RedirectToRoute("CheckoutCompleted", new { orderId = order.Id });- }-- return RedirectToAction("Index", "Home", new { area = "" });- }- }-- [HttpPost]- public async Task<IActionResult> IpnHandler()- {- string strRequest;- using (var stream = new StreamReader(Request.Body))- {- strRequest = await stream.ReadToEndAsync();- }- if (_paymentService.LoadPaymentMethodBySystemName("Payments.PayPalStandard") is not PayPalStandardPaymentProvider processor ||- !processor.IsPaymentMethodActive(_paymentSettings))- throw new GrandException("PayPal Standard module cannot be loaded");-- var (success, values) = await _paypalHttpClient.VerifyIpn(strRequest);-- if (success)- {- #region values- double mcGross = 0;- try- {- mcGross = double.Parse(values["mc_gross"], new CultureInfo("en-US"));- }- catch- {- // ignored- }-- values.TryGetValue("payment_status", out var paymentStatus);- values.TryGetValue("pending_reason", out var pendingReason);- values.TryGetValue("txn_id", value: out var txnId);- values.TryGetValue("txn_type", out var txnType);-- #endregion-- var sb = new StringBuilder();- sb.AppendLine("Paypal IPN:");- foreach (KeyValuePair<string, string> kvp in values)- {- sb.AppendLine(kvp.Key + ": " + kvp.Value);- }-- var newPaymentStatus = PaypalHelper.GetPaymentStatus(paymentStatus, pendingReason);- sb.AppendLine("New payment status: " + newPaymentStatus);-- switch (txnType)- {- case "recurring_payment_profile_created":- //do nothing here- break;- case "recurring_payment":- //do nothing here- break;- default:- #region Standard payment- {- values.TryGetValue("custom", out var orderNumber);- Guid orderNumberGuid = Guid.Empty;- try- {- if (orderNumber != null) orderNumberGuid = Guid.Parse(orderNumber);- }- catch- {- // ignored- }-- var order = orderNumberGuid != Guid.Empty ? await _orderService.GetOrderByGuid(orderNumberGuid) : null;- if (order != null)- {- //order note- await _orderService.InsertOrderNote(new OrderNote {- Note = sb.ToString(),- DisplayToCustomer = false,- OrderId = order.Id- });- var paymentTransaction = await _paymentTransactionService.GetOrderByGuid(order.OrderGuid);-- switch (newPaymentStatus)- {- case PaymentStatus.Authorized:- {- //validate order total- if (Math.Round(mcGross, 2).Equals(Math.Round(order.OrderTotal, 2)))- {- //valid- if (await _mediator.Send(new CanMarkPaymentTransactionAsAuthorizedQuery { PaymentTransaction = paymentTransaction }))- {- await _mediator.Send(new MarkAsAuthorizedCommand { PaymentTransaction = paymentTransaction });- }- }- else- {- //not valid- var errorStr =- $"PayPal IPN. Returned order total {mcGross} doesn't equal order total {order.OrderTotal * order.CurrencyRate}. Order# {order.Id}.";- //log- _logger.LogError(errorStr);- //order note- await _orderService.InsertOrderNote(new OrderNote {- Note = errorStr,- DisplayToCustomer = false,- OrderId = order.Id- });- }- }- break;- case PaymentStatus.Paid:- {- //validate order total- if (Math.Round(mcGross, 2).Equals(Math.Round(order.OrderTotal, 2)))- {- //valid- if (await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransaction = paymentTransaction }))- {- paymentTransaction.AuthorizationTransactionId = txnId;- await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);-- await _mediator.Send(new MarkAsPaidCommand { PaymentTransaction = paymentTransaction });- }- }- else- {- //not valid- var errorStr =- $"PayPal IPN. Returned order total {mcGross} doesn't equal order total {order.OrderTotal * order.CurrencyRate}. Order# {order.Id}.";- //log- _logger.LogError(errorStr);- //order note- await _orderService.InsertOrderNote(new OrderNote {- Note = errorStr,- DisplayToCustomer = false,- OrderId = order.Id- });- }- }- break;- case PaymentStatus.Refunded:- {- var totalToRefund = Math.Abs(mcGross);- if (totalToRefund > 0 && Math.Round(totalToRefund, 2).Equals(Math.Round(order.OrderTotal, 2)))- {- //refund- if (await _mediator.Send(new CanRefundOfflineQuery { PaymentTransaction = paymentTransaction }))- {- await _mediator.Send(new RefundOfflineCommand { PaymentTransaction = paymentTransaction });- }- }- else- {- //partial refund- if (await _mediator.Send(new CanPartiallyRefundOfflineQuery { PaymentTransaction = paymentTransaction, AmountToRefund = totalToRefund }))- {- await _mediator.Send(new PartiallyRefundOfflineCommand { PaymentTransaction = paymentTransaction, AmountToRefund = totalToRefund });- }- }- }- break;- case PaymentStatus.Voided:- {- if (await _mediator.Send(new CanVoidOfflineQuery { PaymentTransaction = paymentTransaction }))- {- await _mediator.Send(new VoidOfflineCommand { PaymentTransaction = paymentTransaction });- }- }- break;- case PaymentStatus.Pending:- break;- case PaymentStatus.PartiallyPaid:- break;- case PaymentStatus.PartiallyRefunded:- break;- case PaymentStatus.PendingRefunded:- break;- default:- throw new ArgumentOutOfRangeException();- }- }- else- {- _logger.LogError(new GrandException(sb.ToString()), "PayPal IPN. Order is not found");- }- }- #endregion- break;- }- return Ok();-- }-- _logger.LogError(new GrandException(strRequest), "PayPal IPN failed");-- return BadRequest();-- }-- public async Task<IActionResult> CancelOrder()- {- var order = (await _orderService.SearchOrders(storeId: _workContext.CurrentStore.Id,- customerId: _workContext.CurrentCustomer.Id, pageSize: 1)).FirstOrDefault();- return order != null ? RedirectToRoute("OrderDetails", new { orderId = order.Id }) : RedirectToRoute("HomePage");- }-- public IActionResult PaymentInfo()- {- return View();- }- }-}\ No newline at end of filediff --git a/src/Plugins/Payments.PayPalStandard/EndpointProvider.cs b/src/Plugins/Payments.PayPalStandard/EndpointProvider.csdeleted file mode 100644index a9fd8db19..000000000--- a/src/Plugins/Payments.PayPalStandard/EndpointProvider.cs+++ /dev/null@@ -1,36 +0,0 @@-using Grand.Infrastructure.Endpoints;-using Microsoft.AspNetCore.Builder;-using Microsoft.AspNetCore.Routing;--namespace Payments.PayPalStandard-{- public class EndpointProvider : IEndpointProvider- {- public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)- {- //PaymentInfo- endpointRouteBuilder.MapControllerRoute("Plugin.PayPalStandard",- "Plugins/PaymentPayPalStandard/PaymentInfo",- new { controller = "PaymentPayPalStandard", action = "PaymentInfo", area = "" }- );-- //PDT- endpointRouteBuilder.MapControllerRoute("Plugin.Payments.PayPalStandard.PDTHandler",- "Plugins/PaymentPayPalStandard/PDTHandler",- new { controller = "PaymentPayPalStandard", action = "PDTHandler" }- );- //IPN- endpointRouteBuilder.MapControllerRoute("Plugin.Payments.PayPalStandard.IPNHandler",- "Plugins/PaymentPayPalStandard/IPNHandler",- new { controller = "PaymentPayPalStandard", action = "IpnHandler" }- );- //Cancel- endpointRouteBuilder.MapControllerRoute("Plugin.Payments.PayPalStandard.CancelOrder",- "Plugins/PaymentPayPalStandard/CancelOrder",- new { controller = "PaymentPayPalStandard", action = "CancelOrder" }- );- }- public int Priority => 0;-- }-}diff --git a/src/Plugins/Payments.PayPalStandard/Manifest.cs b/src/Plugins/Payments.PayPalStandard/Manifest.csdeleted file mode 100644index 94d99b8ed..000000000--- a/src/Plugins/Payments.PayPalStandard/Manifest.cs+++ /dev/null@@ -1,10 +0,0 @@-using Grand.Infrastructure.Plugins;-using Payments.PayPalStandard;--[assembly: PluginInfo(- FriendlyName = "PayPal Standard",- Group = "Payment methods",- SystemName = PayPalStandardPaymentDefaults.ProviderSystemName,- Author = "grandnode team",- Version = "2.1.1"-)]\ No newline at end of filediff --git a/src/Plugins/Payments.PayPalStandard/Models/ConfigurationModel.cs b/src/Plugins/Payments.PayPalStandard/Models/ConfigurationModel.csdeleted file mode 100644index ef260e5ad..000000000--- a/src/Plugins/Payments.PayPalStandard/Models/ConfigurationModel.cs+++ /dev/null@@ -1,37 +0,0 @@-using Grand.Infrastructure.ModelBinding;-using Grand.Infrastructure.Models;--namespace Payments.PayPalStandard.Models-{- public class ConfigurationModel : BaseModel- {- public string StoreScope { get; set; }-- [GrandResourceDisplayName("Plugins.Payments.PayPalStandard.Fields.UseSandbox")]- public bool UseSandbox { get; set; }-- [GrandResourceDisplayName("Plugins.Payments.PayPalStandard.Fields.BusinessEmail")]- public string BusinessEmail { get; set; }-- [GrandResourceDisplayName("Plugins.Payments.PayPalStandard.Fields.PDTToken")]- public string PdtToken { get; set; }-- [GrandResourceDisplayName("Plugins.Payments.PayPalStandard.Fields.PDTValidateOrderTotal")]- public bool PdtValidateOrderTotal { get; set; }-- [GrandResourceDisplayName("Plugins.Payments.PayPalStandard.Fields.AdditionalFee")]- public double AdditionalFee { get; set; }-- [GrandResourceDisplayName("Plugins.Payments.PayPalStandard.Fields.AdditionalFeePercentage")]- public bool AdditionalFeePercentage { get; set; }-- [GrandResourceDisplayName("Plugins.Payments.PayPalStandard.Fields.PassProductNamesAndTotals")]- public bool PassProductNamesAndTotals { get; set; }-- [GrandResourceDisplayName("Plugins.Payments.PayPalStandard.Fields.DisplayOrder")]- public int DisplayOrder { get; set; }---- }-}\ No newline at end of filediff --git a/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentDefaults.cs b/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentDefaults.csdeleted file mode 100644index 8f5f9385f..000000000--- a/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentDefaults.cs+++ /dev/null@@ -1,9 +0,0 @@-namespace Payments.PayPalStandard-{- public static class PayPalStandardPaymentDefaults- {- public const string ProviderSystemName = "Payments.PayPalStandard";- public const string FriendlyName = "Payments.PayPalStandard.FriendlyName";- public const string ConfigurationUrl = "/Admin/PayPalStandard/Configure";- }-}diff --git a/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentPlugin.cs b/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentPlugin.csdeleted file mode 100644index 156d864e2..000000000--- a/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentPlugin.cs+++ /dev/null@@ -1,113 +0,0 @@-using Grand.Business.Core.Extensions;-using Grand.Business.Core.Interfaces.Common.Configuration;-using Grand.Business.Core.Interfaces.Common.Localization;-using Grand.Infrastructure.Plugins;--namespace Payments.PayPalStandard-{- /// <summary>- /// PayPalStandard payment processor- /// </summary>- public class PayPalStandardPaymentPlugin : BasePlugin, IPlugin- {- #region Fields-- private readonly ITranslationService _translationService;- private readonly ILanguageService _languageService;- private readonly ISettingService _settingService;-- #endregion-- #region Ctor-- public PayPalStandardPaymentPlugin(- ITranslationService translationService,- ILanguageService languageService,- ISettingService settingService)- {- _translationService = translationService;- _languageService = languageService;- _settingService = settingService;- }-- #endregion-- #region Methods-- /// <summary>- /// Gets a configuration page URL- /// </summary>- public override string ConfigurationUrl()- {- return PayPalStandardPaymentDefaults.ConfigurationUrl;- }-- /// <summary>- /// Install the plugin- /// </summary>- public override async Task Install()- {- //settings- await _settingService.SaveSetting(new PayPalStandardPaymentSettings- {- UseSandbox = true- });-- //locales- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Payments.PayPalStandard.FriendlyName", "PayPal Standard");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.AdditionalFee", "Additional fee");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.AdditionalFee.Hint", "Enter additional fee to charge your customers.");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.AdditionalFeePercentage", "Additional fee. Use percentage");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.AdditionalFeePercentage.Hint", "Determines whether to apply a percentage additional fee to the order total. If not enabled, a fixed value is used.");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.BusinessEmail", "Business Email");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.BusinessEmail.Hint", "Specify your PayPal business email.");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.PassProductNamesAndTotals", "Pass product names and order totals to PayPal");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.PassProductNamesAndTotals.Hint", "Check if product names and order totals should be passed to PayPal.");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.PDTToken", "PDT Identity Token");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.PDTValidateOrderTotal", "PDT. Validate order total");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.PDTValidateOrderTotal.Hint", "Check if PDT handler should validate order totals.");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.RedirectionTip", "You will be redirected to PayPal site to complete the order.");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.UseSandbox", "Use Sandbox");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.UseSandbox.Hint", "Check to enable Sandbox (testing environment).");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Instructions", "<p><b>If you're using this gateway ensure that your primary store currency is supported by PayPal.</b><br /><br />To use PDT, you must activate PDT and Auto Return in your PayPal account profile. You must also acquire a PDT identity token, which is used in all PDT communication you send to PayPal. Follow these steps to configure your account for PDT:<br /><br />1. Log in to your PayPal account (click <a href=\"https://www.paypal.com/us/webapps/mpp/referral/paypal-business-account2?partner_id=9JJPJNNPQ7PZ8\" target=\"_blank\">here</a> to create your account).<br />2. Click the Profile subtab.<br />3. Click Website Payment Preferences in the Seller Preferences column.<br />4. Under Auto Return for Website Payments, click the On radio button.<br />5. For the Return URL, enter the URL on your site that will receive the transaction ID posted by PayPal after a customer payment ({0}).<br />6. Under Payment Data Transfer, click the On radio button.<br />7. Click Save.<br />8. Click Website Payment Preferences in the Seller Preferences column.<br />9. Scroll down to the Payment Data Transfer section of the page to view your PDT identity token.<br /><br /></p>");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.PaymentMethodDescription", "You will be redirected to PayPal site to complete the payment");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.RoundingWarning", "It looks like you have \"ShoppingCartSettings.RoundPricesDuringCalculation\" setting disabled. Keep in mind that this can lead to a discrepancy of the order total amount, as PayPal only rounds to two doubles.");- await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.DisplayOrder", "Display order");--- await base.Install();- }-- /// <summary>- /// Uninstall the plugin- /// </summary>- public override async Task Uninstall()- {- //settings- await _settingService.DeleteSetting<PayPalStandardPaymentSettings>();-- //locales- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.AdditionalFee");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.AdditionalFee.Hint");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.AdditionalFeePercentage");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.AdditionalFeePercentage.Hint");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.BusinessEmail");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.BusinessEmail.Hint");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.PassProductNamesAndTotals");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.PassProductNamesAndTotals.Hint");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.PDTToken");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.PDTToken.Hint");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.RedirectionTip");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.UseSandbox");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Fields.UseSandbox.Hint");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.Instructions");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.PaymentMethodDescription");- await this.DeletePluginTranslationResource(_translationService, _languageService, "Plugins.Payments.PayPalStandard.RoundingWarning");-- await base.Uninstall();- }-- #endregion-- }-}\ No newline at end of filediff --git a/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentProvider.cs b/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentProvider.csdeleted file mode 100644index 323dd40bd..000000000--- a/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentProvider.cs+++ /dev/null@@ -1,541 +0,0 @@-using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Interfaces.Catalog.Tax;-using Grand.Business.Core.Enums.Checkout;-using Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes;-using Grand.Business.Core.Interfaces.Checkout.Orders;-using Grand.Business.Core.Interfaces.Checkout.Payments;-using Grand.Business.Core.Utilities.Checkout;-using Grand.Business.Core.Interfaces.Common.Directory;-using Grand.Business.Core.Interfaces.Common.Localization;-using Grand.Business.Core.Interfaces.Customers;-using Grand.Domain.Orders;-using Grand.Domain.Payments;-using Grand.Domain.Shipping;-using Grand.Infrastructure;-using Microsoft.AspNetCore.Http;-using Microsoft.AspNetCore.WebUtilities;-using Microsoft.Extensions.DependencyInjection;-using System.Globalization;--namespace Payments.PayPalStandard-{- public class PayPalStandardPaymentProvider : IPaymentProvider- {-- private readonly ITranslationService _translationService;- private readonly PayPalStandardPaymentSettings _paypalStandardPaymentSettings;-- private readonly ICheckoutAttributeParser _checkoutAttributeParser;- private readonly IUserFieldService _userFieldService;- private readonly IHttpContextAccessor _httpContextAccessor;- private readonly ITaxService _taxService;- private readonly IProductService _productService;- private readonly IWorkContext _workContext;- private readonly IOrderService _orderService;- private readonly ICountryService _countryService;- private readonly ICurrencyService _currencyService;- #region Ctor-- public PayPalStandardPaymentProvider(- ICheckoutAttributeParser checkoutAttributeParser,- IUserFieldService userFieldService,- IHttpContextAccessor httpContextAccessor,- ITranslationService translationService,- ITaxService taxService,- IProductService productService,- IWorkContext workContext,- IOrderService orderService,- ICountryService countryService,- ICurrencyService currencyService,- PayPalStandardPaymentSettings paypalStandardPaymentSettings)- {- _checkoutAttributeParser = checkoutAttributeParser;- _userFieldService = userFieldService;- _httpContextAccessor = httpContextAccessor;- _translationService = translationService;- _taxService = taxService;- _productService = productService;- _workContext = workContext;- _orderService = orderService;- _countryService = countryService;- _currencyService = currencyService;- _paypalStandardPaymentSettings = paypalStandardPaymentSettings;- }-- #endregion-- public string ConfigurationUrl => PayPalStandardPaymentDefaults.ConfigurationUrl;-- public string SystemName => PayPalStandardPaymentDefaults.ProviderSystemName;-- public string FriendlyName => _translationService.GetResource(PayPalStandardPaymentDefaults.FriendlyName);-- public int Priority => _paypalStandardPaymentSettings.DisplayOrder;-- public IList<string> LimitedToStores => new List<string>();-- public IList<string> LimitedToGroups => new List<string>();--- #region Utilities-- /// <summary>- /// Gets PayPal URL- /// </summary>- /// <returns></returns>- private string GetPaypalUrl()- {- return _paypalStandardPaymentSettings.UseSandbox ?- PaypalHelper.PayPalUrlSandbox :- PaypalHelper.PayPalUrl;- }-- /// <summary>- /// Create common query parameters for the request- /// </summary>- /// <param name="order"></param>- /// <returns>Created query parameters</returns>- private async Task<IDictionary<string, string>> CreateQueryParameters(Order order)- {- //get store location- var storeLocation = _workContext.CurrentHost.Url.TrimEnd('/');- var stateProvince = "";- var countryCode = "";- if (!string.IsNullOrEmpty(order.ShippingAddress?.StateProvinceId))- {- var country = await _countryService.GetCountryById(order.ShippingAddress?.CountryId);- var state = country?.StateProvinces.FirstOrDefault(x => x.Id == order.ShippingAddress?.StateProvinceId);- if (state != null)- stateProvince = state.Abbreviation;- }- if (!string.IsNullOrEmpty(order.ShippingAddress?.CountryId))- {- var country = await _countryService.GetCountryById(order.ShippingAddress?.CountryId);- if (country != null)- countryCode = country.TwoLetterIsoCode;- }--- //create query parameters- return new Dictionary<string, string>- {- //PayPal ID or an email address associated with your PayPal account- ["business"] = _paypalStandardPaymentSettings.BusinessEmail,-- //the character set and character encoding- ["charset"] = "utf-8",-- //set return method to "2" (the customer redirected to the return URL by using the POST method, and all payment variables are included)- ["rm"] = "2",-- ["currency_code"] = order.CustomerCurrencyCode,-- //order identifier- ["invoice"] = order.OrderNumber.ToString(),- ["custom"] = order.OrderGuid.ToString(),-- //PDT, IPN and cancel URL- ["return"] = $"{storeLocation}/Plugins/PaymentPayPalStandard/PDTHandler?custom={order.OrderGuid}",- ["notify_url"] = $"{storeLocation}/Plugins/PaymentPayPalStandard/IPNHandler",- ["cancel_return"] = $"{storeLocation}/Plugins/PaymentPayPalStandard/CancelOrder",-- //shipping address, if exists- ["no_shipping"] = order.ShippingStatusId == ShippingStatus.ShippingNotRequired ? "1" : "2",- ["address_override"] = order.ShippingStatusId == ShippingStatus.ShippingNotRequired ? "0" : "1",- ["first_name"] = order.ShippingAddress?.FirstName,- ["last_name"] = order.ShippingAddress?.LastName,- ["address1"] = order.ShippingAddress?.Address1,- ["address2"] = order.ShippingAddress?.Address2,- ["city"] = order.ShippingAddress?.City,-- ["state"] = stateProvince,- ["country"] = countryCode,- ["zip"] = order.ShippingAddress?.ZipPostalCode,- ["email"] = order.ShippingAddress?.Email- };- }-- /// <summary>- /// Add order items to the request query parameters- /// </summary>- /// <param name="parameters">Query parameters</param>- /// <param name="order"></param>- private async Task AddItemsParameters(IDictionary<string, string> parameters, Order order)- {- //upload order items- parameters.Add("cmd", "_cart");- parameters.Add("upload", "1");-- double cartTotal = 0;- double roundedCartTotal = 0;- var itemCount = 1;-- //add shopping cart items- foreach (var item in order.OrderItems)- {- var product = await _productService.GetProductById(item.ProductId);-- var roundedItemPrice = Math.Round(item.UnitPriceExclTax, 2);-- //add query parameters- parameters.Add($"item_name_{itemCount}", product.Name);- parameters.Add($"amount_{itemCount}", roundedItemPrice.ToString("0.00", CultureInfo.InvariantCulture));- parameters.Add($"quantity_{itemCount}", item.Quantity.ToString());-- cartTotal += item.PriceExclTax;- roundedCartTotal += roundedItemPrice * item.Quantity;- itemCount++;- }-- //add checkout attributes as order items- var checkoutAttributeValues = await _checkoutAttributeParser.ParseCheckoutAttributeValue(order.CheckoutAttributes);- foreach (var attributeValue in checkoutAttributeValues)- {- var attributePrice = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, false, _workContext.CurrentCustomer);- if (attributePrice.checkoutPrice > 0)- {- var roundedAttributePrice = Math.Round(await _currencyService.ConvertFromPrimaryStoreCurrency(attributePrice.checkoutPrice, _workContext.WorkingCurrency), 2);- //add query parameters- if (attributeValue.ca != null)- {- parameters.Add($"item_name_{itemCount}", attributeValue.ca.Name);- parameters.Add($"amount_{itemCount}", roundedAttributePrice.ToString("0.00", CultureInfo.InvariantCulture));- parameters.Add($"quantity_{itemCount}", "1");-- cartTotal += attributePrice.checkoutPrice;- roundedCartTotal += roundedAttributePrice;- itemCount++;- }- }- }-- //add shipping fee as a separate order item, if it has price- var roundedShippingPrice = Math.Round(order.OrderShippingExclTax, 2);- if (roundedShippingPrice > 0)- {- parameters.Add($"item_name_{itemCount}", "Shipping fee");- parameters.Add($"amount_{itemCount}", roundedShippingPrice.ToString("0.00", CultureInfo.InvariantCulture));- parameters.Add($"quantity_{itemCount}", "1");-- cartTotal += order.OrderShippingExclTax;- roundedCartTotal += roundedShippingPrice;- itemCount++;- }-- //add payment method additional fee as a separate order item, if it has price- var roundedPaymentMethodPrice = Math.Round(order.PaymentMethodAdditionalFeeExclTax, 2);- if (roundedPaymentMethodPrice > 0)- {- parameters.Add($"item_name_{itemCount}", "Payment method fee");- parameters.Add($"amount_{itemCount}", roundedPaymentMethodPrice.ToString("0.00", CultureInfo.InvariantCulture));- parameters.Add($"quantity_{itemCount}", "1");-- cartTotal += order.PaymentMethodAdditionalFeeExclTax;- roundedCartTotal += roundedPaymentMethodPrice;- itemCount++;- }-- //add tax as a separate order item, if it has positive amount- var roundedTaxAmount = Math.Round(order.OrderTax, 2);- if (roundedTaxAmount > 0)- {- parameters.Add($"item_name_{itemCount}", "Tax amount");- parameters.Add($"amount_{itemCount}", roundedTaxAmount.ToString("0.00", CultureInfo.InvariantCulture));- parameters.Add($"quantity_{itemCount}", "1");-- cartTotal += order.OrderTax;- roundedCartTotal += roundedTaxAmount;- }-- if (cartTotal > order.OrderTotal)- {- //get the difference between what the order total is and what it should be and use that as the "discount"- var discountTotal = Math.Round(cartTotal - order.OrderTotal, 2);- roundedCartTotal -= discountTotal;-- //gift voucher or loyalty points amount applied to cart in nopCommerce - shows in PayPal as "discount"- parameters.Add("discount_amount_cart", discountTotal.ToString("0.00", CultureInfo.InvariantCulture));- }-- //save order total that actually sent to PayPal (used for PDT order total validation)- await _userFieldService.SaveField(order, PaypalHelper.OrderTotalSentToPayPal, roundedCartTotal);- }-- /// <summary>- /// Add order total to the request query parameters- /// </summary>- /// <param name="parameters">Query parameters</param>- /// <param name="order"></param>- private async Task AddOrderTotalParameters(IDictionary<string, string> parameters, Order order)- {- //round order total- var roundedOrderTotal = Math.Round(order.OrderTotal, 2);-- parameters.Add("cmd", "_xclick");- parameters.Add("item_name", $"Order Number {order.OrderNumber}");- parameters.Add("amount", roundedOrderTotal.ToString("0.00", CultureInfo.InvariantCulture));-- //save order total that actually sent to PayPal (used for PDT order total validation)- await _userFieldService.SaveField(order, PaypalHelper.OrderTotalSentToPayPal, roundedOrderTotal);- }-- #endregion-- #region Properties-- /// <summary>- /// Init a process a payment transaction- /// </summary>- /// <returns>Payment transaction</returns>- public async Task<PaymentTransaction> InitPaymentTransaction()- {- return await Task.FromResult<PaymentTransaction>(null);- }-- /// <summary>- /// Process a payment- /// </summary>- /// <param name="paymentTransaction"></param>- /// <returns>Process payment result</returns>- public async Task<ProcessPaymentResult> ProcessPayment(PaymentTransaction paymentTransaction)- {- var result = new ProcessPaymentResult();- return await Task.FromResult(result);- }- public Task PostProcessPayment(PaymentTransaction paymentTransaction)- {- //nothing- return Task.CompletedTask;- }-- /// <summary>- /// Post process payment (used by payment gateways that require redirecting to a third-party URL)- /// </summary>- /// <param name="paymentTransaction"></param>- public async Task PostRedirectPayment(PaymentTransaction paymentTransaction)- {- var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- //create common query parameters for the request- var queryParameters = await CreateQueryParameters(order);-- //whether to include order items in a transaction- if (_paypalStandardPaymentSettings.PassProductNamesAndTotals)- {- //add order items query parameters to the request- var parameters = new Dictionary<string, string>(queryParameters);- await AddItemsParameters(parameters, order);-- //remove null values from parameters- parameters = parameters.Where(parameter => !string.IsNullOrEmpty(parameter.Value))- .ToDictionary(parameter => parameter.Key, parameter => parameter.Value);-- //ensure redirect URL doesn't exceed 2K chars to avoid "too long URL" exception- var redirectUrl = QueryHelpers.AddQueryString(GetPaypalUrl(), parameters);- if (redirectUrl.Length <= 2048)- {- _httpContextAccessor.HttpContext?.Response.Redirect(redirectUrl);- return;- }- }-- //or add only an order total query parameters to the request- await AddOrderTotalParameters(queryParameters, order);-- //remove null values from parameters- queryParameters = queryParameters.Where(parameter => !string.IsNullOrEmpty(parameter.Value))- .ToDictionary(parameter => parameter.Key, parameter => parameter.Value);-- var url = QueryHelpers.AddQueryString(GetPaypalUrl(), queryParameters);- _httpContextAccessor.HttpContext?.Response.Redirect(url);- }-- /// <summary>- /// Returns a value indicating whether payment method should be hidden during checkout- /// </summary>- /// <param name="cart">Shopping cart</param>- /// <returns>true - hide; false - display.</returns>- public async Task<bool> HidePaymentMethod(IList<ShoppingCartItem> cart)- {- //you can put any logic here- //for example, hide this payment method if all products in the cart are downloadable- //or hide this payment method if current customer is from certain country- return await Task.FromResult(false);- }-- /// <summary>- /// Gets additional handling fee- /// </summary>- /// <param name="cart">Shopping cart</param>- /// <returns>Additional handling fee</returns>- public async Task<double> GetAdditionalHandlingFee(IList<ShoppingCartItem> cart)- {- if (_paypalStandardPaymentSettings.AdditionalFee <= 0)- return _paypalStandardPaymentSettings.AdditionalFee;-- double result;- if (_paypalStandardPaymentSettings.AdditionalFeePercentage)- {- //percentage- var orderTotalCalculationService = _httpContextAccessor.HttpContext!.RequestServices.GetRequiredService<IOrderCalculationService>();- var subtotal = await orderTotalCalculationService.GetShoppingCartSubTotal(cart, true);- result = (float)subtotal.subTotalWithDiscount * (float)_paypalStandardPaymentSettings.AdditionalFee / 100f;- }- else- {- //fixed value- result = _paypalStandardPaymentSettings.AdditionalFee;- }-- if (!(result > 0)) return await Task.FromResult(result);- result = await _currencyService.ConvertFromPrimaryStoreCurrency(result, _workContext.WorkingCurrency);- //return result;- return await Task.FromResult(result);- }-- /// <summary>- /// Captures payment- /// </summary>- /// <returns>Capture payment result</returns>- public async Task<CapturePaymentResult> Capture(PaymentTransaction paymentTransaction)- {- var result = new CapturePaymentResult();- result.AddError("Capture method not supported");- return await Task.FromResult(result);- }-- /// <summary>- /// Refunds a payment- /// </summary>- /// <param name="refundPaymentRequest">Request</param>- /// <returns>Result</returns>- public async Task<RefundPaymentResult> Refund(RefundPaymentRequest refundPaymentRequest)- {- var result = new RefundPaymentResult();- result.AddError("Refund method not supported");- return await Task.FromResult(result);- }-- /// <summary>- /// Voids a payment- /// </summary>- /// <returns>Result</returns>- public async Task<VoidPaymentResult> Void(PaymentTransaction paymentTransaction)- {- var result = new VoidPaymentResult();- result.AddError("Void method not supported");- return await Task.FromResult(result);- }-- /// <summary>- /// Cancel a payment- /// </summary>- /// <returns>Result</returns>- public Task CancelPayment(PaymentTransaction paymentTransaction)- {- return Task.CompletedTask;- }--- /// <summary>- /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)- /// </summary>- /// <returns>Result</returns>- public async Task<bool> CanRePostRedirectPayment(PaymentTransaction paymentTransaction)- {- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(paymentTransaction));-- //ensure that at least 5 seconds passed after order is placed- //P.S. there's no any particular reason for that. we just do it- if ((DateTime.UtcNow - paymentTransaction.CreatedOnUtc).TotalSeconds < 15)- return false;-- return await Task.FromResult(true);- }-- /// <summary>- /// Validate payment form- /// </summary>- /// <param name="model"></param>- /// <returns>List of validating errors</returns>- public async Task<IList<string>> ValidatePaymentForm(IDictionary<string, string> model)- {- return await Task.FromResult(new List<string>());- }-- /// <summary>- /// Get payment information- /// </summary>- /// <param name="model"></param>- /// <returns>Payment info holder</returns>- public async Task<PaymentTransaction> SavePaymentInfo(IDictionary<string, string> model)- {- return await Task.FromResult<PaymentTransaction>(null);- }--- /// <summary>- /// Gets a value indicating whether capture is supported- /// </summary>- public async Task<bool> SupportCapture()- {- return await Task.FromResult(false);- }-- /// <summary>- /// Gets a value indicating whether partial refund is supported- /// </summary>- public async Task<bool> SupportPartiallyRefund()- {- return await Task.FromResult(false);- }-- /// <summary>- /// Gets a value indicating whether refund is supported- /// </summary>- public async Task<bool> SupportRefund()- {- return await Task.FromResult(false);- }-- /// <summary>- /// Gets a value indicating whether void is supported- /// </summary>- public async Task<bool> SupportVoid()- {- return await Task.FromResult(false);- }-- /// <summary>- /// Gets a payment method type- /// </summary>- public PaymentMethodType PaymentMethodType => PaymentMethodType.Redirection;-- /// <summary>- /// Gets a value indicating whether we should display a payment information page for this plugin- /// </summary>- public async Task<bool> SkipPaymentInfo()- {- return await Task.FromResult(false);- }-- /// <summary>- /// Gets a payment method description that will be displayed on checkout pages in the public store- /// </summary>- public async Task<string> Description()- {- //return description of this payment method to be display on "payment method" checkout step. good practice is to make it localizable- //for example, for a redirection payment method, description may be like this: "You will be redirected to PayPal site to complete the payment"- return await Task.FromResult(_translationService.GetResource("Plugins.Payments.PayPalStandard.PaymentMethodDescription"));- }-- public Task<string> GetControllerRouteName()- {- return Task.FromResult("Plugin.PayPalStandard");- }-- public string LogoURL => "/Plugins/Payments.PayPalStandard/logo.jpg";-- #endregion- }-}diff --git a/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentSettings.cs b/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentSettings.csdeleted file mode 100644index 22d970173..000000000--- a/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentSettings.cs+++ /dev/null@@ -1,24 +0,0 @@-using Grand.Domain.Configuration;--namespace Payments.PayPalStandard-{- public class PayPalStandardPaymentSettings : ISettings- {- public bool UseSandbox { get; set; }- public string BusinessEmail { get; set; }- public string PdtToken { get; set; }- /// <summary>- /// Gets or sets a value indicating whether to "additional fee" is specified as percentage. true - percentage, false - fixed value.- /// </summary>- public bool AdditionalFeePercentage { get; set; }- /// <summary>- /// Additional fee- /// </summary>- public double AdditionalFee { get; set; }- public bool PassProductNamesAndTotals { get; set; }- public bool PdtValidateOrderTotal { get; set; }-- public int DisplayOrder { get; set; }-- }-}diff --git a/src/Plugins/Payments.PayPalStandard/Payments.PayPalStandard.csproj b/src/Plugins/Payments.PayPalStandard/Payments.PayPalStandard.csprojdeleted file mode 100644index f0aefc380..000000000--- a/src/Plugins/Payments.PayPalStandard/Payments.PayPalStandard.csproj+++ /dev/null@@ -1,51 +0,0 @@-<Project Sdk="Microsoft.NET.Sdk.Razor">- <Import Project="..\..\Build\Grand.Common.props" />- <PropertyGroup>- <AddRazorSupportForMvc>true</AddRazorSupportForMvc>- </PropertyGroup>-- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">- <OutputPath>..\..\Web\Grand.Web\Plugins\Payments.PayPalStandard\</OutputPath>- <OutDir>$(OutputPath)</OutDir>- </PropertyGroup>-- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">- <OutputPath>..\..\Web\Grand.Web\Plugins\Payments.PayPalStandard\</OutputPath>- <OutDir>$(OutputPath)</OutDir>- </PropertyGroup>-- <Target Name="PostBuild" AfterTargets="PostBuildEvent">- <RemoveDir Directories="..\..\Web\Grand.Web\Plugins\Payments.PayPalStandard\refs" />- <RemoveDir Directories="..\..\Web\Grand.Web\Plugins\Payments.PayPalStandard\ref" />- </Target>-- <ItemGroup>- <ProjectReference Include="..\..\Core\Grand.Data\Grand.Data.csproj">- <Private>false</Private>- </ProjectReference>- <ProjectReference Include="..\..\Business\Grand.Business.Core\Grand.Business.Core.csproj">- <Private>false</Private>- </ProjectReference>- <ProjectReference Include="..\..\Core\Grand.Domain\Grand.Domain.csproj">- <Private>false</Private>- </ProjectReference>- <ProjectReference Include="..\..\Core\Grand.Infrastructure\Grand.Infrastructure.csproj">- <Private>false</Private>- </ProjectReference>- <ProjectReference Include="..\..\Core\Grand.SharedKernel\Grand.SharedKernel.csproj">- <Private>false</Private>- </ProjectReference>- <ProjectReference Include="..\..\Web\Grand.Web.Common\Grand.Web.Common.csproj">- <Private>false</Private>- <ExcludeAssets>all</ExcludeAssets>- </ProjectReference>- </ItemGroup>--- <ItemGroup>- <None Update="logo.jpg">- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>- </None>- </ItemGroup>--</Project>\ No newline at end of filediff --git a/src/Plugins/Payments.PayPalStandard/PaypalHelper.cs b/src/Plugins/Payments.PayPalStandard/PaypalHelper.csdeleted file mode 100644index 54c20163f..000000000--- a/src/Plugins/Payments.PayPalStandard/PaypalHelper.cs+++ /dev/null@@ -1,57 +0,0 @@-using Grand.Domain.Payments;--namespace Payments.PayPalStandard-{- /// <summary>- /// Represents paypal helper- /// </summary>- public static class PaypalHelper- {- public static string OrderTotalSentToPayPal => "OrderTotalSentToPayPal";-- public static string PayPalUrlSandbox => "https://www.sandbox.paypal.com/us/cgi-bin/webscr";- public static string PayPalUrl => "https://www.paypal.com/us/cgi-bin/webscr";-- /// <summary>- /// Gets a payment status- /// </summary>- /// <param name="paymentStatus">PayPal payment status</param>- /// <param name="pendingReason">PayPal pending reason</param>- /// <returns>Payment status</returns>- public static PaymentStatus GetPaymentStatus(string paymentStatus, string pendingReason)- {- var result = PaymentStatus.Pending;-- paymentStatus ??= string.Empty;-- pendingReason ??= string.Empty;-- switch (paymentStatus.ToLowerInvariant())- {- case "pending":- result = pendingReason.ToLowerInvariant() switch {- "authorization" => PaymentStatus.Authorized,- _ => PaymentStatus.Pending- };- break;- case "processed":- case "completed":- case "canceled_reversal":- result = PaymentStatus.Paid;- break;- case "denied":- case "expired":- case "failed":- case "voided":- result = PaymentStatus.Voided;- break;- case "refunded":- case "reversed":- result = PaymentStatus.Refunded;- break;- }- return result;- }- }-}-diff --git a/src/Plugins/Payments.PayPalStandard/Services/IPaypalHttpClient.cs b/src/Plugins/Payments.PayPalStandard/Services/IPaypalHttpClient.csdeleted file mode 100644index cb2615688..000000000--- a/src/Plugins/Payments.PayPalStandard/Services/IPaypalHttpClient.cs+++ /dev/null@@ -1,8 +0,0 @@-namespace Payments.PayPalStandard.Services-{- public interface IPaypalHttpClient- {- Task<(bool success, Dictionary<string, string> values)> VerifyIpn(string formString);- Task<(bool status, Dictionary<string, string> values, string response)> GetPdtDetails(string tx);- }-}diff --git a/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs b/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.csdeleted file mode 100644index 58999ea97..000000000--- a/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs+++ /dev/null@@ -1,107 +0,0 @@-using Microsoft.Extensions.Logging;-using System.Net.Http;--namespace Payments.PayPalStandard.Services-{- public class PaypalHttpClient : IPaypalHttpClient- {- private readonly HttpClient _client;- private readonly PayPalStandardPaymentSettings _paypalStandardPaymentSettings;- private readonly ILogger<PaypalHttpClient> _logger;- public PaypalHttpClient(HttpClient client, PayPalStandardPaymentSettings paypalStandardPaymentSettings, ILogger<PaypalHttpClient> logger)- {- _client = client;- _paypalStandardPaymentSettings = paypalStandardPaymentSettings;- _logger = logger;- }-- /// <summary>- /// Gets IPN PayPal URL- /// </summary>- /// <returns></returns>- private string GetIpnPaypalUrl()- {- return _paypalStandardPaymentSettings.UseSandbox ?- "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr" :- "https://ipnpb.paypal.com/cgi-bin/webscr";- }-- public async Task<(bool success, Dictionary<string, string> values)> VerifyIpn(string formString)- {- var formContent = new StringContent($"cmd=_notify-validate&{formString}",- Encoding.UTF8, "application/x-www-form-urlencoded");- var response = await _client.PostAsync(GetIpnPaypalUrl(), formContent);- var content = string.Empty;- try- {- response.EnsureSuccessStatusCode();- content = await response.Content.ReadAsStringAsync();- }- catch (Exception ex)- {- _logger.LogError(ex, "VerifyIpn");- }--- var success = content.Trim().Equals("VERIFIED", StringComparison.OrdinalIgnoreCase);-- var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);- foreach (var l in formString.Split('&'))- {- var line = l.Trim();- var equalPox = line.IndexOf('=');- if (equalPox >= 0)- values.Add(line[..equalPox], line[(equalPox + 1)..]);- }- return (success, values);- }-- /// <summary>- /// Gets PayPal PDT URL- /// </summary>- /// <returns></returns>- private string GetPaypalPdtUrl()- {- return _paypalStandardPaymentSettings.UseSandbox ?- PaypalHelper.PayPalUrlSandbox :- PaypalHelper.PayPalUrl;- }-- public async Task<(bool status, Dictionary<string, string> values, string response)> GetPdtDetails(string tx)- {- var formContent = new StringContent($"cmd=_notify-synch&at={_paypalStandardPaymentSettings.PdtToken}&tx={tx}",- Encoding.UTF8, "application/x-www-form-urlencoded");-- var response = await _client.PostAsync(GetPaypalPdtUrl(), formContent);- try- {- response.EnsureSuccessStatusCode();- }- catch(Exception ex)- {- _logger.LogError(ex, "GetPdtDetails");- }- var content = await response.Content.ReadAsStringAsync();-- var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);- bool firstLine = true, success = false;- foreach (var l in content.Split('\n'))- {- var line = l.Trim();- if (firstLine)- {- success = line.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase);- firstLine = false;- }- else- {- var equalPox = line.IndexOf('=');- if (equalPox >= 0)- values.Add(line[..equalPox], line[(equalPox + 1)..]);- }- }-- return (success, values, content);- }- }-}diff --git a/src/Plugins/Payments.PayPalStandard/StartupApplication.cs b/src/Plugins/Payments.PayPalStandard/StartupApplication.csdeleted file mode 100644index e1b06ad8a..000000000--- a/src/Plugins/Payments.PayPalStandard/StartupApplication.cs+++ /dev/null@@ -1,26 +0,0 @@-using Grand.Business.Core.Interfaces.Checkout.Payments;-using Grand.Infrastructure;-using Microsoft.AspNetCore.Builder;-using Microsoft.AspNetCore.Hosting;-using Microsoft.Extensions.Configuration;-using Microsoft.Extensions.DependencyInjection;-using Payments.PayPalStandard.Services;--namespace Payments.PayPalStandard-{- public class StartupApplication : IStartupApplication- {- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- services.AddScoped<IPaymentProvider, PayPalStandardPaymentProvider>();- services.AddHttpClient<IPaypalHttpClient, PaypalHttpClient>();- }-- public int Priority => 10;- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {-- }- public bool BeforeConfigure => false;- }-}diff --git a/src/Plugins/Payments.PayPalStandard/Views/PaymentPayPalStandard/PaymentInfo.cshtml b/src/Plugins/Payments.PayPalStandard/Views/PaymentPayPalStandard/PaymentInfo.cshtmldeleted file mode 100644index 85dd44163..000000000--- a/src/Plugins/Payments.PayPalStandard/Views/PaymentPayPalStandard/PaymentInfo.cshtml+++ /dev/null@@ -1,6 +0,0 @@-@{- Layout = "";-}-<div>- <b>@Loc["Plugins.Payments.PayPalStandard.Fields.RedirectionTip"]</b>-</div>\ No newline at end of filediff --git a/src/Plugins/Payments.PayPalStandard/logo.jpg b/src/Plugins/Payments.PayPalStandard/logo.jpgdeleted file mode 100644index 4de76b599..000000000Binary files a/src/Plugins/Payments.PayPalStandard/logo.jpg and /dev/null differdiff --git a/src/Plugins/Payments.StripeCheckout/Areas/Admin/Controllers/StripeCheckoutController.cs b/src/Plugins/Payments.StripeCheckout/Areas/Admin/Controllers/StripeCheckoutController.csnew file mode 100644index 000000000..8a410cfbc--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/Areas/Admin/Controllers/StripeCheckoutController.cs@@ -0,0 +1,105 @@+using Grand.Business.Core.Interfaces.Common.Configuration;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Business.Core.Interfaces.Common.Security;+using Grand.Business.Core.Interfaces.Common.Stores;+using Grand.Business.Core.Utilities.Common.Security;+using Grand.Domain.Common;+using Grand.Domain.Customers;+using Grand.Infrastructure;+using Grand.Web.Common.Controllers;+using Grand.Web.Common.Filters;+using Grand.Web.Common.Security.Authorization;+using Microsoft.AspNetCore.Mvc;+using Payments.StripeCheckout.Models;++namespace Payments.StripeCheckout.Areas.Admin.Controllers;++[AuthorizeAdmin]+[Area("Admin")]+[PermissionAuthorize(PermissionSystemName.PaymentMethods)]+public class StripeCheckoutController : BasePaymentController+{+ private readonly IWorkContext _workContext;+ private readonly IStoreService _storeService;+ private readonly ISettingService _settingService;+ private readonly ITranslationService _translationService;+ private readonly IPermissionService _permissionService;++ public StripeCheckoutController(IWorkContext workContext,+ IStoreService storeService,+ ISettingService settingService,+ ITranslationService translationService,+ IPermissionService permissionService)+ {+ _workContext = workContext;+ _storeService = storeService;+ _settingService = settingService;+ _translationService = translationService;+ _permissionService = permissionService;+ }++ private async Task<string> GetActiveStore()+ {+ var stores = await _storeService.GetAllStores();+ if (stores.Count < 2)+ return stores.FirstOrDefault()?.Id;++ var storeId =+ _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames+ .AdminAreaStoreScopeConfiguration);+ var store = await _storeService.GetStoreById(storeId);++ return store != null ? store.Id : "";+ }++ public async Task<IActionResult> Configure()+ {+ if (!await _permissionService.Authorize(StandardPermission.ManagePaymentMethods))+ return AccessDeniedView();++ //load settings for a chosen store scope+ var storeScope = await GetActiveStore();+ var stripeCheckoutPaymentSettings = _settingService.LoadSetting<StripeCheckoutPaymentSettings>(storeScope);++ var model = new ConfigurationModel {+ ApiKey = stripeCheckoutPaymentSettings.ApiKey,+ WebhookEndpointSecret = stripeCheckoutPaymentSettings.WebhookEndpointSecret,+ Description = stripeCheckoutPaymentSettings.Description,+ Line = stripeCheckoutPaymentSettings.Line,+ DisplayOrder = stripeCheckoutPaymentSettings.DisplayOrder,+ StoreScope = storeScope+ };++ return View(model);+ }++ [HttpPost]+ public async Task<IActionResult> Configure(ConfigurationModel model)+ {+ if (!await _permissionService.Authorize(StandardPermission.ManagePaymentMethods))+ return AccessDeniedView();++ if (!ModelState.IsValid)+ return await Configure();++ //load settings for a chosen store scope+ var storeScope = await GetActiveStore();+ var stripeCheckoutPaymentSettings = _settingService.LoadSetting<StripeCheckoutPaymentSettings>(storeScope);++ //save settings+ stripeCheckoutPaymentSettings.ApiKey = model.ApiKey;+ stripeCheckoutPaymentSettings.WebhookEndpointSecret = model.WebhookEndpointSecret;+ stripeCheckoutPaymentSettings.Description = model.Description;+ stripeCheckoutPaymentSettings.Line = model.Line;+ stripeCheckoutPaymentSettings.DisplayOrder = model.DisplayOrder;++ await _settingService.SaveSetting(stripeCheckoutPaymentSettings, storeScope);++ //now clear settings cache+ await _settingService.ClearCache();++ Success(_translationService.GetResource("Admin.Plugins.Saved"));++ return await Configure();+ }+}\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/StripeCheckout/Configure.cshtml b/src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/StripeCheckout/Configure.cshtmlnew file mode 100644index 000000000..8b35bdb93--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/StripeCheckout/Configure.cshtml@@ -0,0 +1,85 @@+@inject IUrlHelperFactory UrlHelperFactory+@inject IActionContextAccessor ActionContextAccessor+@inject IWorkContext WorkContext+@{+ Layout = "_ConfigurePlugin";+ var urlHelper = UrlHelperFactory.GetUrlHelper(ActionContextAccessor.ActionContext!);+ var webhookUrl = WorkContext.CurrentHost.Url.TrimEnd('/') + urlHelper.RouteUrl(StripeCheckoutDefaults.WebHook);+}+@model ConfigurationModel+@using Microsoft.AspNetCore.Mvc.Routing+@using Microsoft.AspNetCore.Mvc.Infrastructure+@using Payments.StripeCheckout+@using Payments.StripeCheckout.Models+@using Grand.Infrastructure+@await Component.InvokeAsync("StoreScope")++<form asp-area="Admin" asp-controller="StripeCheckout" asp-action="Configure" method="post">+ <p>+ For plugin configuration please check:<br/>+ <br/>+ 1. Generate API keys from the Stripe Dashboard: <a href="https://stripe.com/docs/api/authentication" target="_blank">Click here.</a><br/>+ 2. Register webhook endpoints with Stripe <a href="https://stripe.com/docs/development/dashboard/register-webhook" target="_blank">Click here.</a><br/>+ 3. Your Webhook URL: @webhookUrl <br/>+ 4. Fill in your credentials below.<br/>+ 5. Save the configuration.<br/>+ <br/>+ <em>Note: Ensure that you have configured your primary store currency that is supported by selected payment service provider.</em><br/>+ </p>+ <div class="form-horizontal">+ <div class="form-body">+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="ApiKey" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="ApiKey"/>+ <span asp-validation-for="ApiKey"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="WebhookEndpointSecret" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="WebhookEndpointSecret"/>+ <span asp-validation-for="WebhookEndpointSecret"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="Line" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="Line"/>+ <span asp-validation-for="Line"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="Description" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-textarea asp-for="Description"/>+ <span asp-validation-for="Description"></span>+ </div>+ </div>+ <div class="form-group">+ <div class="col-md-3 col-sm-3 text-right">+ <admin-label asp-for="DisplayOrder" class="control-label"/>+ </div>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="DisplayOrder"/>+ <span asp-validation-for="DisplayOrder"></span>+ </div>+ </div>+ </div>+ <div class="form-actions">+ <div class="row">+ <div class="offset-md-3 offset-sm-3 col-md-9 col-sm-9">+ <input type="submit" name="save" class="btn green" value="@Loc["Admin.Common.Save"]"/>+ </div>+ </div>+ </div>+ </div>+</form>\ No newline at end of filediff --git a/src/Plugins/Payments.PayPalStandard/Areas/Admin/Views/_ViewImports.cshtml b/src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/_ViewImports.cshtmlsimilarity index 100%rename from src/Plugins/Payments.PayPalStandard/Areas/Admin/Views/_ViewImports.cshtmlrename to src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/_ViewImports.cshtmldiff --git a/src/Plugins/Payments.StripeCheckout/Controllers/PaymentStripeCheckoutController.cs b/src/Plugins/Payments.StripeCheckout/Controllers/PaymentStripeCheckoutController.csnew file mode 100644index 000000000..404a5a386--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/Controllers/PaymentStripeCheckoutController.cs@@ -0,0 +1,69 @@+using Grand.Business.Core.Interfaces.Checkout.Orders;+using Grand.Business.Core.Interfaces.Checkout.Payments;+using Grand.Domain.Payments;+using Grand.Infrastructure;+using Grand.Web.Common.Controllers;+using Microsoft.AspNetCore.Mvc;+using Microsoft.Extensions.Logging;+using Payments.StripeCheckout.Models;+using Payments.StripeCheckout.Services;++namespace Payments.StripeCheckout.Controllers;++public class PaymentStripeCheckoutController : BasePaymentController+{+ private readonly IWorkContext _workContext;+ private readonly IOrderService _orderService;+ private readonly IStripeCheckoutService _stripeCheckoutService;+ private readonly ILogger<PaymentStripeCheckoutController> _logger;+ private readonly IPaymentTransactionService _paymentTransactionService;+ private readonly StripeCheckoutPaymentSettings _stripeCheckoutPaymentSettings;++ private readonly PaymentSettings _paymentSettings;++ public PaymentStripeCheckoutController(+ IWorkContext workContext,+ IOrderService orderService,+ ILogger<PaymentStripeCheckoutController> logger,+ IPaymentTransactionService paymentTransactionService,+ PaymentSettings paymentSettings,+ StripeCheckoutPaymentSettings stripeCheckoutPaymentSettings, IStripeCheckoutService stripeCheckoutService)+ {+ _workContext = workContext;+ _orderService = orderService;+ _logger = logger;+ _paymentTransactionService = paymentTransactionService;+ _paymentSettings = paymentSettings;+ _stripeCheckoutPaymentSettings = stripeCheckoutPaymentSettings;+ _stripeCheckoutService = stripeCheckoutService;+ }++ [HttpPost]+ public async Task<IActionResult> WebHook()+ {+ var json = await new StreamReader(Request.Body).ReadToEndAsync();+ try+ {+ await _stripeCheckoutService.WebHookProcessPayment(Request.Headers["Stripe-Signature"], json);+ return Ok();+ }+ catch(Exception e)+ {+ return BadRequest(e.Message);+ }+ }++ public async Task<IActionResult> CancelOrder(string orderId)+ {+ var order = await _orderService.GetOrderById(orderId);+ if (order != null && order.CustomerId == _workContext.CurrentCustomer.Id)+ return RedirectToRoute("OrderDetails", new { orderId = order.Id });++ return RedirectToRoute("HomePage");+ }++ public IActionResult PaymentInfo()+ {+ return View(new PaymentInfo(_stripeCheckoutPaymentSettings.Description));+ }+}\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/EndpointProvider.cs b/src/Plugins/Payments.StripeCheckout/EndpointProvider.csnew file mode 100644index 000000000..051289390--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/EndpointProvider.cs@@ -0,0 +1,31 @@+using Grand.Infrastructure.Endpoints;+using Microsoft.AspNetCore.Builder;+using Microsoft.AspNetCore.Routing;++namespace Payments.StripeCheckout;++public class EndpointProvider : IEndpointProvider+{+ public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)+ {+ //PaymentInfo+ endpointRouteBuilder.MapControllerRoute(StripeCheckoutDefaults.PaymentInfo,+ "Plugins/PaymentStripeCheckout/PaymentInfo",+ new { controller = "PaymentStripeCheckout", action = "PaymentInfo", area = "" }+ );++ //WebHook+ endpointRouteBuilder.MapControllerRoute(StripeCheckoutDefaults.WebHook,+ "Plugins/PaymentStripeCheckout/WebHook",+ new { controller = "PaymentStripeCheckout", action = "WebHook", area = "" }+ );++ //Cancel+ endpointRouteBuilder.MapControllerRoute("Plugin.Payments.StripeCheckout.CancelOrder",+ "Plugins/PaymentStripeCheckout/CancelOrder/{orderId}",+ new { controller = "PaymentStripeCheckout", action = "CancelOrder", area = "" }+ );+ }+ public int Priority => 0;++}\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/Manifest.cs b/src/Plugins/Payments.StripeCheckout/Manifest.csnew file mode 100644index 000000000..199ee9a1a--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/Manifest.cs@@ -0,0 +1,10 @@+using Grand.Infrastructure.Plugins;+using Payments.StripeCheckout;++[assembly: PluginInfo(+ FriendlyName = "Stripe Checkout",+ Group = "Payment methods",+ SystemName = StripeCheckoutDefaults.ProviderSystemName,+ Author = "grandnode team",+ Version = "1.0.0"+)]\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/Models/ConfigurationModel.cs b/src/Plugins/Payments.StripeCheckout/Models/ConfigurationModel.csnew file mode 100644index 000000000..124f0cdba--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/Models/ConfigurationModel.cs@@ -0,0 +1,24 @@+using Grand.Infrastructure.ModelBinding;+using Grand.Infrastructure.Models;++namespace Payments.StripeCheckout.Models;++public class ConfigurationModel : BaseModel+{+ public string StoreScope { get; set; }++ [GrandResourceDisplayName("Plugins.Payments.StripeCheckout.Fields.ApiKey")]+ public string ApiKey { get; set; }++ [GrandResourceDisplayName("Plugins.Payments.StripeCheckout.Fields.WebhookEndpointSecret")]+ public string WebhookEndpointSecret { get; set; }++ [GrandResourceDisplayName("Plugins.Payments.StripeCheckout.Fields.Description")]+ public string Description { get; set; }++ [GrandResourceDisplayName("Plugins.Payments.StripeCheckout.Fields.Line")]+ public string Line { get; set; }++ [GrandResourceDisplayName("Plugins.Payments.StripeCheckout.Fields.DisplayOrder")]+ public int DisplayOrder { get; set; }+}\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/Models/PaymentInfo.cs b/src/Plugins/Payments.StripeCheckout/Models/PaymentInfo.csnew file mode 100644index 000000000..e41483145--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/Models/PaymentInfo.cs@@ -0,0 +1,3 @@+namespace Payments.StripeCheckout.Models;++public record PaymentInfo(string Description);diff --git a/src/Plugins/Payments.StripeCheckout/Payments.StripeCheckout.csproj b/src/Plugins/Payments.StripeCheckout/Payments.StripeCheckout.csprojnew file mode 100644index 000000000..0269089ef--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/Payments.StripeCheckout.csproj@@ -0,0 +1,64 @@+<Project Sdk="Microsoft.NET.Sdk.Razor">+ <Import Project="..\..\Build\Grand.Common.props" />+ <PropertyGroup>+ <AddRazorSupportForMvc>true</AddRazorSupportForMvc>+ </PropertyGroup>++ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">+ <OutputPath>..\..\Web\Grand.Web\Plugins\Payments.StripeCheckout\</OutputPath>+ <OutDir>$(OutputPath)</OutDir>+ </PropertyGroup>++ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">+ <OutputPath>..\..\Web\Grand.Web\Plugins\Payments.StripeCheckout\</OutputPath>+ <OutDir>$(OutputPath)</OutDir>+ </PropertyGroup>++ <Target Name="PostBuild" AfterTargets="PostBuildEvent">+ <RemoveDir Directories="..\..\Web\Grand.Web\Plugins\Payments.StripeCheckout\refs" />+ </Target>++ <ItemGroup>+ <PackageReference Include="Stripe.net" Version="43.11.0" />+ </ItemGroup>++ <Target Name="CopyFile" AfterTargets="AfterBuild">+ <ItemGroup>+ <CopyFiles Include="$(NuGetPackageRoot)\stripe.net\43.11.0\lib\net6.0\*.*" />+ </ItemGroup>+ <Copy SourceFiles="@(CopyFiles)" DestinationFolder="..\..\Web\Grand.Web\Plugins\Payments.StripeCheckout\" />+ </Target>++ <ItemGroup>+ <ProjectReference Include="..\..\Core\Grand.Data\Grand.Data.csproj">+ <Private>false</Private>+ </ProjectReference>+ <ProjectReference Include="..\..\Business\Grand.Business.Core\Grand.Business.Core.csproj">+ <Private>false</Private>+ </ProjectReference>+ <ProjectReference Include="..\..\Core\Grand.Domain\Grand.Domain.csproj">+ <Private>false</Private>+ </ProjectReference>+ <ProjectReference Include="..\..\Core\Grand.Infrastructure\Grand.Infrastructure.csproj">+ <Private>false</Private>+ </ProjectReference>+ <ProjectReference Include="..\..\Core\Grand.SharedKernel\Grand.SharedKernel.csproj">+ <Private>false</Private>+ </ProjectReference>+ <ProjectReference Include="..\..\Web\Grand.Web.Common\Grand.Web.Common.csproj">+ <Private>false</Private>+ <ExcludeAssets>all</ExcludeAssets>+ </ProjectReference>+ </ItemGroup>++ <ItemGroup>+ <None Update="logo.jpg">+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>+ </None>+ </ItemGroup>++ <ItemGroup>+ <Folder Include="Properties\" />+ </ItemGroup>++</Project>\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/Services/IStripeCheckoutService.cs b/src/Plugins/Payments.StripeCheckout/Services/IStripeCheckoutService.csnew file mode 100644index 000000000..0050c5f4a--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/Services/IStripeCheckoutService.cs@@ -0,0 +1,9 @@+using Grand.Domain.Orders;++namespace Payments.StripeCheckout.Services;++public interface IStripeCheckoutService+{+ Task<string> CreateRedirectUrl(Order order);+ Task<bool> WebHookProcessPayment(string stripeSignature, string json);+}\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/Services/StripeCheckoutService.cs b/src/Plugins/Payments.StripeCheckout/Services/StripeCheckoutService.csnew file mode 100644index 000000000..d5a63c2ff--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/Services/StripeCheckoutService.cs@@ -0,0 +1,126 @@+using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Interfaces.Checkout.Payments;+using Grand.Domain.Orders;+using Grand.Infrastructure;+using MediatR;+using Microsoft.Extensions.Logging;+using Stripe;+using Stripe.Checkout;++namespace Payments.StripeCheckout.Services;++public class StripeCheckoutService : IStripeCheckoutService+{+ private readonly StripeCheckoutPaymentSettings _stripeCheckoutPaymentSettings;+ private readonly IWorkContext _workContext;+ private readonly ILogger<StripeCheckoutService> _logger;+ private readonly IMediator _mediator;+ private readonly IPaymentTransactionService _paymentTransactionService;++ public StripeCheckoutService(+ IWorkContext workContext,+ StripeCheckoutPaymentSettings stripeCheckoutPaymentSettings,+ ILogger<StripeCheckoutService> logger,+ IMediator mediator,+ IPaymentTransactionService paymentTransactionService)+ {+ _workContext = workContext;+ _stripeCheckoutPaymentSettings = stripeCheckoutPaymentSettings;+ _logger = logger;+ _mediator = mediator;+ _paymentTransactionService = paymentTransactionService;+ }++ public async Task<string> CreateRedirectUrl(Order order)+ {+ var session = await CreateUrlSession(order);+ return session.Url;+ }++ public async Task<bool> WebHookProcessPayment(string stripeSignature, string json)+ {+ try+ {+ var stripeEvent = EventUtility.ConstructEvent(json, stripeSignature,+ _stripeCheckoutPaymentSettings.WebhookEndpointSecret);+ // Handle the event+ if (stripeEvent.Type == Events.PaymentIntentSucceeded)+ {+ var paymentIntent = stripeEvent.Data.Object as PaymentIntent;+ await CreatePaymentTransaction(paymentIntent);+ return true;+ }+ }+ catch (StripeException e)+ {+ _logger.LogError(e, "StripeException");+ return false;+ }+ return false;+ }++ private async Task CreatePaymentTransaction(PaymentIntent paymentIntent)+ {+ if (paymentIntent.Metadata.TryGetValue("order_guid", out var order_guid)+ && Guid.TryParse(order_guid, out var orderGuid))+ {+ var paymentTransaction = await _paymentTransactionService.GetOrderByGuid(orderGuid);+ if (paymentTransaction == null ||+ !paymentIntent.Currency.Equals(paymentTransaction.CurrencyCode,+ StringComparison.InvariantCultureIgnoreCase))+ {+ _logger.LogError("paymentTransaction is null or currency is not equal");+ return;+ }++ try+ {+ paymentTransaction.AuthorizationTransactionId = paymentIntent.Id;+ paymentTransaction.PaidAmount += (paymentIntent.Amount / 100);+ await _mediator.Send(new MarkAsPaidCommand { PaymentTransaction = paymentTransaction });+ }+ catch (Exception e)+ {+ _logger.LogError(e, "Error in CreatePaymentTransaction");+ }+ }+ else+ {+ _logger.LogError("order_guid can't get from metadata or orderGuid is not valid");+ }+ }++ private async Task<Session> CreateUrlSession(Order order)+ {+ StripeConfiguration.ApiKey = _stripeCheckoutPaymentSettings.ApiKey;++ var storeLocation = _workContext.CurrentHost.Url.TrimEnd('/');++ var options = new SessionCreateOptions {+ LineItems = [+ new SessionLineItemOptions {+ PriceData = new SessionLineItemPriceDataOptions {+ UnitAmountDecimal = (decimal?)order.OrderTotal * 100,+ ProductData = new SessionLineItemPriceDataProductDataOptions {+ Name = string.Format(_stripeCheckoutPaymentSettings.Line, order.OrderNumber),+ },+ Currency = order.CustomerCurrencyCode,+ },+ Quantity = 1,+ }+ ],+ ClientReferenceId = order.Id,+ CustomerEmail = order.CustomerEmail,+ PaymentIntentData = new SessionPaymentIntentDataOptions() {+ Metadata = new Dictionary<string, string> { { "order_guid", order.OrderGuid.ToString() } },+ },+ Mode = "payment",+ SuccessUrl = $"{storeLocation}/orderdetails/{order.Id}",+ CancelUrl = $"{storeLocation}/Plugins/PaymentStripeCheckout/CancelOrder/{order.Id}",+ };+ var service = new SessionService();+ Session session = await service.CreateAsync(options);++ return session;+ }+}\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/StartupApplication.cs b/src/Plugins/Payments.StripeCheckout/StartupApplication.csnew file mode 100644index 000000000..6e5002791--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/StartupApplication.cs@@ -0,0 +1,25 @@+using Grand.Business.Core.Interfaces.Checkout.Payments;+using Grand.Infrastructure;+using Microsoft.AspNetCore.Builder;+using Microsoft.AspNetCore.Hosting;+using Microsoft.Extensions.Configuration;+using Microsoft.Extensions.DependencyInjection;+using Payments.StripeCheckout.Services;++namespace Payments.StripeCheckout;++public class StartupApplication : IStartupApplication+{+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration)+ {+ services.AddScoped<IPaymentProvider, StripeCheckoutPaymentProvider>();+ services.AddScoped<IStripeCheckoutService, StripeCheckoutService>();+ }++ public int Priority => 10;+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {++ }+ public bool BeforeConfigure => false;+}\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/StripeCheckoutDefaults.cs b/src/Plugins/Payments.StripeCheckout/StripeCheckoutDefaults.csnew file mode 100644index 000000000..37f571711--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/StripeCheckoutDefaults.cs@@ -0,0 +1,10 @@+namespace Payments.StripeCheckout;++public static class StripeCheckoutDefaults+{+ public const string ProviderSystemName = "Payments.StripeCheckout";+ public const string FriendlyName = "Plugins.Payments.StripeCheckout.FriendlyName";+ public const string ConfigurationUrl = "/Admin/StripeCheckout/Configure";+ public static string WebHook => "Plugin.Payments.StripeCheckout.WebHook";+ public static string PaymentInfo => "Plugin.Payments.StripeCheckout.PaymentInfo";+}\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentPlugin.cs b/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentPlugin.csnew file mode 100644index 000000000..62d690822--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentPlugin.cs@@ -0,0 +1,100 @@+using Grand.Business.Core.Extensions;+using Grand.Business.Core.Interfaces.Common.Configuration;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Infrastructure.Plugins;++namespace Payments.StripeCheckout;++/// <summary>+/// StripeCheckout payment processor+/// </summary>+public class StripeCheckoutPaymentPlugin : BasePlugin, IPlugin+{+ #region Fields++ private readonly ITranslationService _translationService;+ private readonly ILanguageService _languageService;+ private readonly ISettingService _settingService;++ #endregion++ #region Ctor++ public StripeCheckoutPaymentPlugin(+ ITranslationService translationService,+ ILanguageService languageService,+ ISettingService settingService)+ {+ _translationService = translationService;+ _languageService = languageService;+ _settingService = settingService;+ }++ #endregion++ #region Methods++ /// <summary>+ /// Gets a configuration page URL+ /// </summary>+ public override string ConfigurationUrl()+ {+ return StripeCheckoutDefaults.ConfigurationUrl;+ }++ /// <summary>+ /// Install the plugin+ /// </summary>+ public override async Task Install()+ {+ //settings+ await _settingService.SaveSetting(new StripeCheckoutPaymentSettings {+ Description = "Enjoy seamless transactions with the flexibility to pay using your preferred payment method through Stripe Checkout. We ensure a secure and hassle-free payment experience, accommodating a wide range of payment options to suit your convenience.",+ DisplayOrder = 0,+ Line = "Order number {0}"+ });++ //locales+ await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService,+ "Plugins.Payments.StripeCheckout.FriendlyName", "Pay with Stripe");+ await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService,+ "Plugins.Payments.StripeCheckout.Fields.ApiKey", "Stripe ApiKey (secret type)");+ await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService,+ "Plugins.Payments.StripeCheckout.Fields.WebhookEndpointSecret", "Webhook secret for your endpoint");+ await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService,+ "Plugins.Payments.StripeCheckout.Fields.Description", "Description");+ await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService,+ "Plugins.Payments.StripeCheckout.Fields.Line", "Description line on the checkout page in Stripe");+ await this.AddOrUpdatePluginTranslateResource(_translationService, _languageService,+ "Plugins.Payments.StripeCheckout.Fields.DisplayOrder", "Display order");++ await base.Install();+ }++ /// <summary>+ /// Uninstall the plugin+ /// </summary>+ public override async Task Uninstall()+ {+ //settings+ await _settingService.DeleteSetting<StripeCheckoutPaymentSettings>();++ //locales+ await this.DeletePluginTranslationResource(_translationService, _languageService,+ "Plugins.Payments.StripeCheckout.FriendlyName");+ await this.DeletePluginTranslationResource(_translationService, _languageService,+ "Plugins.Payments.StripeCheckout.Fields.ApiKey");+ await this.DeletePluginTranslationResource(_translationService, _languageService,+ "Plugins.Payments.StripeCheckout.Fields.WebhookEndpointSecret");+ await this.DeletePluginTranslationResource(_translationService, _languageService,+ "Plugins.Payments.StripeCheckout.Fields.Description");+ await this.DeletePluginTranslationResource(_translationService, _languageService,+ "Plugins.Payments.StripeCheckout.Fields.Line");+ await this.DeletePluginTranslationResource(_translationService, _languageService,+ "Plugins.Payments.StripeCheckout.Fields.DisplayOrder");++ await base.Uninstall();+ }++ #endregion+}\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentProvider.cs b/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentProvider.csnew file mode 100644index 000000000..b3257fb06--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentProvider.cs@@ -0,0 +1,251 @@+using Grand.Business.Core.Enums.Checkout;+using Grand.Business.Core.Interfaces.Checkout.Orders;+using Grand.Business.Core.Interfaces.Checkout.Payments;+using Grand.Business.Core.Utilities.Checkout;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Domain.Orders;+using Grand.Domain.Payments;+using Microsoft.AspNetCore.Http;+using Payments.StripeCheckout.Services;++namespace Payments.StripeCheckout;++public class StripeCheckoutPaymentProvider : IPaymentProvider+{+ private readonly ITranslationService _translationService;+ private readonly IStripeCheckoutService _stripeCheckoutService;+ private readonly StripeCheckoutPaymentSettings _stripeCheckoutPaymentSettings;+ private readonly IHttpContextAccessor _httpContextAccessor;+ private readonly IOrderService _orderService;++ #region Ctor++ public StripeCheckoutPaymentProvider(+ IHttpContextAccessor httpContextAccessor,+ ITranslationService translationService,+ IOrderService orderService,+ StripeCheckoutPaymentSettings stripeCheckoutPaymentSettings, IStripeCheckoutService stripeCheckoutService)+ {+ _httpContextAccessor = httpContextAccessor;+ _translationService = translationService;+ _orderService = orderService;+ _stripeCheckoutPaymentSettings = stripeCheckoutPaymentSettings;+ _stripeCheckoutService = stripeCheckoutService;+ }++ #endregion++ public string ConfigurationUrl => StripeCheckoutDefaults.ConfigurationUrl;++ public string SystemName => StripeCheckoutDefaults.ProviderSystemName;++ public string FriendlyName => _translationService.GetResource(StripeCheckoutDefaults.FriendlyName);++ public int Priority => _stripeCheckoutPaymentSettings.DisplayOrder;++ public IList<string> LimitedToStores => new List<string>();++ public IList<string> LimitedToGroups => new List<string>();++ #region Properties++ /// <summary>+ /// Init a process a payment transaction+ /// </summary>+ /// <returns>Payment transaction</returns>+ public async Task<PaymentTransaction> InitPaymentTransaction()+ {+ return await Task.FromResult<PaymentTransaction>(null);+ }++ /// <summary>+ /// Process a payment+ /// </summary>+ /// <param name="paymentTransaction"></param>+ /// <returns>Process payment result</returns>+ public async Task<ProcessPaymentResult> ProcessPayment(PaymentTransaction paymentTransaction)+ {+ var result = new ProcessPaymentResult();+ return await Task.FromResult(result);+ }++ public Task PostProcessPayment(PaymentTransaction paymentTransaction)+ {+ //nothing+ return Task.CompletedTask;+ }++ /// <summary>+ /// Post process payment (used by payment gateways that require redirecting to a third-party URL)+ /// </summary>+ /// <param name="paymentTransaction"></param>+ public async Task PostRedirectPayment(PaymentTransaction paymentTransaction)+ {+ var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);+ var url = await _stripeCheckoutService.CreateRedirectUrl(order);+ _httpContextAccessor.HttpContext?.Response.Redirect(url);+ }++ /// <summary>+ /// Returns a value indicating whether payment method should be hidden during checkout+ /// </summary>+ /// <param name="cart">Shopping cart</param>+ /// <returns>true - hide; false - display.</returns>+ public async Task<bool> HidePaymentMethod(IList<ShoppingCartItem> cart)+ {+ //you can put any logic here+ //for example, hide this payment method if all products in the cart are downloadable+ //or hide this payment method if current customer is from certain country+ return await Task.FromResult(false);+ }++ /// <summary>+ /// Gets additional handling fee+ /// </summary>+ /// <param name="cart">Shopping cart</param>+ /// <returns>Additional handling fee</returns>+ public async Task<double> GetAdditionalHandlingFee(IList<ShoppingCartItem> cart)+ {+ return await Task.FromResult(0.0);+ }++ /// <summary>+ /// Captures payment+ /// </summary>+ /// <returns>Capture payment result</returns>+ public async Task<CapturePaymentResult> Capture(PaymentTransaction paymentTransaction)+ {+ var result = new CapturePaymentResult();+ result.AddError("Capture method not supported");+ return await Task.FromResult(result);+ }++ /// <summary>+ /// Refunds a payment+ /// </summary>+ /// <param name="refundPaymentRequest">Request</param>+ /// <returns>Result</returns>+ public async Task<RefundPaymentResult> Refund(RefundPaymentRequest refundPaymentRequest)+ {+ var result = new RefundPaymentResult();+ result.AddError("Refund method not supported");+ return await Task.FromResult(result);+ }++ /// <summary>+ /// Voids a payment+ /// </summary>+ /// <returns>Result</returns>+ public async Task<VoidPaymentResult> Void(PaymentTransaction paymentTransaction)+ {+ var result = new VoidPaymentResult();+ result.AddError("Void method not supported");+ return await Task.FromResult(result);+ }++ /// <summary>+ /// Cancel a payment+ /// </summary>+ /// <returns>Result</returns>+ public Task CancelPayment(PaymentTransaction paymentTransaction)+ {+ return Task.CompletedTask;+ }+++ /// <summary>+ /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)+ /// </summary>+ /// <returns>Result</returns>+ public async Task<bool> CanRePostRedirectPayment(PaymentTransaction paymentTransaction)+ {+ ArgumentNullException.ThrowIfNull(paymentTransaction);+ if ((DateTime.UtcNow - paymentTransaction.CreatedOnUtc).TotalMinutes < 1)+ return false;++ return await Task.FromResult(true);+ }++ /// <summary>+ /// Validate payment form+ /// </summary>+ /// <param name="model"></param>+ /// <returns>List of validating errors</returns>+ public async Task<IList<string>> ValidatePaymentForm(IDictionary<string, string> model)+ {+ return await Task.FromResult(new List<string>());+ }++ /// <summary>+ /// Get payment information+ /// </summary>+ /// <param name="model"></param>+ /// <returns>Payment info holder</returns>+ public async Task<PaymentTransaction> SavePaymentInfo(IDictionary<string, string> model)+ {+ return await Task.FromResult<PaymentTransaction>(null);+ }+++ /// <summary>+ /// Gets a value indicating whether capture is supported+ /// </summary>+ public async Task<bool> SupportCapture()+ {+ return await Task.FromResult(false);+ }++ /// <summary>+ /// Gets a value indicating whether partial refund is supported+ /// </summary>+ public async Task<bool> SupportPartiallyRefund()+ {+ return await Task.FromResult(false);+ }++ /// <summary>+ /// Gets a value indicating whether refund is supported+ /// </summary>+ public async Task<bool> SupportRefund()+ {+ return await Task.FromResult(false);+ }++ /// <summary>+ /// Gets a value indicating whether void is supported+ /// </summary>+ public async Task<bool> SupportVoid()+ {+ return await Task.FromResult(false);+ }++ /// <summary>+ /// Gets a payment method type+ /// </summary>+ public PaymentMethodType PaymentMethodType => PaymentMethodType.Redirection;++ /// <summary>+ /// Gets a value indicating whether we should display a payment information page for this plugin+ /// </summary>+ public async Task<bool> SkipPaymentInfo()+ {+ return await Task.FromResult(false);+ }++ /// <summary>+ /// Gets a payment method description that will be displayed on checkout pages in the public store+ /// </summary>+ public async Task<string> Description()+ {+ return await Task.FromResult(_translationService.GetResource("Plugins.Payments.StripeCheckout.FriendlyName"));+ }++ public Task<string> GetControllerRouteName()+ {+ return Task.FromResult(StripeCheckoutDefaults.PaymentInfo);+ }++ public string LogoURL => "/Plugins/Payments.StripeCheckout/logo.jpg";++ #endregion+}\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentSettings.cs b/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentSettings.csnew file mode 100644index 000000000..9e22a2767--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/StripeCheckoutPaymentSettings.cs@@ -0,0 +1,12 @@+using Grand.Domain.Configuration;++namespace Payments.StripeCheckout;++public class StripeCheckoutPaymentSettings : ISettings+{+ public string ApiKey { get; set; }+ public string WebhookEndpointSecret { get; set; }+ public string Description { get; set; }+ public string Line { get; set; }+ public int DisplayOrder { get; set; }+}\ No newline at end of filediff --git a/src/Plugins/Payments.StripeCheckout/Views/PaymentStripeCheckout/PaymentInfo.cshtml b/src/Plugins/Payments.StripeCheckout/Views/PaymentStripeCheckout/PaymentInfo.cshtmlnew file mode 100644index 000000000..ee165be01--- /dev/null+++ b/src/Plugins/Payments.StripeCheckout/Views/PaymentStripeCheckout/PaymentInfo.cshtml@@ -0,0 +1,7 @@+@model Payments.StripeCheckout.Models.PaymentInfo+@{+ Layout = "";+}+<div>+ @Html.Raw(Model.Description)+</div>\ No newline at end of filediff --git a/src/Plugins/Payments.PayPalStandard/Views/_ViewImports.cshtml b/src/Plugins/Payments.StripeCheckout/Views/_ViewImports.cshtmlsimilarity index 100%rename from src/Plugins/Payments.PayPalStandard/Views/_ViewImports.cshtmlrename to src/Plugins/Payments.StripeCheckout/Views/_ViewImports.cshtmldiff --git a/src/Plugins/Payments.StripeCheckout/logo.jpg b/src/Plugins/Payments.StripeCheckout/logo.jpgnew file mode 100644index 000000000..b4d08e68fBinary files /dev/null and b/src/Plugins/Payments.StripeCheckout/logo.jpg differdiff --git a/src/Tests/Grand.Business.Checkout.Tests/Extensions/PaymentExtensionsTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Extensions/PaymentExtensionsTests.csindex 657616597..29d9d4cd4 100644--- a/src/Tests/Grand.Business.Checkout.Tests/Extensions/PaymentExtensionsTests.cs+++ b/src/Tests/Grand.Business.Checkout.Tests/Extensions/PaymentExtensionsTests.cs@@ -21,8 +21,8 @@ namespace Grand.Business.Checkout.Tests.Extensionspublic void IsPaymentMethodActive_ReturnExpectedResult(){var settings = new PaymentSettings();- _providerMock.Setup(c => c.SystemName).Returns("paypal");- settings.ActivePaymentProviderSystemNames.Add("paypal");+ _providerMock.Setup(c => c.SystemName).Returns("stripe");+ settings.ActivePaymentProviderSystemNames.Add("stripe");Assert.IsTrue(_providerMock.Object.IsPaymentMethodActive(settings));_providerMock.Setup(c => c.SystemName).Returns("klarna");Assert.IsFalse(_providerMock.Object.IsPaymentMethodActive(settings));diff --git a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs b/src/Web/Grand.Web.Admin/Controllers/PluginController.csindex 1c901724d..dcc3b0f49 100644--- a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/PluginController.cs@@ -338,7 +338,7 @@ namespace Grand.Web.Admin.Controllersif (rootDirectories.Count != 1){throw new Exception(- "The archive should contain only one root plugin. For example, Payments.PayPalDirect.");+ "The archive should contain only one root plugin. For example, Payments.StripeCheckout.");}//get directory name (remove the ending /)