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
Fix PayPalStandard payment plugin
KrzysztofPajak98e531e98104
diff --git a/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs b/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.csindex 1d726939e..489bec0a4 100644--- a/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs+++ b/src/Plugins/Payments.PayPalStandard/Controllers/PaymentPayPalStandardController.cs@@ -4,11 +4,7 @@ using Grand.Business.Checkout.Interfaces.Orders;using Grand.Business.Checkout.Interfaces.Payments;using Grand.Business.Checkout.Queries.Models.Orders;using Grand.Business.Common.Extensions;-using Grand.Business.Common.Interfaces.Configuration;-using Grand.Business.Common.Interfaces.Localization;using Grand.Business.Common.Interfaces.Logging;-using Grand.Business.Common.Interfaces.Security;-using Grand.Business.Common.Interfaces.Stores;using Grand.Domain.Orders;using Grand.Domain.Payments;using Grand.Infrastructure;@@ -18,6 +14,7 @@ using MediatR;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Primitives;+using Payments.PayPalStandard.Services;using System;using System.Collections.Generic;using System.Globalization;@@ -37,6 +34,8 @@ namespace Payments.PayPalStandard.Controllersprivate readonly ILogger _logger;private readonly IMediator _mediator;private readonly IPaymentTransactionService _paymentTransactionService;+ private readonly IPaypalHttpClient _paypalHttpClient;+private readonly PaymentSettings _paymentSettings;private readonly PayPalStandardPaymentSettings _payPalStandardPaymentSettings;@@ -47,6 +46,7 @@ namespace Payments.PayPalStandard.ControllersILogger logger,IMediator mediator,IPaymentTransactionService paymentTransactionService,+ IPaypalHttpClient paypalHttpClient,PayPalStandardPaymentSettings payPalStandardPaymentSettings,PaymentSettings paymentSettings){@@ -56,6 +56,7 @@ namespace Payments.PayPalStandard.Controllers_logger = logger;_mediator = mediator;_paymentTransactionService = paymentTransactionService;+ _paypalHttpClient = paypalHttpClient;_payPalStandardPaymentSettings = payPalStandardPaymentSettings;_paymentSettings = paymentSettings;}@@ -69,21 +70,19 @@ namespace Payments.PayPalStandard.Controllersreturn HttpContext.Request.Query[name].ToString();}- public async Task<IActionResult> PDTHandler(IFormCollection form)+ public async Task<IActionResult> PDTHandler(){var tx = QueryString("tx");- Dictionary<string, string> values;- string response;- var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.PayPalStandard") as PayPalStandardPaymentProvider;- if (processor == null ||+ if (_paymentService.LoadPaymentMethodBySystemName("Payments.PayPalStandard") is not PayPalStandardPaymentProvider processor ||!processor.IsPaymentMethodActive(_paymentSettings))throw new GrandException("PayPal Standard module cannot be loaded");- if (processor.GetPdtDetails(tx, out values, out response))+ (var status, var values, var _) = await _paypalHttpClient.GetPdtDetails(tx);++ if (status){- string orderNumber = string.Empty;- values.TryGetValue("custom", out orderNumber);+ values.TryGetValue("custom", out var orderNumber);Guid orderNumberGuid = Guid.Empty;try{@@ -105,26 +104,16 @@ namespace Payments.PayPalStandard.Controllers_logger.Error("PayPal PDT. Error getting mc_gross", exc);}- string payer_status = string.Empty;- values.TryGetValue("payer_status", out payer_status);- string payment_status = string.Empty;- values.TryGetValue("payment_status", out payment_status);- string pending_reason = string.Empty;- values.TryGetValue("pending_reason", out pending_reason);- string mc_currency = string.Empty;- values.TryGetValue("mc_currency", out mc_currency);- string txn_id = string.Empty;- values.TryGetValue("txn_id", out txn_id);- string payment_type = string.Empty;- values.TryGetValue("payment_type", out payment_type);- string payer_id = string.Empty;- values.TryGetValue("payer_id", out payer_id);- string receiver_id = string.Empty;- values.TryGetValue("receiver_id", out receiver_id);- string invoice = string.Empty;- values.TryGetValue("invoice", out invoice);- string payment_fee = string.Empty;- values.TryGetValue("payment_fee", out payment_fee);+ 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:");@@ -185,29 +174,24 @@ namespace Payments.PayPalStandard.Controllers}else{- string orderNumber = string.Empty;- values.TryGetValue("custom", out orderNumber);+ var custom = QueryString("custom");Guid orderNumberGuid = Guid.Empty;try{- orderNumberGuid = new Guid(orderNumber);+ orderNumberGuid = new Guid(custom);}catch { }Order order = await _orderService.GetOrderByGuid(orderNumberGuid);if (order != null)- {- //order note- await _orderService.InsertOrderNote(new OrderNote {- Note = "PayPal PDT failed. " + response,- DisplayToCustomer = false,- CreatedOnUtc = DateTime.UtcNow,- OrderId = order.Id,- });+ {+ return RedirectToRoute("CheckoutCompleted", new { orderId = order.Id });}- return RedirectToAction("Index", "Home", new { area = "" });+ else+ return RedirectToAction("Index", "Home", new { area = "" });}}+ [HttpPost]public async Task<IActionResult> IPNHandler(){string strRequest = string.Empty;@@ -215,13 +199,13 @@ namespace Payments.PayPalStandard.Controllers{strRequest = await stream.ReadToEndAsync();}- Dictionary<string, string> values;- var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.PayPalStandard") as PayPalStandardPaymentProvider;- if (processor == null ||+ if (_paymentService.LoadPaymentMethodBySystemName("Payments.PayPalStandard") is not PayPalStandardPaymentProvider processor ||!processor.IsPaymentMethodActive(_paymentSettings))throw new GrandException("PayPal Standard module cannot be loaded");- if (processor.VerifyIpn(strRequest, out values))+ var (success, values) = await _paypalHttpClient.VerifyIpn(strRequest);++ if (success){#region valuesdouble mc_gross = 0;@@ -231,30 +215,18 @@ namespace Payments.PayPalStandard.Controllers}catch { }- string payer_status = string.Empty;- values.TryGetValue("payer_status", out payer_status);- string payment_status = string.Empty;- values.TryGetValue("payment_status", out payment_status);- string pending_reason = string.Empty;- values.TryGetValue("pending_reason", out pending_reason);- string mc_currency = string.Empty;- values.TryGetValue("mc_currency", out mc_currency);- string txn_id = string.Empty;- values.TryGetValue("txn_id", out txn_id);- string txn_type = string.Empty;- values.TryGetValue("txn_type", out txn_type);- string rp_invoice_id = string.Empty;- values.TryGetValue("rp_invoice_id", out rp_invoice_id);- string payment_type = string.Empty;- values.TryGetValue("payment_type", out payment_type);- string payer_id = string.Empty;- values.TryGetValue("payer_id", out payer_id);- string receiver_id = string.Empty;- values.TryGetValue("receiver_id", out receiver_id);- string invoice = string.Empty;- values.TryGetValue("invoice", out invoice);- string payment_fee = string.Empty;- values.TryGetValue("payment_fee", out payment_fee);+ 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("txn_type", out var txn_type);+ values.TryGetValue("rp_invoice_id", out var rp_invoice_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);#endregion@@ -406,17 +378,19 @@ namespace Payments.PayPalStandard.Controllers#endregionbreak;}+ return Ok();+}else{_logger.Error("PayPal IPN failed.", new GrandException(strRequest));}- //nothing should be rendered to visitor- return Content("");+ return BadRequest();+}- public async Task<IActionResult> CancelOrder(IFormCollection form)+ public async Task<IActionResult> CancelOrder(){var order = (await _orderService.SearchOrders(storeId: _workContext.CurrentStore.Id,customerId: _workContext.CurrentCustomer.Id, pageSize: 1)).FirstOrDefault();diff --git a/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentProvider.cs b/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentProvider.csindex 8d0cc0a6b..7526cc900 100644--- a/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentProvider.cs+++ b/src/Plugins/Payments.PayPalStandard/PayPalStandardPaymentProvider.cs@@ -92,105 +92,8 @@ namespace Payments.PayPalStandardprivate string GetPaypalUrl(){return _paypalStandardPaymentSettings.UseSandbox ?- "https://www.sandbox.paypal.com/us/cgi-bin/webscr" :- "https://www.paypal.com/us/cgi-bin/webscr";- }-- /// <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";- }-- /// <summary>- /// Gets PDT details- /// </summary>- /// <param name="tx">TX</param>- /// <param name="values">Values</param>- /// <param name="response">Response</param>- /// <returns>Result</returns>- public bool GetPdtDetails(string tx, out Dictionary<string, string> values, out string response)- {- var req = (HttpWebRequest)WebRequest.Create(GetPaypalUrl());- req.Method = WebRequestMethods.Http.Post;- req.ContentType = "application/x-www-form-urlencoded";- //now PayPal requires user-agent. otherwise, we can get 403 error- req.UserAgent = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.UserAgent];-- var formContent = $"cmd=_notify-synch&at={_paypalStandardPaymentSettings.PdtToken}&tx={tx}";- req.ContentLength = formContent.Length;-- using (var sw = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))- sw.Write(formContent);-- using (var sr = new StreamReader(req.GetResponse().GetResponseStream()))- response = WebUtility.UrlDecode(sr.ReadToEnd());-- values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);- bool firstLine = true, success = false;- foreach (var l in response.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.Substring(0, equalPox), line.Substring(equalPox + 1));- }- }-- return success;- }-- /// <summary>- /// Verifies IPN- /// </summary>- /// <param name="formString">Form string</param>- /// <param name="values">Values</param>- /// <returns>Result</returns>- public bool VerifyIpn(string formString, out Dictionary<string, string> values)- {- var req = (HttpWebRequest)WebRequest.Create(GetIpnPaypalUrl());- req.Method = WebRequestMethods.Http.Post;- req.ContentType = "application/x-www-form-urlencoded";- //now PayPal requires user-agent. otherwise, we can get 403 error- req.UserAgent = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.UserAgent];-- var formContent = $"cmd=_notify-validate&{formString}";- req.ContentLength = formContent.Length;-- using (var sw = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))- {- sw.Write(formContent);- }-- string response;- using (var sr = new StreamReader(req.GetResponse().GetResponseStream()))- {- response = WebUtility.UrlDecode(sr.ReadToEnd());- }- var success = response.Trim().Equals("VERIFIED", StringComparison.OrdinalIgnoreCase);-- 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.Substring(0, equalPox), line.Substring(equalPox + 1));- }-- return success;+ PaypalHelper.PayPalUrlSandbox :+ PaypalHelper.PayPalUrl;}/// <summary>@@ -239,7 +142,7 @@ namespace Payments.PayPalStandard["custom"] = order.OrderGuid.ToString(),//PDT, IPN and cancel URL- ["return"] = $"{storeLocation}/Plugins/PaymentPayPalStandard/PDTHandler",+ ["return"] = $"{storeLocation}/Plugins/PaymentPayPalStandard/PDTHandler?custom={order.OrderGuid}",["notify_url"] = $"{storeLocation}/Plugins/PaymentPayPalStandard/IPNHandler",["cancel_return"] = $"{storeLocation}/Plugins/PaymentPayPalStandard/CancelOrder",diff --git a/src/Plugins/Payments.PayPalStandard/PaypalHelper.cs b/src/Plugins/Payments.PayPalStandard/PaypalHelper.csindex 9c7674ee4..5f6c4e97d 100644--- a/src/Plugins/Payments.PayPalStandard/PaypalHelper.cs+++ b/src/Plugins/Payments.PayPalStandard/PaypalHelper.cs@@ -1,14 +1,21 @@using Grand.Domain.Payments;+using Microsoft.AspNetCore.Http;+using System.IO;+using System.Text;+using System.Threading.Tasks;namespace Payments.PayPalStandard{/// <summary>/// Represents paypal helper/// </summary>- public class PaypalHelper+ 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>diff --git a/src/Plugins/Payments.PayPalStandard/Services/IPaypalHttpClient.cs b/src/Plugins/Payments.PayPalStandard/Services/IPaypalHttpClient.csnew file mode 100644index 000000000..98565c5cb--- /dev/null+++ b/src/Plugins/Payments.PayPalStandard/Services/IPaypalHttpClient.cs@@ -0,0 +1,11 @@+using System.Collections.Generic;+using System.Threading.Tasks;++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.csnew file mode 100644index 000000000..e16e3ceeb--- /dev/null+++ b/src/Plugins/Payments.PayPalStandard/Services/PaypalHttpClient.cs@@ -0,0 +1,111 @@+using Grand.Business.Common.Interfaces.Logging;+using System;+using System.Collections.Generic;+using System.Net.Http;+using System.Text;+using System.Threading.Tasks;++namespace Payments.PayPalStandard.Services+{+ public class PaypalHttpClient : IPaypalHttpClient+ {+ private readonly HttpClient _client;+ private readonly PayPalStandardPaymentSettings _paypalStandardPaymentSettings;+ private readonly ILogger _logger;+ public PaypalHttpClient(HttpClient client, PayPalStandardPaymentSettings paypalStandardPaymentSettings, ILogger 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 virtual 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)+ {+ await _logger.InsertLog(Grand.Domain.Logging.LogLevel.Error, "VerifyIpn", ex.Message);+ }+++ 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.Substring(0, equalPox), line.Substring(equalPox + 1));+ }+ return (success, values);+ }++ /// <summary>+ /// Gets PayPal PDT URL+ /// </summary>+ /// <returns></returns>+ private string GetPaypalPdtUrl()+ {+ return _paypalStandardPaymentSettings.UseSandbox ?+ PaypalHelper.PayPalUrlSandbox :+ PaypalHelper.PayPalUrl;+ }++ public virtual 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)+ {+ await _logger.InsertLog(Grand.Domain.Logging.LogLevel.Error, "GetPdtDetails", ex.Message);+ }+ 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.Substring(0, equalPox), line.Substring(equalPox + 1));+ }+ }++ return (success, values, content);+ }+ }+}diff --git a/src/Plugins/Payments.PayPalStandard/StartupApplication.cs b/src/Plugins/Payments.PayPalStandard/StartupApplication.csindex 5f73b85ea..43501a8db 100644--- a/src/Plugins/Payments.PayPalStandard/StartupApplication.cs+++ b/src/Plugins/Payments.PayPalStandard/StartupApplication.cs@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;+using Payments.PayPalStandard.Services;namespace Payments.PayPalStandard{@@ -12,6 +13,7 @@ namespace Payments.PayPalStandardpublic void ConfigureServices(IServiceCollection services, IConfiguration configuration){services.AddScoped<IPaymentProvider, PayPalStandardPaymentProvider>();+ services.AddHttpClient<IPaypalHttpClient, PaypalHttpClient>();}public int Priority => 10;