/// <summary>
        /// Invoke view component
        /// </summary>
        /// <param name="widgetZone">Widget zone name</param>
        /// <param name="additionalData">Additional data</param>
        /// <returns>View component result</returns>
        public IViewComponentResult Invoke(string widgetZone, object additionalData)
        {
            if (!_paymentPluginManager.IsPluginActive(Defaults.SystemName, _workContext.CurrentCustomer, _storeContext.CurrentStore.Id))
            {
                return(Content(string.Empty));
            }

            if (!_settings.ButtonsWidgetZones.Contains(widgetZone))
            {
                return(Content(string.Empty));
            }

            if (widgetZone.Equals(PublicWidgetZones.ProductDetailsAddInfo) && additionalData is ProductDetailsModel.AddToCartModel model)
            {
                return(View("~/Plugins/Payments.PayPalSmartPaymentButtons/Views/Buttons.cshtml", (widgetZone, model.ProductId)));
            }

            if (widgetZone.Equals(PublicWidgetZones.OrderSummaryContentAfter) &&
                RouteData.Routers.OfType <INamedRouter>().Any(route => route.Name.Equals(Defaults.ShoppingCartRouteName)))
            {
                return(View("~/Plugins/Payments.PayPalSmartPaymentButtons/Views/Buttons.cshtml", (widgetZone, 0)));
            }

            if (widgetZone.Equals(PublicWidgetZones.HeaderLinksBefore) ||
                widgetZone.Equals(PublicWidgetZones.Footer))
            {
                return(View("~/Plugins/Payments.PayPalSmartPaymentButtons/Views/Logo.cshtml", widgetZone));
            }

            return(Content(string.Empty));
        }
        /// <summary>
        /// Prepare paged payment method list model
        /// </summary>
        /// <param name="searchModel">Payment method search model</param>
        /// <returns>Payment method list model</returns>
        public virtual PaymentMethodListModel PreparePaymentMethodListModel(PaymentMethodSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get payment methods
            var paymentMethods = _paymentPluginManager.LoadAllPlugins().ToPagedList(searchModel);

            //prepare grid model
            var model = new PaymentMethodListModel().PrepareToGrid(searchModel, paymentMethods, () =>
            {
                return(paymentMethods.Select(method =>
                {
                    //fill in model values from the entity
                    var paymentMethodModel = method.ToPluginModel <PaymentMethodModel>();

                    //fill in additional values (not existing in the entity)
                    paymentMethodModel.IsActive = _paymentPluginManager.IsPluginActive(method);
                    paymentMethodModel.ConfigurationUrl = method.GetConfigurationPageUrl();
                    paymentMethodModel.LogoUrl = _paymentPluginManager.GetPluginLogoUrl(method);
                    paymentMethodModel.RecurringPaymentType = _localizationService.GetLocalizedEnum(method.RecurringPaymentType);

                    return paymentMethodModel;
                }));
            });

            return(model);
        }
示例#3
0
        public async Task <IActionResult> SecurePayWebhook(SecurePayWebhookRequest request)
        {
            try
            {
                var plugin = await _paymentPluginManager.LoadPluginBySystemNameAsync(Defaults.SystemName);

                if (plugin is not YuansferPaymentProcessor processor || !_paymentPluginManager.IsPluginActive(processor))
                {
                    throw new NopException("Module could not be loaded");
                }

                if (!ModelState.IsValid)
                {
                    throw new NopException("Request is invalid");
                }

                var requestPayload = @$ "
                    Status: {request.Status}
                    Transaction number: {request.TransactionNo}
                    Order guid: {request.Reference}
                    Amount: {request.Amount}
                    Currency: {request.Currency}
                    Settlement currency: {request.SettleCurrency}
                    Time: {request.Time}
                ";

                if (request.Status != "success")
                {
                    throw new NopException($"The payment transaction failed. The tranaction status is '{request.Status}'. The payload: {requestPayload}");
                }

                var signingParams = new[]
示例#4
0
        /// <summary>
        /// Handle page rendering event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        public void HandleEvent(PageRenderingEvent eventMessage)
        {
            if (!_paymentPluginManager.IsPluginActive(BraintreePaymentDefaults.SystemName))
            {
                return;
            }

            if (!_braintreePaymentSettings.Use3DS)
            {
                return;
            }

            if (eventMessage?.Helper?.ViewContext?.ActionDescriptor == null)
            {
                return;
            }

            //add js script to one page checkout
            var routeName = eventMessage.GetRouteName() ?? string.Empty;

            if (routeName == BraintreePaymentDefaults.OnePageCheckoutRouteName)
            {
                eventMessage.Helper.AddScriptParts(ResourceLocation.Footer, BraintreePaymentDefaults.ScriptPath, excludeFromBundle: true);
                eventMessage.Helper.AddScriptParts(ResourceLocation.Footer, BraintreePaymentDefaults.ClientScriptPath, excludeFromBundle: true);
                eventMessage.Helper.AddScriptParts(ResourceLocation.Footer, BraintreePaymentDefaults.HostedFieldsScriptPath, excludeFromBundle: true);
                eventMessage.Helper.AddScriptParts(ResourceLocation.Footer, BraintreePaymentDefaults.SecureScriptPath, excludeFromBundle: true);
            }
        }
        public void HandleEvent(PageRenderingEvent eventMessage)
        {
            if (!_brainTreePaymentSettings.Use3DS)
            {
                return;
            }

            if (eventMessage?.Helper?.ViewContext?.ActionDescriptor == null)
            {
                return;
            }

            //check whether the plugin is installed and is active
            var squarePaymentMethod = _paymentPluginManager.LoadPluginBySystemName(BraintreePaymentDefaults.SystemName);

            if (!(squarePaymentMethod?.PluginDescriptor?.Installed ?? false) || !_paymentPluginManager.IsPluginActive(squarePaymentMethod))
            {
                return;
            }

            //add js script to one page checkout
            if (eventMessage.GetRouteNames().Any(r => r.Equals("CheckoutOnePage")))
            {
                eventMessage.Helper.AddScriptParts(ResourceLocation.Footer, BraintreePaymentDefaults.BraintreeScriptPath, excludeFromBundle: true);
                eventMessage.Helper.AddScriptParts(ResourceLocation.Footer, BraintreePaymentDefaults.BraintreeClientScriptPath, excludeFromBundle: true);
                eventMessage.Helper.AddScriptParts(ResourceLocation.Footer, BraintreePaymentDefaults.BraintreeHostedFieldsScriptPath, excludeFromBundle: true);
                eventMessage.Helper.AddScriptParts(ResourceLocation.Footer, BraintreePaymentDefaults.Braintree3DSecureScriptPath, excludeFromBundle: true);
            }
        }
        /// <summary>
        /// Prepare plugins enabled warning model
        /// </summary>
        /// <param name="models">List of system warning models</param>
        protected virtual void PreparePluginsEnabledWarningModel(List <SystemWarningModel> models)
        {
            var plugins = _pluginService.GetPlugins <IPlugin>();

            var notEnabled = new List <string>();

            foreach (var plugin in plugins)
            {
                var isEnabled = true;

                switch (plugin)
                {
                case IPaymentMethod paymentMethod:
                    isEnabled = _paymentPluginManager.IsPluginActive(paymentMethod);
                    break;

                case IShippingRateComputationMethod shippingRateComputationMethod:
                    isEnabled = _shippingPluginManager.IsPluginActive(shippingRateComputationMethod);
                    break;

                case IPickupPointProvider pickupPointProvider:
                    isEnabled = _pickupPluginManager.IsPluginActive(pickupPointProvider);
                    break;

                case ITaxProvider taxProvider:
                    isEnabled = _taxPluginManager.IsPluginActive(taxProvider);
                    break;

                case IExternalAuthenticationMethod externalAuthenticationMethod:
                    isEnabled = _authenticationPluginManager.IsPluginActive(externalAuthenticationMethod);
                    break;

                case IWidgetPlugin widgetPlugin:
                    isEnabled = _widgetPluginManager.IsPluginActive(widgetPlugin);
                    break;

                case IExchangeRateProvider exchangeRateProvider:
                    isEnabled = _exchangeRatePluginManager.IsPluginActive(exchangeRateProvider);
                    break;
                }

                if (isEnabled)
                {
                    continue;
                }

                notEnabled.Add(plugin.PluginDescriptor.FriendlyName);
            }

            if (notEnabled.Any())
            {
                models.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Warning,
                    Text  = $"{_localizationService.GetResource("Admin.System.Warnings.PluginNotEnabled")}: {string.Join(", ", notEnabled)}"
                });
            }
        }
        /// <summary>
        /// Prepare plugin model properties of the installed plugin
        /// </summary>
        /// <param name="model">Plugin model</param>
        /// <param name="plugin">Plugin</param>
        protected virtual void PrepareInstalledPluginModel(PluginModel model, IPlugin plugin)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (plugin == null)
            {
                throw new ArgumentNullException(nameof(plugin));
            }

            //prepare configuration URL
            model.ConfigurationUrl = plugin.GetConfigurationPageUrl();

            //prepare enabled/disabled (only for some plugin types)
            model.CanChangeEnabled = true;
            switch (plugin)
            {
            case IPaymentMethod paymentMethod:
                model.IsEnabled = _paymentPluginManager.IsPluginActive(paymentMethod);
                break;

            case IShippingRateComputationMethod shippingRateComputationMethod:
                model.IsEnabled = _shippingPluginManager.IsPluginActive(shippingRateComputationMethod);
                break;

            case IPickupPointProvider pickupPointProvider:
                model.IsEnabled = _pickupPluginManager.IsPluginActive(pickupPointProvider);
                break;

            case ITaxProvider taxProvider:
                model.IsEnabled = _taxPluginManager.IsPluginActive(taxProvider);
                break;

            case IExternalAuthenticationMethod externalAuthenticationMethod:
                model.IsEnabled = _authenticationPluginManager.IsPluginActive(externalAuthenticationMethod);
                break;

            case IMultiFactorAuthenticationMethod multiFactorAuthenticationMethod:
                model.IsEnabled = _multiFactorAuthenticationPluginManager.IsPluginActive(multiFactorAuthenticationMethod);
                break;

            case IWidgetPlugin widgetPlugin:
                model.IsEnabled = _widgetPluginManager.IsPluginActive(widgetPlugin);
                break;

            default:
                model.CanChangeEnabled = false;
                break;
            }
        }
        /// <summary>
        /// Handle page rendering event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        public void HandleEvent(PageRenderingEvent eventMessage)
        {
            //check whether the plugin is active
            if (!_paymentPluginManager.IsPluginActive(SquarePaymentDefaults.SystemName))
            {
                return;
            }

            //add js script to one page checkout
            if (eventMessage.GetRouteNames().Any(routeName => routeName.Equals(SquarePaymentDefaults.OnePageCheckoutRouteName)))
            {
                eventMessage.Helper?.AddScriptParts(ResourceLocation.Footer, SquarePaymentDefaults.PaymentFormScriptPath, excludeFromBundle: true);
            }
        }
        public void HandleEvent(PageRenderingEvent eventMessage)
        {
            //check whether the plugin is active
            if (!_paymentPluginManager.IsPluginActive("Payments.PayPalPlus"))
            {
                return;
            }

            //add js script to one page checkout
            if (eventMessage.GetRouteNames().Any(routeName => routeName.Equals("CheckoutOnePage")))
            {
                eventMessage.Helper?.AddScriptParts(ResourceLocation.Footer, "https://www.paypalobjects.com/webstatic/ppplusdcc/ppplusdcc.min.js", excludeFromBundle: true);
            }
        }
        /// <summary>
        /// Invoke view component
        /// </summary>
        /// <param name="widgetZone">Widget zone name</param>
        /// <param name="additionalData">Additional data</param>
        /// <returns>View component result</returns>
        public IViewComponentResult Invoke(string widgetZone, object additionalData)
        {
            if (!_paymentPluginManager.IsPluginActive(Defaults.SystemName, _workContext.CurrentCustomer, _storeContext.CurrentStore.Id))
            {
                return(Content(string.Empty));
            }

            var script = widgetZone.Equals(PublicWidgetZones.HeaderLinksBefore) && _settings.DisplayLogoInHeaderLinks
                ? _settings.LogoInHeaderLinks
                : (widgetZone.Equals(PublicWidgetZones.Footer) && _settings.DisplayLogoInFooter
                ? _settings.LogoInFooter
                : null);

            return(new HtmlContentViewComponentResult(new HtmlString(script ?? string.Empty)));
        }
