Convert string to json

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
2 года назад
Hi All.
How Can use this part in nopcommerce?
like in this example
https://github.com/ECPay/ApplePay_NET/blob/master/Net%20Sample%20Code/ApplePaySample/ApplePaySample_V2.aspx.cs#L45

Or any way to convert string to json?


Thank you
2 года назад
Please clarify your needs "...convert string to json?"

JSON is a string.  In your example  (... .Serialize(payload) ), payload is an object, and it gets converted from an object to a JSON string.

NopCommerce uses the NewtonSoft JSON.NET library; you can do same with - e.g.

using Newtonsoft.Json;
...
var json = JsonConvert.SerializeObject(payload);
один год назад
Ban IP address Feature and to add data in generic table for repeat ip address

public class PaymentAttempt
    {
        public int Attempt { get; set; }

        public DateTime AttemptDateTime { get; set; }

        public string IpAddress { get; set; }
    }



if (PluginDefaults.RequestState_Declined == PaymentResponse.status)
                {
                    var paymentAttempts = new List<PaymentAttempt>();
                    if (_genericAttributeService.GetAttribute<string>(_workContext.CurrentCustomer, "PaymentAttempts") == null)
                    {
                        paymentAttempts.Add(
                            new PaymentAttempt { Attempt = 1, AttemptDateTime = DateTime.UtcNow,IpAddress = _workContext.CurrentCustomer.LastIpAddress }
                        );
                        var paymentAttemptsContent = JsonConvert.SerializeObject(paymentAttempts);
                        _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, "PaymentAttempts", paymentAttemptsContent);
                    }
                    else
                    {
                        var genericPaymentAttempts = _genericAttributeService.GetAttribute<string>(_workContext.CurrentCustomer, "PaymentAttempts");
                        paymentAttempts = JsonConvert.DeserializeObject<List<PaymentAttempt>>(genericPaymentAttempts);

                        var timeDiff = paymentAttempts.Select(x => x.AttemptDateTime).LastOrDefault().Subtract(paymentAttempts.Select(x => x.AttemptDateTime).FirstOrDefault());
                        var containsIp = paymentAttempts.Select(x => x.IpAddress).Contains(_workContext.CurrentCustomer.LastIpAddress);
                        if (paymentAttempts.Count == 2 && timeDiff.TotalMinutes <= 1 && containsIp)
                        {
                            _logger.Error(string.Format(_localizationService.GetResource("Plugin.Payments.ProcessPayment.Ban.Ip"), paymentAttempts.Select(x => x.IpAddress).FirstOrDefault()));
                            return null;
                        }
                        else if (timeDiff.TotalMinutes > 1 || !containsIp)
                            _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, "PaymentAttempts", string.Empty);
                        else
                        {
                            paymentAttempts.Insert(paymentAttempts.Count,
                                new PaymentAttempt { Attempt = paymentAttempts.Count + 1, AttemptDateTime = DateTime.UtcNow, IpAddress = _workContext.CurrentCustomer.LastIpAddress }
                            );
                            var paymentAttemptsContent = JsonConvert.SerializeObject(paymentAttempts);
                            _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, "PaymentAttempts", paymentAttemptsContent);
                        }
                    }

                    if (!string.IsNullOrEmpty(PaymentResponse.errorInformation.message))
                        _logger.InsertLog(logLevel: LogLevel.Error, shortMessage: PaymentResponse.errorInformation.message, fullMessage: response);
                    else
                        _logger.Error(_localizationService.GetResource("Plugin.Payments.ProcessPayment.Error"));
                    return null;
                }
один год назад
API methods for payment feature



        /// <summary>
        /// Gets the body text encoded string
        /// </summary>
        /// <param name="bodyText"></param>
        /// <returns>returns encoded string</returns>
        public static string GenerateDigest(string bodyText)
        {
            var digest = string.Empty;
            using (var sha256hash = SHA256.Create())
            {
                byte[] payloadBytes = sha256hash
                    .ComputeHash(Encoding.UTF8.GetBytes(bodyText));
                digest = Convert.ToBase64String(payloadBytes);
                digest = "SHA-256=" + digest;
            }
            return digest;
        }

        /// <summary>
        /// Gets the encoded string of singnature parameter and secret key
        /// </summary>
        /// <param name="signatureParams"></param>
        /// <param name="secretKey"></param>
        /// <returns>returns encoded string</returns>
        public static string GenerateSignatureFromParams(string signatureParams, string secretKey)
        {
            var sigBytes = Encoding.UTF8.GetBytes(signatureParams);
            var decodedSecret = Convert.FromBase64String(secretKey);
            var hmacSha256 = new HMACSHA256(decodedSecret);
            var messageHash = hmacSha256.ComputeHash(sigBytes);
            return Convert.ToBase64String(messageHash);
        }


Get response Payment by API