示例#11
0
        /// <summary>
        /// Handle page rendering event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        public void HandleEvent(PageRenderingEvent eventMessage)
        {
            if (eventMessage?.Helper?.ViewContext?.ActionDescriptor == null)
            {
                return;
            }

            //check whether the plugin is active
            if (!_paymentPluginManager.IsPluginActive(VivaDefaults.SystemName))
            {
                return;
            }

            //add js script to one page checkout
            if (eventMessage.GetRouteNames().Any(routeName => routeName.Equals("CheckoutOnePage")))
            {
                eventMessage.Helper?.AddScriptParts(ResourceLocation.Footer, "https://www.vivapayments.com/web/checkout/js", excludeFromBundle: true);
            }
        }
示例#12
0
        /// <summary>
        /// Executes a task
        /// </summary>
        public void Execute()
        {
            //whether plugin is active
            if (!_paymentPluginManager.IsPluginActive(SquarePaymentDefaults.SystemName))
            {
                return;
            }

            //do not execute for sandbox environment
            if (_squarePaymentSettings.UseSandbox)
            {
                return;
            }

            try
            {
                var storeId = _storeContext.CurrentStore.Id;

                //get the new access token
                var(newAccessToken, refreshToken) = _squarePaymentManager.RenewAccessToken(storeId);
                if (string.IsNullOrEmpty(newAccessToken) || string.IsNullOrEmpty(refreshToken))
                {
                    throw new NopException("No service response");
                }

                //if access token successfully received, save it for the further usage
                _squarePaymentSettings.AccessToken  = newAccessToken;
                _squarePaymentSettings.RefreshToken = refreshToken;

                _settingService.SaveSetting(_squarePaymentSettings, x => x.AccessToken, storeId, false);
                _settingService.SaveSetting(_squarePaymentSettings, x => x.RefreshToken, storeId, false);

                _settingService.ClearCache();

                //log information about the successful renew of the access token
                _logger.Information(_localizationService.GetResource("Plugins.Payments.Square.RenewAccessToken.Success"));
            }
            catch (Exception exception)
            {
                //log error on renewing of the access token
                _logger.Error(_localizationService.GetResource("Plugins.Payments.Square.RenewAccessToken.Error"), exception);
            }
        }
        /// <summary>
        /// Invoke view component
        /// </summary>
        /// <param name="widgetZone">Widget zone name</param>
        /// <param name="additionalData">Additional data</param>
        /// <returns>View component result</returns>
        public IViewComponentResult Invoke(string widgetZone, object additionalData)
        {
            if (!_paymentPluginManager.IsPluginActive(Defaults.SystemName, _workContext.CurrentCustomer, _storeContext.CurrentStore.Id))
            {
                return(Content(string.Empty));
            }

            if (string.IsNullOrEmpty(_settings.ClientId))
            {
                return(Content(string.Empty));
            }

            if (!widgetZone.Equals(PublicWidgetZones.CheckoutPaymentInfoTop) &&
                !widgetZone.Equals(PublicWidgetZones.OpcContentBefore) &&
                !widgetZone.Equals(PublicWidgetZones.ProductDetailsTop) &&
                !widgetZone.Equals(PublicWidgetZones.OrderSummaryContentBefore))
            {
                return(Content(string.Empty));
            }

            if (widgetZone.Equals(PublicWidgetZones.OrderSummaryContentBefore))
            {
                if (!_settings.DisplayButtonsOnShoppingCart)
                {
                    return(Content(string.Empty));
                }

                var routeName = HttpContext.GetEndpoint()?.Metadata.GetMetadata <RouteNameMetadata>()?.RouteName;
                if (routeName != Defaults.ShoppingCartRouteName)
                {
                    return(Content(string.Empty));
                }
            }

            if (widgetZone.Equals(PublicWidgetZones.ProductDetailsTop) && !_settings.DisplayButtonsOnProductDetails)
            {
                return(Content(string.Empty));
            }

            var(script, _) = _serviceManager.GetScript(_settings);
            return(new HtmlContentViewComponentResult(new HtmlString(script ?? string.Empty)));
        }
示例#14
0
        /// <summary>
        /// Handle page rendering event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        public void HandleEvent(PageRenderingEvent eventMessage)
        {
            if (eventMessage?.Helper?.ViewContext?.ActionDescriptor == null)
            {
                return;
            }

            //check whether the plugin is active
            if (!_paymentPluginManager.IsPluginActive(QualpayDefaults.SystemName))
            {
                return;
            }

            //add Embedded Fields sсript and styles to the one page checkout
            if (eventMessage.GetRouteName()?.Equals(QualpayDefaults.OnePageCheckoutRouteName) ?? false)
            {
                eventMessage.Helper.AddScriptParts(ResourceLocation.Footer, QualpayDefaults.EmbeddedFieldsScriptPath, excludeFromBundle: true);
                eventMessage.Helper.AddCssFileParts(QualpayDefaults.EmbeddedFieldsStylePath, excludeFromBundle: true);
            }
        }
示例#15
0
        /// <summary>
        /// Invoke view component
        /// </summary>
        /// <param name="widgetZone">Widget zone name</param>
        /// <param name="additionalData">Additional data</param>
        /// <returns>View component result</returns>
        public IViewComponentResult Invoke(string widgetZone, object additionalData)
        {
            if (!_paymentPluginManager.IsPluginActive(Defaults.SystemName))
            {
                return(Content(string.Empty));
            }

            if (!widgetZone.Equals(AdminWidgetZones.OrderDetailsBlock) || !(additionalData is OrderModel model))
            {
                return(Content(string.Empty));
            }

            if (!model.PaymentMethod.Equals(Defaults.SystemName) &&
                !model.PaymentMethod.Equals(_paymentPluginManager.LoadPluginBySystemName(Defaults.SystemName)?.PluginDescriptor.FriendlyName))
            {
                return(Content(string.Empty));
            }

            return(View("~/Plugins/Payments.Skrill/Views/RefundHints.cshtml"));
        }