public CyberSourcePaymentResponse PaymentAPI(ProcessPaymentRequest processPaymentRequest)
        {
            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            var merchantId = _encryptionService.DecryptText(_cyberSourceSettings.MerchantID);
            var secretKey = _encryptionService.DecryptText(_cyberSourceSettings.SharedSecretKey);
            var keyId = _encryptionService.DecryptText(_cyberSourceSettings.KeyID);
            var baseUrl = _cyberSourceSettings.UseSandbox ? _cyberSourceSettings.SandboxURL ?? string.Empty : _cyberSourceSettings.ProductionURL ?? string.Empty;
            var cyberSourcPaymentRequest = PrepareCyberSourcePaymentRequest(processPaymentRequest, customer);
            var JsonObj = JObject.Parse(JsonConvert.SerializeObject(cyberSourcPaymentRequest)).ToString();
            var digest = GenerateDigest(JsonObj);
            var signatureParm = "host: " + baseUrl + "\n(request-target): post /pts/v2/payments/\ndigest: " + digest + "\nv-c-merchant-id: " + merchantId;
            var signatureHash = GenerateSignatureFromParams(signatureParm, secretKey);
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://" + baseUrl + "/pts/v2/payments/");
            httpWebRequest.Method = "POST";
            httpWebRequest.Headers.Add(PluginDefaults.HEADER_V_C_MERCHANT_ID, merchantId);
            httpWebRequest.Headers.Add(PluginDefaults.HEADER_V_C_DATE, DateTime.UtcNow.ToString("ddd, dd MMM yyy HH':'mm':'ss 'GMT'"));
            httpWebRequest.Headers.Add(PluginDefaults.HEADER_DIGEST, digest);
            httpWebRequest.Headers.Add(PluginDefaults.HEADER_SIGNATURE, "keyid=\"" + keyId + "\", algorithm=\"HmacSHA256\", headers=\"host (request-target) digest v-c-merchant-id\", signature=\"" + signatureHash + "\"");
            httpWebRequest.ContentType = PluginDefaults.Content_Type;

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(JsonObj);
                streamWriter.Flush();
                streamWriter.Close();
            }

            try
            {
                var response = string.Empty;
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    response = streamReader.ReadToEnd();

                if (string.IsNullOrEmpty(response))
                    return null;

                if (_cyberSourceSettings.Debug)
                    _logger.InsertLog(logLevel: LogLevel.Information, shortMessage: "cyberSource-paymentapi:", fullMessage: "request:" + JsonObj + "____response:" + response);

                var cyberSourcePaymentResponse = JsonConvert.DeserializeObject<CyberSourcePaymentResponse>(response);

                if ( cyberSourcePaymentResponse == null )
                {
                    _logger.Error(_localizationService.GetResource("Plugin.Payments.CyberSource.ProcessPayment.NoResponse"));
                    return null;
                }

                if (PluginDefaults.RequestState_Declined == cyberSourcePaymentResponse.status)
                {
                    var paymentAttempts = new List<PaymentAttempt>();
                    if (_genericAttributeService.GetAttribute<string>(_workContext.CurrentCustomer, "PaymentAttempts") == null)
                    {
                        paymentAttempts.Add(
                            new PaymentAttempt { Attempt = 1, AttemptDateTime = DateTime.UtcNow,IpAddress = _workContext.CurrentCustomer.LastIpAddress }
                        );
                        var paymentAttemptsContent = JsonConvert.SerializeObject(paymentAttempts);
                        _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, "PaymentAttempts", paymentAttemptsContent);
                    }
                    else
                    {
                        var genericPaymentAttempts = _genericAttributeService.GetAttribute<string>(_workContext.CurrentCustomer, "PaymentAttempts");
                        paymentAttempts = JsonConvert.DeserializeObject<List<PaymentAttempt>>(genericPaymentAttempts);

                        var timeDiff = paymentAttempts.Select(x => x.AttemptDateTime).LastOrDefault().Subtract(paymentAttempts.Select(x => x.AttemptDateTime).FirstOrDefault());
                        var containsIp = paymentAttempts.Select(x => x.IpAddress).Contains(_workContext.CurrentCustomer.LastIpAddress);
                        if (paymentAttempts.Count == 2 && timeDiff.TotalMinutes <= 1 && containsIp)
                        {
                            _logger.Error(string.Format(_localizationService.GetResource("Plugin.Payments.CyberSource.ProcessPayment.Ban.Ip"), paymentAttempts.Select(x => x.IpAddress).FirstOrDefault()));
                            return null;
                        }
                        else if (timeDiff.TotalMinutes > 1 || !containsIp)
                            _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, "PaymentAttempts", string.Empty);
                        else
                        {
                            paymentAttempts.Insert(paymentAttempts.Count,
                                new PaymentAttempt { Attempt = paymentAttempts.Count + 1, AttemptDateTime = DateTime.UtcNow, IpAddress = _workContext.CurrentCustomer.LastIpAddress }
                            );
                            var paymentAttemptsContent = JsonConvert.SerializeObject(paymentAttempts);
                            _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, "PaymentAttempts", paymentAttemptsContent);
                        }
                    }

                    if (!string.IsNullOrEmpty(cyberSourcePaymentResponse.errorInformation.message) && _cyberSourceSettings.Debug)
                        _logger.InsertLog(logLevel: LogLevel.Error, shortMessage: cyberSourcePaymentResponse.errorInformation.message, fullMessage: response);
                    else
                        _logger.Error(_localizationService.GetResource("Plugin.Payments.CyberSource.ProcessPayment.Error"));
                    return null;
                }

                // store payment info
                InsertPaymentCard(processPaymentRequest, cyberSourcePaymentResponse, customer);

                // remove custom values
                ResetPaymentCardCustomValues(processPaymentRequest.CustomValues);

                return cyberSourcePaymentResponse;
            }
            catch (WebException ex)
            {
                using (StreamReader response_stream = new StreamReader(ex.Response.GetResponseStream()))
                {
                    var error = response_stream.ReadToEnd();
                    _logger.Error(error);
                    response_stream.Close();

                    var cyberSourcePaymentResponse = JsonConvert.DeserializeObject<CyberSourceExceptionResponse>(error);
                    if (cyberSourcePaymentResponse != null && cyberSourcePaymentResponse.message != null)
                    {
                        _logger.Error(cyberSourcePaymentResponse.message);
                        return null;
                    }
                }
            }
            return null;
        }
один год назад
Middleware to check ban ip address and restricted to use a site

1.Create a ApplicationBuilderExtensions

/// <summary>
    /// Represents extensions of IApplicationBuilder
    /// </summary>
    public static class ApplicationBuilderExtensions
    {

        /// <summary>
        /// Adds the authentication middleware, which enables authentication capabilities.
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public static void UseBanIpAddress(this IApplicationBuilder application)
        {
            //check whether database is installed
            if (!DataSettingsManager.DatabaseIsInstalled)
                return;

            application.UseMiddleware<BanIpAddressMiddleware>();
        }

    }


2. Register on startup file

/// <summary>
    /// Represents object for the configuring plugin DB context on application startup
    /// </summary>
    public class PluginDbStartup : INopStartup



public void Configure(IApplicationBuilder application)
        {
            //configure banIpAddress
            application.UseBanIpAddress();
        }


3. use middleware feature to ban IP Address (BanIpAddressMiddleware)


public class BanIpAddressMiddleware
    {
        #region Fields

        private readonly RequestDelegate _next;
        private readonly IWorkContext _workContext;
        private readonly IGenericAttributeService _genericAttributeService;

        #endregion

        #region Ctor

        public BanIpAddressMiddleware(RequestDelegate next,
                IWorkContext workContext,
                IGenericAttributeService genericAttributeService)
        {
            _next = next;
            _workContext = workContext;
            _genericAttributeService = genericAttributeService;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Invoke middleware actions
        /// </summary>
        /// <param name="context">HTTP context</param>
        /// <returns>Task</returns>
        public async Task Invoke(HttpContext context, IWebHelper webHelper)
        {
            var genericPaymentAttempts = _genericAttributeService.GetAttribute<string>(_workContext.CurrentCustomer, "PaymentAttempts");
            if (string.IsNullOrEmpty(genericPaymentAttempts))
            {
                await _next(context);
                return;
            }

            var paymentAttempts = JsonConvert.DeserializeObject<List<PaymentAttempt>>(genericPaymentAttempts);
            if (paymentAttempts == null)
            {
                await _next(context);
                return;
            }

            var timeDiff = paymentAttempts.Select(x => x.AttemptDateTime).LastOrDefault().Subtract(paymentAttempts.Select(x => x.AttemptDateTime).FirstOrDefault());
            var containsIp = paymentAttempts.Select(x => x.IpAddress).Contains(_workContext.CurrentCustomer.LastIpAddress);
            if (paymentAttempts.Count == 2 && timeDiff.TotalMinutes <= 1 && containsIp)
            {
                var originalUrl = webHelper.GetThisPageUrl(includeQueryString: true, lowercaseUrl: true);
                if (!originalUrl.Contains("/admin") &&
                    !context.Request.Method.Equals(HttpMethods.Post, StringComparison.OrdinalIgnoreCase) &&
                    !originalUrl.Contains("/?") &&
                    !originalUrl.EndsWith("/") &&
                    !originalUrl.Contains("/themes/") &&
                    !originalUrl.Contains("/bundles/") &&
                    !originalUrl.Contains("publitas.xml"))
                {
                    var oldUrl = originalUrl;
                    originalUrl = originalUrl.Replace("?", "/?");
                    if (!originalUrl.Contains("/?") && !originalUrl.EndsWith('/'))
                        originalUrl += "/";

                    var url = context.Request.Scheme + "//" + context.Request.Host;
                    if (originalUrl.Length != oldUrl.Length)
                    {
                        //redirect
                        //var url = context.Request.Scheme + "//" + context.Request.Host + "/Security/AccessDenied";
                        context.Response.Redirect(url);
                        await _next(context);
                        return;
                    }
                }
            }
            //or call the next middleware in the request pipeline
            await _next(context);
        }

        #endregion
    }
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.