示例#16
0
        /// <returns>A task that represents the asynchronous operation</returns>
        public virtual async Task <IActionResult> MethodUpdate(PaymentMethodModel model)
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManagePaymentMethods))
            {
                return(AccessDeniedView());
            }

            var pm = await _paymentPluginManager.LoadPluginBySystemNameAsync(model.SystemName);

            if (_paymentPluginManager.IsPluginActive(pm))
            {
                if (!model.IsActive)
                {
                    //mark as disabled
                    _paymentSettings.ActivePaymentMethodSystemNames.Remove(pm.PluginDescriptor.SystemName);
                    await _settingService.SaveSettingAsync(_paymentSettings);
                }
            }
            else
            {
                if (model.IsActive)
                {
                    //mark as active
                    _paymentSettings.ActivePaymentMethodSystemNames.Add(pm.PluginDescriptor.SystemName);
                    await _settingService.SaveSettingAsync(_paymentSettings);
                }
            }

            var pluginDescriptor = pm.PluginDescriptor;

            pluginDescriptor.FriendlyName = model.FriendlyName;
            pluginDescriptor.DisplayOrder = model.DisplayOrder;

            //update the description file
            pluginDescriptor.Save();

            //raise event
            await _eventPublisher.PublishAsync(new PluginUpdatedEvent(pluginDescriptor));

            return(new NullJsonResult());
        }
示例#17
0
        /// <summary>
        /// Invoke view component
        /// </summary>
        /// <param name="widgetZone">Widget zone name</param>
        /// <param name="additionalData">Additional data</param>
        /// <returns>View component result</returns>
        public IViewComponentResult Invoke(string widgetZone, object additionalData)
        {
            if (!_paymentPluginManager.IsPluginActive(Defaults.SystemName, _workContext.CurrentCustomer, _storeContext.CurrentStore.Id))
            {
                return(Content(string.Empty));
            }

            if (!widgetZone.Equals(PublicWidgetZones.CheckoutPaymentInfoTop) &&
                !widgetZone.Equals(PublicWidgetZones.OpcContentBefore) &&
                !widgetZone.Equals(PublicWidgetZones.ProductDetailsTop) &&
                !widgetZone.Equals(PublicWidgetZones.OrderSummaryContentBefore))
            {
                return(Content(string.Empty));
            }

            var model = new ScriptModel {
                ScriptUrl = _serviceManager.GetScriptUrl()
            };

            return(View("~/Plugins/Payments.PayPalSmartPaymentButtons/Views/Script.cshtml", model));
        }
示例#18
0
        /// <summary>
        /// Invoke view component
        /// </summary>
        /// <param name="widgetZone">Widget zone name</param>
        /// <param name="additionalData">Additional data</param>
        /// <returns>View component result</returns>
        public IViewComponentResult Invoke(string widgetZone, object additionalData)
        {
            if (!_paymentPluginManager.IsPluginActive(Defaults.SystemName, _workContext.CurrentCustomer, _storeContext.CurrentStore.Id))
            {
                return(Content(string.Empty));
            }

            if (string.IsNullOrEmpty(_settings.ClientId))
            {
                return(Content(string.Empty));
            }

            if (!widgetZone.Equals(PublicWidgetZones.ProductDetailsAddInfo) && !widgetZone.Equals(PublicWidgetZones.OrderSummaryContentAfter))
            {
                return(Content(string.Empty));
            }

            if (widgetZone.Equals(PublicWidgetZones.OrderSummaryContentAfter))
            {
                if (!_settings.DisplayButtonsOnShoppingCart)
                {
                    return(Content(string.Empty));
                }

                var routeName = HttpContext.GetEndpoint()?.Metadata.GetMetadata <RouteNameMetadata>()?.RouteName;
                if (routeName != Defaults.ShoppingCartRouteName)
                {
                    return(Content(string.Empty));
                }
            }

            if (widgetZone.Equals(PublicWidgetZones.ProductDetailsAddInfo) && !_settings.DisplayButtonsOnProductDetails)
            {
                return(Content(string.Empty));
            }

            var productId = additionalData is ProductDetailsModel.AddToCartModel model ? model.ProductId : 0;

            return(View("~/Plugins/Payments.PayPalSmartPaymentButtons/Views/Buttons.cshtml", (widgetZone, productId)));
        }
        /// <summary>
        /// Invoke view component
        /// </summary>
        /// <param name="widgetZone">Widget zone name</param>
        /// <param name="additionalData">Additional data</param>
        /// <returns>View component result</returns>
        public IViewComponentResult Invoke(string widgetZone, object additionalData)
        {
            if (!widgetZone?.Equals(AdminWidgetZones.CustomerDetailsBlock, StringComparison.InvariantCultureIgnoreCase) ?? true)
            {
                return(Content(string.Empty));
            }

            //check whether the payment plugin is active
            if (!_paymentPluginManager.IsPluginActive(QualpayDefaults.SystemName))
            {
                return(Content(string.Empty));
            }

            //whether Qualpay Customer Vault feature is enabled
            if (!_qualpaySettings.UseCustomerVault)
            {
                return(Content(string.Empty));
            }

            //get the view model
            if (!(additionalData is CustomerModel customerModel))
            {
                return(Content(string.Empty));
            }

            //check whether a customer exists and isn't guest
            var customer = _customerService.GetCustomerById(customerModel.Id);

            if (customer?.IsGuest() ?? true)
            {
                return(Content(string.Empty));
            }

            var model = _qualpayCustomerModelFactory.PrepareQualpayCustomerModel(customerModel, customer);

            return(View("~/Plugins/Payments.Qualpay/Views/Customer/_CreateOrUpdate.Qualpay.cshtml", model));
        }
        public ActionResult Return(IpnModel model)
        {
            var processor =
                _paymentPluginManager.LoadPluginBySystemName("Payments.CCAvenue") as CCAvenuePaymentProcessor;

            if (processor == null || !_paymentPluginManager.IsPluginActive(processor) ||
                !processor.PluginDescriptor.Installed)
            {
                throw new NopException("CCAvenue module cannot be loaded");
            }

            //assign following values to send it to verifychecksum function.
            if (string.IsNullOrWhiteSpace(_ccAvenuePaymentSettings.Key))
            {
                throw new NopException("CCAvenue key is not set");
            }

            var workingKey  = _ccAvenuePaymentSettings.Key;
            var ccaCrypto   = new CCACrypto();
            var encResponse = ccaCrypto.Decrypt(model.Form["encResp"], workingKey);
            var paramList   = new NameValueCollection();
            var segments    = encResponse.Split('&');

            foreach (var seg in segments)
            {
                var parts = seg.Split('=');

                if (parts.Length <= 0)
                {
                    continue;
                }

                paramList.Add(parts[0].Trim(), parts[1].Trim());
            }

            var sb = new StringBuilder();

            sb.AppendLine("CCAvenue:");
            for (var i = 0; i < paramList.Count; i++)
            {
                sb.AppendLine(paramList.Keys[i] + " = " + paramList[i]);
            }

            var orderId  = paramList["Order_Id"];
            var authDesc = paramList["order_status"];

            var order = _orderService.GetOrderById(Convert.ToInt32(orderId));

            if (order == null)
            {
                return(RedirectToAction("Index", "Home", new { area = string.Empty }));
            }

            order.OrderNotes.Add(new OrderNote
            {
                Note = sb.ToString(),
                DisplayToCustomer = false,
                CreatedOnUtc      = DateTime.UtcNow
            });

            //var merchantId = Params["Merchant_Id"];
            //var Amount = Params["Amount"];
            //var myUtility = new CCAvenueHelper();
            //var checksum = myUtility.verifychecksum(merchantId, orderId, Amount, AuthDesc, _ccAvenuePaymentSettings.Key, checksum);

            if (!authDesc.Equals("Success", StringComparison.InvariantCultureIgnoreCase))
            {
                return(RedirectToRoute("OrderDetails", new { orderId = order.Id }));
            }

            //here you need to put in the routines for a successful transaction such as sending an email to customer,
            //setting database status, informing logistics etc etc

            if (_orderProcessingService.CanMarkOrderAsPaid(order))
            {
                _orderProcessingService.MarkOrderAsPaid(order);
            }

            //thank you for shopping with us. Your credit card has been charged and your transaction is successful
            return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
        }
        public ActionResult Return()
        {
            var processor = _paymentPluginManager.LoadPluginBySystemName("Payments.Paytm") as PaytmPaymentProcessor;

            if (processor == null ||
                !_paymentPluginManager.IsPluginActive(processor) || !processor.PluginDescriptor.Installed)
            {
                throw new NopException("Paytm module cannot be loaded");
            }


            var    myUtility = new PaytmHelper();
            string orderId, amount, authDesc, resCode;
            bool   checkSumMatch = false;

            //Assign following values to send it to verifychecksum function.
            if (String.IsNullOrWhiteSpace(_paytmPaymentSettings.MerchantKey))
            {
                throw new NopException("Paytm key is not set");
            }

            string workingKey    = _paytmPaymentSettings.MerchantKey;
            string paytmChecksum = null;

            Dictionary <string, string> parameters = new Dictionary <string, string>();

            if (Request.Form.Keys.Count > 0)
            {
                foreach (string key in Request.Form.Keys)
                {
                    if (Request.Form[key].Contains("|"))
                    {
                        parameters.Add(key.Trim(), "");
                    }
                    else
                    {
                        parameters.Add(key.Trim(), Request.Form[key]);
                    }
                }

                if (parameters.ContainsKey("CHECKSUMHASH"))
                {
                    paytmChecksum = parameters["CHECKSUMHASH"];
                    parameters.Remove("CHECKSUMHASH");
                }
                if (!string.IsNullOrEmpty(paytmChecksum) && paytm.CheckSum.verifyCheckSum(workingKey, parameters, paytmChecksum))
                {
                    checkSumMatch = true;
                }
            }

            orderId  = parameters["ORDERID"];
            amount   = parameters["TXNAMOUNT"];
            resCode  = parameters["RESPCODE"];
            authDesc = parameters["STATUS"];

            var order = _orderService.GetOrderById(Convert.ToInt32(orderId));

            if (checkSumMatch == true)
            {
                if (resCode == "01" && authDesc == "TXN_SUCCESS")
                {
                    if (TxnStatus(orderId, order.OrderTotal.ToString("0.00")))
                    {
                        if (_orderProcessingService.CanMarkOrderAsPaid(order))
                        {
                            _orderProcessingService.MarkOrderAsPaid(order);
                        }
                        return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                    }
                    else
                    {
                        return(Content("Amount Mismatch"));
                    }
                }
                else if (authDesc == "TXN_FAILURE")
                {
                    _orderProcessingService.CancelOrder(order, false);
                    order.OrderStatus = OrderStatus.Cancelled;
                    _orderService.UpdateOrder(order);
                    return(RedirectToRoute("OrderDetails", new { orderId = order.Id }));
                }
                else
                {
                    return(Content("Security Error. Illegal access detected"));
                }
            }
            else if (string.IsNullOrEmpty(paytmChecksum))
            {
                return(Content("Please Contact Customer Care"));
            }
            else
            {
                return(Content("Security Error. Illegal access detected, Checksum failed"));
            }
        }
        public IActionResult IPNHandler()
        {
            byte[] parameters;
            using (var stream = new MemoryStream())
            {
                this.Request.Body.CopyTo(stream);
                parameters = stream.ToArray();
            }
            var strRequest = Encoding.ASCII.GetString(parameters);

            var processor = _paymentPluginManager.LoadPluginBySystemName("Payments.Paytm") as PaytmPaymentProcessor;

            if (processor == null ||
                !_paymentPluginManager.IsPluginActive(processor) || !processor.PluginDescriptor.Installed)
            {
                throw new NopException("Paytm Standard module cannot be loaded");
            }

            if (processor.VerifyIpn(strRequest, out Dictionary <string, string> values))
            {
                #region values
                var mc_gross = decimal.Zero;
                try
                {
                    mc_gross = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
                }
                catch { }

                values.TryGetValue("payer_status", out string payer_status);
                values.TryGetValue("payment_status", out string payment_status);
                values.TryGetValue("pending_reason", out string pending_reason);
                values.TryGetValue("mc_currency", out string mc_currency);
                values.TryGetValue("txn_id", out string txn_id);
                values.TryGetValue("txn_type", out string txn_type);
                values.TryGetValue("rp_invoice_id", out string rp_invoice_id);
                values.TryGetValue("payment_type", out string payment_type);
                values.TryGetValue("payer_id", out string payer_id);
                values.TryGetValue("receiver_id", out string receiver_id);
                values.TryGetValue("invoice", out string _);
                values.TryGetValue("payment_fee", out string payment_fee);

                #endregion

                var sb = new StringBuilder();
                sb.AppendLine("Paytm IPN:");
                foreach (var kvp in values)
                {
                    sb.AppendLine(kvp.Key + ": " + kvp.Value);
                }

                var newPaymentStatus = PaytmHelper.GetPaymentStatus(payment_status, pending_reason);
                sb.AppendLine("New payment status: " + newPaymentStatus);

                switch (txn_type)
                {
                case "recurring_payment_profile_created":
                    //do nothing here
                    break;

                    #region Recurring payment
                case "recurring_payment":
                {
                    var orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(rp_invoice_id);
                    }
                    catch
                    {
                    }

                    var initialOrder = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (initialOrder != null)
                    {
                        var recurringPayments = _orderService.SearchRecurringPayments(initialOrderId: initialOrder.Id);
                        foreach (var rp in recurringPayments)
                        {
                            switch (newPaymentStatus)
                            {
                            case PaymentStatus.Authorized:
                            case PaymentStatus.Paid:
                            {
                                var recurringPaymentHistory = rp.RecurringPaymentHistory;
                                if (!recurringPaymentHistory.Any())
                                {
                                    //first payment
                                    var rph = new RecurringPaymentHistory
                                    {
                                        RecurringPaymentId = rp.Id,
                                        OrderId            = initialOrder.Id,
                                        CreatedOnUtc       = DateTime.UtcNow
                                    };
                                    rp.RecurringPaymentHistory.Add(rph);
                                    _orderService.UpdateRecurringPayment(rp);
                                }
                                else
                                {
                                    //next payments
                                    var processPaymentResult = new ProcessPaymentResult
                                    {
                                        NewPaymentStatus = newPaymentStatus
                                    };
                                    if (newPaymentStatus == PaymentStatus.Authorized)
                                    {
                                        processPaymentResult.AuthorizationTransactionId = txn_id;
                                    }
                                    else
                                    {
                                        processPaymentResult.CaptureTransactionId = txn_id;
                                    }

                                    _orderProcessingService.ProcessNextRecurringPayment(rp, processPaymentResult);
                                }
                            }
                            break;

                            case PaymentStatus.Voided:
                                //failed payment
                                var failedPaymentResult = new ProcessPaymentResult
                                {
                                    Errors = new[] { $"Paytm IPN. Recurring payment is {payment_status} ." },
                                    RecurringPaymentFailed = true
                                };
                                _orderProcessingService.ProcessNextRecurringPayment(rp, failedPaymentResult);
                                break;
                            }
                        }

                        //this.OrderService.InsertOrderNote(newOrder.OrderId, sb.ToString(), DateTime.UtcNow);
                        _logger.Information("Paytm IPN. Recurring info", new NopException(sb.ToString()));
                    }
                    else
                    {
                        _logger.Error("Paytm IPN. Order is not found", new NopException(sb.ToString()));
                    }
                }
                break;

                case "recurring_payment_failed":
                    if (Guid.TryParse(rp_invoice_id, out Guid orderGuid))
                    {
                        var initialOrder = _orderService.GetOrderByGuid(orderGuid);
                        if (initialOrder != null)
                        {
                            var recurringPayment = _orderService.SearchRecurringPayments(initialOrderId: initialOrder.Id).FirstOrDefault();
                            //failed payment
                            if (recurringPayment != null)
                            {
                                _orderProcessingService.ProcessNextRecurringPayment(recurringPayment, new ProcessPaymentResult {
                                    Errors = new[] { txn_type }, RecurringPaymentFailed = true
                                });
                            }
                        }
                    }
                    break;

                    #endregion
                default:
                    #region Standard payment
                {
                    values.TryGetValue("custom", out string orderNumber);
                    var orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(orderNumber);
                    }
                    catch
                    {
                    }

                    var order = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (order != null)
                    {
                        //order note
                        order.OrderNotes.Add(new OrderNote
                            {
                                Note = sb.ToString(),
                                DisplayToCustomer = false,
                                CreatedOnUtc      = DateTime.UtcNow
                            });
                        _orderService.UpdateOrder(order);

                        switch (newPaymentStatus)
                        {
                        case PaymentStatus.Pending:
                        {
                        }
                        break;

                        case PaymentStatus.Authorized:
                        {
                            //validate order total
                            if (Math.Round(mc_gross, 2).Equals(Math.Round(order.OrderTotal, 2)))
                            {
                                //valid
                                if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                                {
                                    _orderProcessingService.MarkAsAuthorized(order);
                                }
                            }
                            else
                            {
                                //not valid
                                var errorStr =
                                    $"Paytm IPN. Returned order total {mc_gross} doesn't equal order total {order.OrderTotal}. Order# {order.Id}.";
                                //log
                                _logger.Error(errorStr);
                                //order note
                                order.OrderNotes.Add(new OrderNote
                                        {
                                            Note = errorStr,
                                            DisplayToCustomer = false,
                                            CreatedOnUtc      = DateTime.UtcNow
                                        });
                                _orderService.UpdateOrder(order);
                            }
                        }
                        break;

                        case PaymentStatus.Paid:
                        {
                            //validate order total
                            if (Math.Round(mc_gross, 2).Equals(Math.Round(order.OrderTotal, 2)))
                            {
                                //valid
                                if (_orderProcessingService.CanMarkOrderAsPaid(order))
                                {
                                    order.AuthorizationTransactionId = txn_id;
                                    _orderService.UpdateOrder(order);

                                    _orderProcessingService.MarkOrderAsPaid(order);
                                }
                            }
                            else
                            {
                                //not valid
                                var errorStr =
                                    $"Paytm IPN. Returned order total {mc_gross} doesn't equal order total {order.OrderTotal}. Order# {order.Id}.";
                                //log
                                _logger.Error(errorStr);
                                //order note
                                order.OrderNotes.Add(new OrderNote
                                        {
                                            Note = errorStr,
                                            DisplayToCustomer = false,
                                            CreatedOnUtc      = DateTime.UtcNow
                                        });
                                _orderService.UpdateOrder(order);
                            }
                        }
                        break;

                        case PaymentStatus.Refunded:
                        {
                            var totalToRefund = Math.Abs(mc_gross);
                            if (totalToRefund > 0 && Math.Round(totalToRefund, 2).Equals(Math.Round(order.OrderTotal, 2)))
                            {
                                //refund
                                if (_orderProcessingService.CanRefundOffline(order))
                                {
                                    _orderProcessingService.RefundOffline(order);
                                }
                            }
                            else
                            {
                                //partial refund
                                if (_orderProcessingService.CanPartiallyRefundOffline(order, totalToRefund))
                                {
                                    _orderProcessingService.PartiallyRefundOffline(order, totalToRefund);
                                }
                            }
                        }
                        break;

                        case PaymentStatus.Voided:
                        {
                            if (_orderProcessingService.CanVoidOffline(order))
                            {
                                _orderProcessingService.VoidOffline(order);
                            }
                        }
                        break;

                        default:
                            break;
                        }
                    }
                    else
                    {
                        _logger.Error("Paytm IPN. Order is not found", new NopException(sb.ToString()));
                    }
                }
                    #endregion
                    break;
                }
            }
            else
            {
                _logger.Error("Paytm IPN failed.", new NopException(strRequest));
            }

            //nothing should be rendered to visitor
            return(Content(""));
        }
示例#23
0
        public async Task <IActionResult> IPNHandler()
        {
            await using var stream = new MemoryStream();
            await Request.Body.CopyToAsync(stream);

            var strRequest = Encoding.ASCII.GetString(stream.ToArray());

            if (await _paymentPluginManager.LoadPluginBySystemNameAsync("Payments.Paytm") is not PaytmPaymentProcessor processor || !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new NopException("Paytm module cannot be loaded");
            }

            var(result, values) = await processor.VerifyIpnAsync(strRequest);

            if (!result)
            {
                await _logger.ErrorAsync("Paytm IPN failed.", new NopException(strRequest));

                //nothing should be rendered to visitor
                return(Ok());
            }

            var mcGross = decimal.Zero;

            try
            {
                mcGross = decimal.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", out var txnId);
            values.TryGetValue("txn_type", out var txnType);
            values.TryGetValue("rp_invoice_id", out var rpInvoiceId);

            var sb = new StringBuilder();

            sb.AppendLine("Paytm IPN:");
            foreach (var kvp in values)
            {
                sb.AppendLine(kvp.Key + ": " + kvp.Value);
            }

            var newPaymentStatus = PaytmHelper.GetPaymentStatus(paymentStatus, pendingReason);

            sb.AppendLine("New payment status: " + newPaymentStatus);

            var ipnInfo = sb.ToString();

            switch (txnType)
            {
            case "recurring_payment":
                await ProcessRecurringPaymentAsync(rpInvoiceId, newPaymentStatus, txnId, ipnInfo);

                break;

            case "recurring_payment_failed":
                if (Guid.TryParse(rpInvoiceId, out var orderGuid))
                {
                    var order = await _orderService.GetOrderByGuidAsync(orderGuid);

                    if (order != null)
                    {
                        var recurringPayment = (await _orderService.SearchRecurringPaymentsAsync(initialOrderId: order.Id))
                                               .FirstOrDefault();
                        //failed payment
                        if (recurringPayment != null)
                        {
                            await _orderProcessingService.ProcessNextRecurringPaymentAsync(recurringPayment,
                                                                                           new ProcessPaymentResult
                            {
                                Errors = new[] { txnType },
                                RecurringPaymentFailed = true
                            });
                        }
                    }
                }

                break;

            default:
                values.TryGetValue("custom", out var orderNumber);
                await ProcessPaymentAsync(orderNumber, ipnInfo, newPaymentStatus, mcGross, txnId);

                break;
            }

            //nothing should be rendered to visitor
            return(Ok());
        }
示例#24
0
        public IActionResult PDTHandler()
        {
            var tx = _webHelper.QueryString <string>("tx");

            if (!(_paymentPluginManager.LoadPluginBySystemName("Payments.PayPalStandard") is PayPalStandardPaymentProcessor processor) || !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new NopException("PayPal Standard module cannot be loaded");
            }

            if (processor.GetPdtDetails(tx, out var values, out var response))
            {
                values.TryGetValue("custom", out var orderNumber);
                var orderNumberGuid = Guid.Empty;
                try
                {
                    orderNumberGuid = new Guid(orderNumber);
                }
                catch
                {
                    // ignored
                }

                var order = _orderService.GetOrderByGuid(orderNumberGuid);

                if (order == null)
                {
                    return(RedirectToAction("Index", "Home", new { area = string.Empty }));
                }

                var mcGross = decimal.Zero;

                try
                {
                    mcGross = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
                }
                catch (Exception exc)
                {
                    _logger.Error("PayPal PDT. Error getting mc_gross", exc);
                }

                values.TryGetValue("payer_status", out var payerStatus);
                values.TryGetValue("payment_status", out var paymentStatus);
                values.TryGetValue("pending_reason", out var pendingReason);
                values.TryGetValue("mc_currency", out var mcCurrency);
                values.TryGetValue("txn_id", out var txnId);
                values.TryGetValue("payment_type", out var paymentType);
                values.TryGetValue("payer_id", out var payerId);
                values.TryGetValue("receiver_id", out var receiverId);
                values.TryGetValue("invoice", out var invoice);
                values.TryGetValue("payment_fee", out var paymentFee);

                var sb = new StringBuilder();
                sb.AppendLine("PayPal PDT:");
                sb.AppendLine("mc_gross: " + mcGross);
                sb.AppendLine("Payer status: " + payerStatus);
                sb.AppendLine("Payment status: " + paymentStatus);
                sb.AppendLine("Pending reason: " + pendingReason);
                sb.AppendLine("mc_currency: " + mcCurrency);
                sb.AppendLine("txn_id: " + txnId);
                sb.AppendLine("payment_type: " + paymentType);
                sb.AppendLine("payer_id: " + payerId);
                sb.AppendLine("receiver_id: " + receiverId);
                sb.AppendLine("invoice: " + invoice);
                sb.AppendLine("payment_fee: " + paymentFee);

                var newPaymentStatus = PayPalHelper.GetPaymentStatus(paymentStatus, string.Empty);
                sb.AppendLine("New payment status: " + newPaymentStatus);

                //order note
                _orderService.InsertOrderNote(new OrderNote
                {
                    OrderId           = order.Id,
                    Note              = sb.ToString(),
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });

                //validate order total
                var orderTotalSentToPayPal = _genericAttributeService.GetAttribute <decimal?>(order, PayPalHelper.OrderTotalSentToPayPal);
                if (orderTotalSentToPayPal.HasValue && mcGross != orderTotalSentToPayPal.Value)
                {
                    var errorStr = $"PayPal PDT. Returned order total {mcGross} doesn't equal order total {order.OrderTotal}. Order# {order.Id}.";
                    //log
                    _logger.Error(errorStr);
                    //order note
                    _orderService.InsertOrderNote(new OrderNote
                    {
                        OrderId           = order.Id,
                        Note              = errorStr,
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    });

                    return(RedirectToAction("Index", "Home", new { area = string.Empty }));
                }

                //clear attribute
                if (orderTotalSentToPayPal.HasValue)
                {
                    _genericAttributeService.SaveAttribute <decimal?>(order, PayPalHelper.OrderTotalSentToPayPal, null);
                }

                if (newPaymentStatus != PaymentStatus.Paid)
                {
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }

                if (!_orderProcessingService.CanMarkOrderAsPaid(order))
                {
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }

                //mark order as paid
                order.AuthorizationTransactionId = txnId;
                _orderService.UpdateOrder(order);
                _orderProcessingService.MarkOrderAsPaid(order);

                return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
            }
示例#25
0
        public IActionResult s2sHandler()
        {
            string errorCode = "", errorDesc = "";

            string strRequest = Request.QueryString.ToString().Replace("?", "");
            Dictionary <string, string> values;

            var processor = _paymentPluginManager.LoadPluginBySystemName("Payments.GestPay") as GestPayPaymentProcessor;

            if (processor == null ||
                !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new NopException("GestPay module cannot be loaded");
            }

            processor.GetResponseDetails(strRequest, out values);
            if (values != null && values.Count > 0)
            {
                if (values.Count == 4)
                {
                    return(RedirectToRoute("Plugin.Payments.GestPay.AcceptPaymenyByLink", new { a = values["a"], status = values["Status"], paymentId = values["paymentID"], paymentToken = values["paymentToken"] }));
                }

                var    shopLogin = values["a"];
                var    encString = values["b"];
                string shopTransactionId = "", authorizationCode = "", bankTransactionId = "";
                string transactionResult = "", buyerName = "", buyerEmail = "", riskified = "", authorizationcode = "", threeDSAuthenticationLevel = "";

                var acceptedThreeDSAuthLevels = new List <string> {
                    "1H", "1F", "2F", "2C", "2E"
                };
                var checkAmount = decimal.Zero;

                var sb = new StringBuilder();
                sb.AppendLine("GestPay s2s:");

                if (processor.IsShopLoginChecked(shopLogin) && encString != null)
                {
                    var endpoint   = _gestPayPaymentSettings.UseSandbox ? WSCryptDecryptSoapClient.EndpointConfiguration.WSCryptDecryptSoap12Test : WSCryptDecryptSoapClient.EndpointConfiguration.WSCryptDecryptSoap12;
                    var objDecrypt = new WSCryptDecryptSoapClient(endpoint);

                    string xmlResponse = objDecrypt.DecryptAsync(shopLogin, encString, _gestPayPaymentSettings.ApiKey).Result.OuterXml;

                    XmlDocument XMLReturn = new XmlDocument();
                    XMLReturn.LoadXml(xmlResponse.ToLower());

                    //_logger.Information(xmlResponse.ToLower());

                    //Id transazione inviato
                    errorCode = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/errorcode")?.InnerText;
                    errorDesc = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/errordescription")?.InnerText;
                    //authorizationCode = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/authorizationcode")?.InnerText;
                    shopTransactionId = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/shoptransactionid")?.InnerText;

                    //_____ Messaggio OK _____//
                    if (errorCode == "0")
                    {
                        //Codice autorizzazione
                        authorizationCode = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/authorizationcode")?.InnerText;
                        //Codice transazione
                        bankTransactionId = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/banktransactionid")?.InnerText;
                        //Ammontare della transazione
                        var amount = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/amount")?.InnerText;
                        //Risultato transazione
                        transactionResult = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/transactionresult")?.InnerText;
                        //Nome dell'utente
                        buyerName = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/buyer/buyername")?.InnerText;
                        //Email utilizzata nella transazione
                        buyerEmail = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/buyer/buyeremail")?.InnerText;

                        //__________ ?validare il totale? __________//
                        riskified = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/riskresponsedescription")?.InnerText;

                        //  3DS authentication level (1H,1F,2F,2C,2E)
                        threeDSAuthenticationLevel = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/threeds/authenticationresult/authenticationlevel")?.InnerText?.ToUpper();

                        try
                        {
                            checkAmount = decimal.Parse(amount, new CultureInfo("en-US"));
                        }
                        catch (Exception exc)
                        {
                            _logger.Error("GestPay s2s. Error getting Amount", exc);
                        }
                        sb.AppendLine("GestPay success.");
                    }
                    else
                    {
                        sb.AppendLine("GestPay failed.");
                        _logger.Error("GestPay S2S. Transaction not found", new NopException(sb.ToString()));
                    }
                }

                //________ Inizio composizione messaggio dal server _________//
                foreach (var kvp in values)
                {
                    sb.AppendLine(kvp.Key + ": " + kvp.Value);
                }

                //Recupero lo stato del pagamento
                var newPaymentStatus = GestPayHelper.GetPaymentStatus(transactionResult, "");
                sb.AppendLine("New payment status: " + newPaymentStatus);
                sb.AppendLine("Riskified = " + riskified);
                sb.AppendLine("3DS Level = " + threeDSAuthenticationLevel);

                //Cerco di recuperare l'ordine
                var orderNumberGuid = Guid.Empty;
                try
                {
                    orderNumberGuid = new Guid(shopTransactionId);
                }
                catch { }

                var order = _orderService.GetOrderByGuid(orderNumberGuid);
                //_________ aggiorno lo stato dell'ordine _________//
                if (order != null)
                {
                    switch (newPaymentStatus)
                    {
                    case PaymentStatus.Pending:
                    {
                    }
                    break;

                    case PaymentStatus.Authorized:
                    {
                        if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                        {
                            _orderProcessingService.MarkAsAuthorized(order);
                        }
                    }
                    break;

                    case PaymentStatus.Paid:
                    {
                        if (_orderProcessingService.CanMarkOrderAsPaid(order))
                        {
                            order.AuthorizationTransactionId   = bankTransactionId;
                            order.AuthorizationTransactionCode = authorizationCode;
                            _orderService.UpdateOrder(order);

                            if (!_gestPayPaymentSettings.EnableGuaranteedPayment || acceptedThreeDSAuthLevels.Contains(threeDSAuthenticationLevel))
                            {
                                _orderProcessingService.MarkOrderAsPaid(order);
                            }
                        }
                    }
                    break;

                    case PaymentStatus.Refunded:
                    {
                        if (_orderProcessingService.CanRefundOffline(order))
                        {
                            _orderProcessingService.RefundOffline(order);
                        }
                    }
                    break;

                    case PaymentStatus.Voided:
                    {
                        /*_ Visto che non si può impostare il pagamento ad Annullato
                         * _orderProcessingService.CanVoidOffline allora cancello l'ordine.
                         * C'è da decidere se avvisare o meno l'utente _*/
                        if (_orderProcessingService.CanCancelOrder(order))
                        {
                            _orderProcessingService.CancelOrder(order, true);
                        }
                    }
                    break;
                    }

                    //__________________ salvo i valori restituiti __________________//
                    sb.AppendLine("GestPay response:");
                    //Codice Errore
                    sb.AppendLine("ErrorCode: " + errorCode);
                    //Descrizione Errore
                    sb.AppendLine("ErrorDesc: " + errorDesc);
                    sb.AppendLine("TrxResult: " + transactionResult);
                    sb.AppendLine("BankTrxID: " + bankTransactionId);
                    sb.AppendLine("AuthCode: " + authorizationCode);
                    sb.AppendLine("Amount: " + checkAmount);
                    if (!Math.Round(checkAmount, 2).Equals(Math.Round(order.OrderTotal, 2)))
                    {
                        //__________ ?validare il totale? __________//
                        sb.AppendLine(String.Format("Amount difference: {0}-{1}", Math.Round(checkAmount, 2), Math.Round(order.OrderTotal, 2)));
                    }
                    sb.AppendLine("BuyerName: " + buyerName);
                    sb.AppendLine("BuyerEmail: " + buyerEmail);

                    //Inserisco la nota sull'ordine
                    var orderNote = new OrderNote
                    {
                        OrderId           = order.Id,
                        Note              = sb.ToString(),
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    };
                    _orderService.InsertOrderNote(orderNote);
                }
                else
                {
                    _logger.Error("GestPay S2S. Order is not found", new NopException(sb.ToString()));
                }
            }
            else
            {
                _logger.Error("GestPay S2S failed.", new NopException(strRequest));
            }

            //_________ Imposto il risultato __________//
            var s2SResponse = "KO";

            if (errorCode == "0")
            {
                s2SResponse = "OK";
            }
            //nothing should be rendered to visitor
            return(Content(String.Format("<html>{0}</html>", s2SResponse)));
        }
        public IActionResult IPNHandler()
        {
            //ensure this payment method is active
            if (!_paymentPluginManager.IsPluginActive(TwoCheckoutDefaults.SystemName,
                                                      _workContext.CurrentCustomer, _storeContext.CurrentStore.Id))
            {
                throw new NopException("2Checkout module cannot be loaded");
            }

            //define local function to get a value from the request Form or from the Query parameters
            string getValue(string key) =>
            Request.HasFormContentType && Request.Form.TryGetValue(key, out var value)
                ? value.ToString()
                : _webHelper.QueryString <string>(key)
            ?? string.Empty;

            //get order
            var customOrderNumber = getValue("x_invoice_num");
            var order             = _orderService.GetOrderByCustomOrderNumber(customOrderNumber);

            if (order == null)
            {
                //try to get order by the order identifier (used in previous plugin versions)
                int.TryParse(customOrderNumber, out var orderId);
                order = _orderService.GetOrderById(orderId);
                if (order == null)
                {
                    return(RedirectToRoute("Homepage"));
                }
            }

            //save request info as order note for debug purposes
            var info = new StringBuilder();

            info.AppendLine("2Checkout IPN:");
            if (Request.HasFormContentType && Request.Form.Keys.Any())
            {
                //form parameters
                foreach (var key in Request.Form.Keys)
                {
                    info.AppendLine($"{key}: {Request.Form[key]}");
                }
            }
            else
            {
                //query parameters
                info.AppendLine(Request.QueryString.ToString());
            }
            order.OrderNotes.Add(new OrderNote
            {
                Note = info.ToString(),
                DisplayToCustomer = false,
                CreatedOnUtc      = DateTime.UtcNow
            });
            _orderService.UpdateOrder(order);

            //verify the passed data by comparing MD5 hashes
            if (_twoCheckoutPaymentSettings.UseMd5Hashing)
            {
                var stringToHash = $"{_twoCheckoutPaymentSettings.SecretWord}" +
                                   $"{_twoCheckoutPaymentSettings.AccountNumber}" +
                                   $"{(_twoCheckoutPaymentSettings.UseSandbox ? "1" : getValue("order_number"))}" +
                                   $"{getValue("x_amount")}";
                var data     = new MD5CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(stringToHash));
                var sBuilder = new StringBuilder();
                foreach (var t in data)
                {
                    sBuilder.Append(t.ToString("x2"));
                }

                var computedHash = sBuilder.ToString();
                var receivedHash = getValue("x_md5_hash");

                if (computedHash.ToUpperInvariant() != receivedHash.ToUpperInvariant())
                {
                    order.OrderNotes.Add(new OrderNote
                    {
                        Note = "Hash validation failed",
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    });
                    _orderService.UpdateOrder(order);

                    return(RedirectToRoute("OrderDetails", new { orderId = order.Id }));
                }
            }

            var newPaymentStatus = PaymentStatus.Pending;

            var messageType   = getValue("message_type");
            var invoiceStatus = getValue("invoice_status");
            var fraudStatus   = getValue("fraud_status");
            var paymentType   = getValue("payment_type");

            //from documentation (https://www.2checkout.com/documentation/checkout/return):
            //if your return method is set to Direct Return or Header Redirect,
            //the buyer gets directed to automatically after the successful sale.
            if (messageType + invoiceStatus + fraudStatus + paymentType == string.Empty)
            {
                newPaymentStatus = PaymentStatus.Paid;
            }

            if (messageType.ToUpperInvariant() == "FRAUD_STATUS_CHANGED" &&
                fraudStatus == "pass" &&
                (invoiceStatus == "approved" || invoiceStatus == "deposited" || paymentType == "paypal ec"))
            {
                newPaymentStatus = PaymentStatus.Paid;
            }

            if (newPaymentStatus != PaymentStatus.Paid || !_orderProcessingService.CanMarkOrderAsPaid(order))
            {
                return(RedirectToRoute("OrderDetails", new { orderId = order.Id }));
            }

            //mark order as paid
            _orderProcessingService.MarkOrderAsPaid(order);
            return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
        }
        public virtual IActionResult EditPopup(PluginModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlugins))
            {
                return(AccessDeniedView());
            }

            //try to get a plugin with the specified system name
            var pluginDescriptor = _pluginService.GetPluginDescriptorBySystemName <IPlugin>(model.SystemName, LoadPluginsMode.All);

            if (pluginDescriptor == null)
            {
                return(RedirectToAction("List"));
            }

            if (ModelState.IsValid)
            {
                ViewBag.RefreshPage = true;

                //we allow editing of 'friendly name', 'display order', store mappings
                pluginDescriptor.FriendlyName = model.FriendlyName;
                pluginDescriptor.DisplayOrder = model.DisplayOrder;
                pluginDescriptor.LimitedToStores.Clear();
                if (model.SelectedStoreIds.Any())
                {
                    pluginDescriptor.LimitedToStores = model.SelectedStoreIds;
                }
                pluginDescriptor.LimitedToCustomerRoles.Clear();
                if (model.SelectedCustomerRoleIds.Any())
                {
                    pluginDescriptor.LimitedToCustomerRoles = model.SelectedCustomerRoleIds;
                }

                //update the description file
                pluginDescriptor.Save();

                //raise event
                _eventPublisher.Publish(new PluginUpdatedEvent(pluginDescriptor));

                //locales
                var pluginInstance = pluginDescriptor.Instance <IPlugin>();
                foreach (var localized in model.Locales)
                {
                    _localizationService.SaveLocalizedFriendlyName(pluginInstance, localized.LanguageId, localized.FriendlyName);
                }

                //enabled/disabled
                if (!pluginDescriptor.Installed)
                {
                    return(View(model));
                }

                var pluginIsActive = false;
                switch (pluginInstance)
                {
                case IPaymentMethod paymentMethod:
                    pluginIsActive = _paymentPluginManager.IsPluginActive(paymentMethod);
                    if (pluginIsActive && !model.IsEnabled)
                    {
                        //mark as disabled
                        _paymentSettings.ActivePaymentMethodSystemNames.Remove(pluginDescriptor.SystemName);
                        _settingService.SaveSetting(_paymentSettings);
                        break;
                    }

                    if (!pluginIsActive && model.IsEnabled)
                    {
                        //mark as enabled
                        _paymentSettings.ActivePaymentMethodSystemNames.Add(pluginDescriptor.SystemName);
                        _settingService.SaveSetting(_paymentSettings);
                    }

                    break;

                case IShippingRateComputationMethod shippingRateComputationMethod:
                    pluginIsActive = _shippingPluginManager.IsPluginActive(shippingRateComputationMethod);
                    if (pluginIsActive && !model.IsEnabled)
                    {
                        //mark as disabled
                        _shippingSettings.ActiveShippingRateComputationMethodSystemNames.Remove(pluginDescriptor.SystemName);
                        _settingService.SaveSetting(_shippingSettings);
                        break;
                    }

                    if (!pluginIsActive && model.IsEnabled)
                    {
                        //mark as enabled
                        _shippingSettings.ActiveShippingRateComputationMethodSystemNames.Add(pluginDescriptor.SystemName);
                        _settingService.SaveSetting(_shippingSettings);
                    }

                    break;

                case IPickupPointProvider pickupPointProvider:
                    pluginIsActive = _pickupPluginManager.IsPluginActive(pickupPointProvider);
                    if (pluginIsActive && !model.IsEnabled)
                    {
                        //mark as disabled
                        _shippingSettings.ActivePickupPointProviderSystemNames.Remove(pluginDescriptor.SystemName);
                        _settingService.SaveSetting(_shippingSettings);
                        break;
                    }

                    if (!pluginIsActive && model.IsEnabled)
                    {
                        //mark as enabled
                        _shippingSettings.ActivePickupPointProviderSystemNames.Add(pluginDescriptor.SystemName);
                        _settingService.SaveSetting(_shippingSettings);
                    }

                    break;

                case ITaxProvider taxProvider:
                    if (!model.IsEnabled)
                    {
                        //mark as disabled
                        _taxSettings.ActiveTaxProviderSystemName = string.Empty;
                        _settingService.SaveSetting(_taxSettings);
                        break;
                    }

                    //mark as enabled
                    _taxSettings.ActiveTaxProviderSystemName = model.SystemName;
                    _settingService.SaveSetting(_taxSettings);
                    break;

                case IExternalAuthenticationMethod externalAuthenticationMethod:
                    pluginIsActive = _authenticationPluginManager.IsPluginActive(externalAuthenticationMethod);
                    if (pluginIsActive && !model.IsEnabled)
                    {
                        //mark as disabled
                        _externalAuthenticationSettings.ActiveAuthenticationMethodSystemNames.Remove(pluginDescriptor.SystemName);
                        _settingService.SaveSetting(_externalAuthenticationSettings);
                        break;
                    }

                    if (!pluginIsActive && model.IsEnabled)
                    {
                        //mark as enabled
                        _externalAuthenticationSettings.ActiveAuthenticationMethodSystemNames.Add(pluginDescriptor.SystemName);
                        _settingService.SaveSetting(_externalAuthenticationSettings);
                    }

                    break;

                case IWidgetPlugin widgetPlugin:
                    pluginIsActive = _widgetPluginManager.IsPluginActive(widgetPlugin);
                    if (pluginIsActive && !model.IsEnabled)
                    {
                        //mark as disabled
                        _widgetSettings.ActiveWidgetSystemNames.Remove(pluginDescriptor.SystemName);
                        _settingService.SaveSetting(_widgetSettings);
                        break;
                    }

                    if (!pluginIsActive && model.IsEnabled)
                    {
                        //mark as enabled
                        _widgetSettings.ActiveWidgetSystemNames.Add(pluginDescriptor.SystemName);
                        _settingService.SaveSetting(_widgetSettings);
                    }

                    break;
                }

                //activity log
                _customerActivityService.InsertActivity("EditPlugin",
                                                        string.Format(_localizationService.GetResource("ActivityLog.EditPlugin"), pluginDescriptor.FriendlyName));

                return(View(model));
            }

            //prepare model
            model = _pluginModelFactory.PreparePluginModel(model, pluginDescriptor, true);

            //if we got this far, something failed, redisplay form
            return(View(model));
        }
        /*
         *
         * [NonAction]
         * public override IList<string> ValidatePaymentForm(FormCollection form)
         * {
         *  var warnings = new List<string>();
         *  return warnings;
         * }
         *
         * [NonAction]
         * public override ProcessPaymentRequest GetPaymentInfo(FormCollection form)
         * {
         *  var paymentInfo = new ProcessPaymentRequest();
         *  return paymentInfo;
         * }
         */



        //[ValidateInput(false)]
        public IActionResult Return()
        {
            _webHelper.QueryString <string>("");

            if (!(_paymentPluginManager.LoadPluginBySystemName("Payments.PayEpayco") is PayEpaycoPaymentProcessor processor) || !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new NopException("Epayco Colombia module cannot be loaded");
            }


            var transactionId = _webHelper.QueryString <string>("ref_payco");

            if (processor.GetTransactionDetails(transactionId, out var response))
            {
                dynamic item = JObject.Parse(response);

                var transactionID   = (string)item["data"]["x_ref_payco"];
                var orderNumber     = (string)item["data"]["x_id_factura"];
                var customer_email  = (string)item["data"]["x_customer_email"];
                var amount_in_cents = (string)item["data"]["x_amount"];
                var created_at      = (string)item["data"]["x_fecha_transaccion"];
                var status          = (string)item["data"]["x_respuesta"];
                var reason_text     = (string)item["data"]["x_response_reason_text"];

                var sb = new StringBuilder();
                sb.AppendLine("PayEpayCo :");
                sb.AppendLine("transactionID" + ": " + transactionID);
                sb.AppendLine("customer_email" + ": " + customer_email);
                sb.AppendLine("reference" + ": " + orderNumber);
                sb.AppendLine("amount" + ": " + amount_in_cents);
                sb.AppendLine("created_at" + ": " + created_at);
                sb.AppendLine("status" + ": " + status);
                sb.AppendLine("reason text" + ": " + reason_text);

                var ipnInfo = sb.ToString();

                var mcGross = 0;

                try
                {
                    mcGross = Convert.ToInt32(amount_in_cents);
                }
                catch (Exception exc)
                {
                    _logger.Error("EpayCo PDT. Error getting gross", exc);
                }

                var order = _orderService.GetOrderById(Convert.ToInt32(orderNumber));

                if (order == null)
                {
                    var errorStr = "EpayCo Order is not found";
                    _logger.Error(errorStr, new NopException(ipnInfo));
                    return(Content(errorStr));
                }
                //order note
                _orderService.InsertOrderNote(new OrderNote
                {
                    Note = ipnInfo,
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });
                _orderService.UpdateOrder(order);

                //validate order total
                if (status == "Aceptada" && mcGross.Equals(order.OrderTotal))
                {
                    var errorStr = $"EpayCo Returned order total {mcGross} doesn't equal order total {order.OrderTotal}. Order# {order.Id}.";
                    //log
                    _logger.Error(errorStr);
                    //order note
                    _orderService.InsertOrderNote(new OrderNote
                    {
                        Note = errorStr,
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    });
                    _orderService.UpdateOrder(order);

                    return(Content(errorStr));
                }
                if (status == "Aceptada")
                {
                    if (_orderProcessingService.CanMarkOrderAsPaid(order))
                    {
                        order.AuthorizationTransactionId = transactionId;
                        _orderService.UpdateOrder(order);
                    }

                    //Thank you for shopping with us. Your credit card has been charged and your transaction is successful
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }
                else
                {
                    /*
                     *      Here you need to put in the routines for a failed
                     *      transaction such as sending an email to customer
                     *      setting database status etc etc
                     */

                    return(RedirectToAction("Index", "Home", new { area = "" }));
                }
            }
            else
            {
                return(RedirectToAction("Index", "Home", new { area = "" }));
            }
        }
        //[NonAction]
        //public override IList<string> ValidatePaymentForm(IFormCollection form)
        //{
        //    var warnings = new List<string>();

        //    return warnings;
        //}

        //[NonAction]
        //public override ProcessPaymentRequest GetPaymentInfo(IFormCollection form)
        //{
        //    var paymentInfo = new ProcessPaymentRequest();

        //    return paymentInfo;
        //}
        #endregion

        #region 支付请求
        /// <summary>
        /// 接收支付宝支付通知
        /// </summary>
        public ActionResult Notify(FormCollection form)
        {
            if (!(_paymentPluginManager.LoadPluginBySystemName("Nop.Plugin.Payments.AliPay") is AliPayPaymentProcessor processor) || !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new NopException("插件无法加载");
            }
            var aliPayPaymentSettings = _settingService.LoadSetting <AliPayPaymentSettings>(_storeContext.CurrentStore.Id);
            var partner = aliPayPaymentSettings.Partner;

            if (string.IsNullOrEmpty(partner))
            {
                throw new Exception("合作身份者ID 不能为空");
            }
            var key = aliPayPaymentSettings.Key;

            if (string.IsNullOrEmpty(key))
            {
                throw new Exception("MD5密钥不能为空");
            }
            var sellerEmail = aliPayPaymentSettings.SellerEmail;

            if (string.IsNullOrEmpty(sellerEmail))
            {
                throw new Exception("卖家Email 不能为空");
            }
            ///↓↓↓↓↓↓↓ 获取支付宝POST过来通知消息,并以“参数名 = 参数值”的形式组成数组↓↓↓↓↓↓↓↓
            int i;
            var coll      = Request.Form;
            var sortedStr = coll.Keys.ToList();

            SortedDictionary <string, string> sPara = new SortedDictionary <string, string>();

            for (i = 0; i < sortedStr.Count; i++)
            {
                sPara.Add(sortedStr[i], Request.Form[sortedStr[i]]);
            }
            ///↑↑↑↑↑↑↑ 获取支付宝POST过来通知消息,并以“参数名 = 参数值”的形式组成数组↑↑↑↑↑↑↑↑
            if (sPara.Count > 0)//判断是否有带返回参数
            {
                AlipayNotify aliNotify    = new AlipayNotify(partner: partner, key: key, input_charset: "utf-8", sign_type: sPara["sign_type"]);
                var          sign         = Request.Form["sign"];
                var          notify_id    = Request.Form["notify_id"];
                bool         verifyResult = aliNotify.Verify(sPara, notify_id, sign);
                if (verifyResult)//验证成功
                {
                    //商户订单号

                    string out_trade_no = Request.Form["out_trade_no"];

                    //支付宝交易号

                    string trade_no = Request.Form["trade_no"];

                    //交易状态
                    string trade_status = Request.Form["trade_status"];


                    if (coll["trade_status"] == "TRADE_FINISHED" || coll["trade_status"] == "TRADE_SUCCESS")
                    {
                        int orderId;

                        if (int.TryParse(out_trade_no, out orderId))
                        {
                            var order = _orderService.GetOrderById(orderId);

                            if (order != null && _orderProcessingService.CanMarkOrderAsPaid(order))
                            {
                                //修改订单状态
                                _orderProcessingService.MarkOrderAsPaid(order);
                                //添加付款信息
                                var paymentInfo = new PaymentInfo()
                                {
                                    OrderId       = orderId,
                                    Name          = processor.PluginDescriptor.SystemName,
                                    PaymentGuid   = Guid.NewGuid(),
                                    Trade_no      = trade_no,
                                    Total         = decimal.Parse(Request.Form["price"]),
                                    Trade_status  = Request.Form["trade_status"],
                                    Buyer_email   = Request.Form["buyer_email"],
                                    Buyer_id      = Request.Form["buyer_id"],
                                    Seller_email  = Request.Form["seller_email"],
                                    Seller_id     = Request.Form["seller_id"],
                                    Note          = Request.Form["subject"],
                                    Out_Trade_No  = Request.Form["trade_no"],
                                    CreateDateUtc = DateTime.Now,
                                };
                                _paymentInfoService.Insert(paymentInfo);
                            }
                        }
                    }
                    return(Content("success")); //请不要修改或删除
                }
                else //验证失败
                {
                    var logStr = string.Format("MD5:notify_id={0},sign={1}", notify_id, sign);
                    _logger.Error(logStr);
                    return(Content("fail"));
                }
            }
            return(Content("无通知参数"));
        }
        public ActionResult ResultHandler(string Status, string Authority, string OGUID)
        {
            if (!(_paymentPluginManager.LoadPluginBySystemName("Payments.Zarinpal") is ZarinPalPaymentProcessor processor) || !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new NopException("ZarinPal module cannot be loaded");
            }

            Guid orderNumberGuid = Guid.Empty;

            try
            {
                orderNumberGuid = new Guid(OGUID);
            }
            catch { }

            Order order = _orderService.GetOrderByGuid(orderNumberGuid);
            var   total = Convert.ToInt32(Math.Round(order.OrderTotal, 2));

            if (_ZarinPalPaymentSettings.RialToToman)
            {
                total = total / 10;
            }

            if (string.IsNullOrEmpty(Status) == false && string.IsNullOrEmpty(Authority) == false)
            {
                long _refId = 0;
                System.Net.ServicePointManager.Expect100Continue = false;
                int _status          = -1;
                var storeScope       = _storeContext.ActiveStoreScopeConfiguration;
                var ZarinPalSettings = _settingService.LoadSetting <ZarinpalPaymentSettings>(storeScope);

                if (_ZarinPalPaymentSettings.UseSandbox)
                {
                    using (ServiceReferenceZarinpalSandBox.PaymentGatewayImplementationServicePortTypeClient ZpalSr = new ServiceReferenceZarinpalSandBox.PaymentGatewayImplementationServicePortTypeClient())
                    {
                        var res = ZpalSr.PaymentVerificationAsync(
                            ZarinPalSettings.MerchantID,
                            Authority,
                            total).Result; //test
                        _status = res.Body.Status;
                        _refId  = res.Body.RefID;
                    }
                }
                else
                {
                    using (ServiceReferenceZarinpal.PaymentGatewayImplementationServicePortTypeClient ZpalSr = new ServiceReferenceZarinpal.PaymentGatewayImplementationServicePortTypeClient())
                    {
                        var res = ZpalSr.PaymentVerificationAsync(
                            ZarinPalSettings.MerchantID,
                            Authority,
                            total).Result; //test
                        _status = res.Body.Status;
                        _refId  = res.Body.RefID;
                    }
                }

                var result = ZarinpalHelper.StatusToMessage(_status);

                order.OrderNotes.Add(new OrderNote()
                {
                    Note = string.Concat(
                        "پرداخت ",
                        (result.IsOk ? "" : "نا"), "موفق", " - ",
                        "پیغام درگاه : ", result.Message,
                        result.IsOk ? string.Concat(" - ", "کد پی گیری : ", _refId.ToString()) : ""
                        ),
                    DisplayToCustomer = true,
                    CreatedOnUtc      = DateTime.UtcNow
                });

                _orderService.UpdateOrder(order);

                if (result.IsOk && _orderProcessingService.CanMarkOrderAsPaid(order))
                {
                    order.AuthorizationTransactionId = _refId.ToString();
                    _orderService.UpdateOrder(order);
                    _orderProcessingService.MarkOrderAsPaid(order);
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }
            }
            return(RedirectToRoute("orderdetails", new { orderId = order.Id }));
        }