Пример #1
0
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var orderTotal = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);

            using (var client = new WebClient())
            {
                var initiateData = new NameValueCollection();
                initiateData["PAYGATE_ID"] = _payGatePaymentSettings.PayGateID;
                initiateData["REFERENCE"]  = postProcessPaymentRequest.Order.Id.ToString();
                initiateData["AMOUNT"]     = (Convert.ToDouble(orderTotal) * 100).ToString();
                initiateData["CURRENCY"]   = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;
                var storeLocation = _webHelper.GetStoreLocation(false);
                if (_payGatePaymentSettings.UseSSL)
                {
                    storeLocation = storeLocation.Replace("http://", "https://");
                }
                initiateData["RETURN_URL"]       = storeLocation + "Plugins/PaymentPayGate/PayGateReturnHandler?pgnopcommerce=" + postProcessPaymentRequest.Order.Id.ToString();
                initiateData["TRANSACTION_DATE"] = String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now).ToString();
                initiateData["LOCALE"]           = "en-za";
                initiateData["COUNTRY"]          = postProcessPaymentRequest.Order.BillingAddress.Country.ThreeLetterIsoCode;
                initiateData["EMAIL"]            = postProcessPaymentRequest.Order.BillingAddress.Email;
                //initiateData["NOTIFY_URL"] = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayGate/PayGateNotifyHandler?pgnopcommerce=" + postProcessPaymentRequest.Order.Id.ToString();
                initiateData["USER3"] = "nopcommerce-v1.0.0";

                string initiateValues = string.Join("", initiateData.AllKeys.Select(key => initiateData[key]));

                initiateData["CHECKSUM"] = new PayGateHelper().CalculateMD5Hash(initiateValues + _payGatePaymentSettings.EncryptionKey);
                var initiateResponse = client.UploadValues("https://secure.paygate.co.za/payweb3/initiate.trans", "POST", initiateData);
                dictionaryResponse = Encoding.Default.GetString(initiateResponse)
                                     .Split('&')
                                     .Select(p => p.Split('='))
                                     .ToDictionary(p => p[0], p => p.Length > 1 ? Uri.UnescapeDataString(p[1]) : null);
            }

            // New Code to fix it
            RemotePost remotePost = new RemotePost();

            remotePost.FormName = "PayGate";
            remotePost.Method   = "POST";
            remotePost.Url      = "https://secure.paygate.co.za/payweb3/process.trans";
            remotePost.Add("PAY_REQUEST_ID", dictionaryResponse["PAY_REQUEST_ID"]);
            remotePost.Add("CHECKSUM", dictionaryResponse["CHECKSUM"]);
            remotePost.Post();
        }
Пример #2
0
        //public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        //{
        //    this.defaultLogger.Information("Calling async");
        //    await PostProcessPaymentAsync(postProcessPaymentRequest);
        //    this.defaultLogger.Information("After async");
        //}

        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public async Task PostProcessPaymentAsync(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var orderTotal    = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);
            var testMode      = _payGatePaymentSettings.TestMode;
            var encryptionKey = "";
            var initiated     = false;

            using (var client = new WebClient())
            {
                var initiateData = new NameValueCollection();
                if (testMode)
                {
                    initiateData["PAYGATE_ID"] = "10011072130";
                    encryptionKey = "secret";
                    await this.defaultLogger.InformationAsync("Using test mode");
                }
                else
                {
                    initiateData["PAYGATE_ID"] = _payGatePaymentSettings.PayGateID;
                    encryptionKey = _payGatePaymentSettings.EncryptionKey;
                }
                initiateData["REFERENCE"] = postProcessPaymentRequest.Order.Id.ToString();
                initiateData["AMOUNT"]    = (Convert.ToDouble(orderTotal) * 100).ToString();
                initiateData["CURRENCY"]  = (await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId)).CurrencyCode;

                var storeLocation = _webHelper.GetStoreLocation(false);
                if (_payGatePaymentSettings.UseSSL)
                {
                    storeLocation = storeLocation.Replace("http://", "https://");
                }
                initiateData["RETURN_URL"]       = storeLocation + "Plugins/PaymentPayGate/PayGateReturnHandler?pgnopcommerce=" + postProcessPaymentRequest.Order.Id.ToString();
                initiateData["TRANSACTION_DATE"] = String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now).ToString();
                initiateData["LOCALE"]           = "en-za";

                var threeLetterIsoCode = "";
                var billingEmail       = "";

                var customer = await _customerService.GetCustomerByIdAsync(postProcessPaymentRequest.Order.CustomerId);

                if (customer != null)
                {
                    var billingAddress = await _customerService.GetCustomerBillingAddressAsync(customer);

                    if (billingAddress != null)
                    {
                        billingEmail = billingAddress.Email;

                        var country = await _countryService.GetCountryByAddressAsync(billingAddress);

                        if (country != null && !string.IsNullOrWhiteSpace(country.ThreeLetterIsoCode))
                        {
                            threeLetterIsoCode = country.ThreeLetterIsoCode;
                        }
                    }
                }

                initiateData["COUNTRY"] = threeLetterIsoCode;
                initiateData["EMAIL"]   = billingEmail;
                if (_payGatePaymentSettings.EnableIpn)
                {
                    initiateData["NOTIFY_URL"] = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayGate/PayGateNotifyHandler?pgnopcommerce=" + postProcessPaymentRequest.Order.Id.ToString();
                }
                initiateData["USER1"] = postProcessPaymentRequest.Order.Id.ToString();
                initiateData["USER3"] = "nopcommerce-v4.4.0";

                string initiateValues = string.Join("", initiateData.AllKeys.Select(key => initiateData[key]));

                initiateData["CHECKSUM"] = new PayGateHelper().CalculateMD5Hash(initiateValues + encryptionKey);

                string initiateValuesString = string.Join("", initiateData.AllKeys.Select(key => initiateData[key]));

                var cnt = 0;
                while (!initiated && cnt < 5)
                {
                    var initiateResponse = client.UploadValues("https://secure.paygate.co.za/payweb3/initiate.trans", "POST", initiateData);
                    await defaultLogger.InformationAsync("Initiate response: " + Encoding.UTF8.GetString(initiateResponse) + " cnt=" + cnt);

                    dictionaryResponse = Encoding.Default.GetString(initiateResponse)
                                         .Split('&')
                                         .Select(p => p.Split('='))
                                         .ToDictionary(p => p[0], p => p.Length > 1 ? Uri.UnescapeDataString(p[1]) : null);
                    if (dictionaryResponse.Count == 4 && dictionaryResponse.ContainsKey("PAY_REQUEST_ID"))
                    {
                        await defaultLogger.InformationAsync("PAYGATE_ID = " + dictionaryResponse["PAYGATE_ID"]);

                        await defaultLogger.InformationAsync("PAY_REQUEST_ID = " + dictionaryResponse["PAY_REQUEST_ID"]);

                        await defaultLogger.InformationAsync("REFERENCE = " + dictionaryResponse["REFERENCE"]);

                        await defaultLogger.InformationAsync("CHECKSUM = " + dictionaryResponse["CHECKSUM"]);

                        initiated = true;
                    }
                    cnt++;
                }

                // Redirect to payment portal
                if (initiated)
                {
                    _webHelper.IsPostBeingDone = true;
                    try
                    {
                        await defaultLogger.InformationAsync("Is initiated");

                        var sb           = new StringBuilder();
                        var Url          = "https://secure.paygate.co.za/payweb3/process.trans";
                        var payRequestId = dictionaryResponse["PAY_REQUEST_ID"];
                        var checksum     = dictionaryResponse["CHECKSUM"];
                        sb.Append("<html><head></head>");
                        sb.Append("<body>");
                        sb.Append("<form id=\"PayGate_Form\" method=\"post\" action=\"" + Url + "\" >");
                        sb.Append("<input type=\"hidden\" name=\"PAY_REQUEST_ID\" value=\"" + payRequestId + "\" >");
                        sb.Append("<input type=\"hidden\" name=\"CHECKSUM\" value=\"" + checksum + "\" >");
                        sb.Append("<script>document.getElementById('PayGate_Form').submit();</script>");
                        sb.Append("</form></body></html>");

                        // Synchronous operations disabled by default in DotnetCore >= 3.0
                        var feat = _httpContextAccessor.HttpContext.Features.Get <IHttpBodyControlFeature>();
                        if (feat != null)
                        {
                            feat.AllowSynchronousIO = true;
                        }

                        var response = _httpContextAccessor.HttpContext.Response;
                        var data     = Encoding.UTF8.GetBytes(sb.ToString());
                        response.ContentType   = "text/html; charset=utf-8";
                        response.ContentLength = data.Length;
                        await defaultLogger.InformationAsync("Start write to body: " + sb.ToString());

                        response.Body.Write(data, 0, data.Length);
                        response.Body.Flush();
                        await defaultLogger.InformationAsync("End write to body: " + sb.ToString());

                        //await Task.Delay(3000);
                        await defaultLogger.InformationAsync("End three second delay: " + sb.ToString());
                    }
                    catch (Exception e)
                    {
                        await defaultLogger.ErrorAsync("Failed to POST: " + e.Message);
                    }
                }
                else
                {
                    await defaultLogger.ErrorAsync("Failed to get valid initiate response after 5 attempts");
                }
            }
        }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var orderTotal   = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);
            var currentOrder = _orderService.GetOrderById(postProcessPaymentRequest.Order.Id);

            using (var client = new WebClient())
            {
                var initiateData = new NameValueCollection();
                initiateData["PAYGATE_ID"] = _payGatePaymentSettings.PayGateID;
                initiateData["REFERENCE"]  = postProcessPaymentRequest.Order.Id.ToString();
                initiateData["AMOUNT"]     = (Convert.ToDouble(orderTotal) * 100).ToString();
                initiateData["CURRENCY"]   =
                    _currencyService.GetCurrencyByCode(currentOrder.CustomerCurrencyCode).CurrencyCode;
                initiateData["RETURN_URL"]       = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayGate/PayGateReturnHandler?pgnopcommerce=" + postProcessPaymentRequest.Order.Id.ToString();
                initiateData["TRANSACTION_DATE"] = String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now).ToString();
                initiateData["LOCALE"]           = "en-za";
                initiateData["COUNTRY"]          = postProcessPaymentRequest.Order.BillingAddress.Country.ThreeLetterIsoCode;
                initiateData["EMAIL"]            = postProcessPaymentRequest.Order.BillingAddress.Email;
                initiateData["NOTIFY_URL"]       = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayGate/PayGateNotifyHandler?pgnopcommerce=" + postProcessPaymentRequest.Order.Id.ToString();
                initiateData["USER3"]            = "nopcommerce-v1.0.0";

                string initiateValues = string.Join("", initiateData.AllKeys.Select(key => initiateData[key]));

                initiateData["CHECKSUM"] = new PayGateHelper().CalculateMD5Hash(initiateValues + _payGatePaymentSettings.EncryptionKey);
                var initiateResponse = client.UploadValues("https://secure.paygate.co.za/payweb3/initiate.trans", "POST", initiateData);
                var responseText     = Encoding.Default.GetString(initiateResponse);

                if (responseText.Contains("PGID_NOT_EN") || responseText.Contains("DATA_CUR") ||
                    responseText.Contains("DATA_PW") || responseText.Contains("DATA_CHK"))
                {
                    string Error = "Checksum posted does not match the one calculated by PayGate, either due to an incorrect encryption key used or a field that has been excluded from the checksum calculation";
                    if (Encoding.Default.GetString(initiateResponse).Contains("PGID_NOT_EN"))
                    {
                        Error = "The PayGate ID being used to post data to PayGate has not yet been enabled, or there are no payment methods setup on it.";
                    }
                    else if (Encoding.Default.GetString(initiateResponse).Contains("DATA_CUR"))
                    {
                        Error = "The currency that has been posted to PayGate is not supported.";
                    }
                    else if (Encoding.Default.GetString(initiateResponse).Contains("DATA_PW"))
                    {
                        Error = "Mandatory fields have been excluded from the post to PayGate, refer to page 9 of the documentation as to what fields should be posted.";
                    }

                    _logger.InsertLog(LogLevel.Debug, "Paygate response for order number " + postProcessPaymentRequest.Order.Id.ToString(), Error);


                    currentOrder.OrderStatus = OrderStatus.Cancelled;
                    _orderService.UpdateOrder(currentOrder);


                    var url = _storeContext.CurrentStore.Url;
                    if (!url.EndsWith("/"))
                    {
                        url += "/";
                    }
                    var stringBuilder = "<html><head><script>function GoToUrl(){window.location = '" + url + "orderdetails/" + currentOrder.Id.ToString() + "';} GoToUrl();</script></head><body></body></html>";

                    _httpContext.Response.Write(stringBuilder);
                    _httpContext.Response.End();
                }
                else
                {
                    dictionaryResponse = Encoding.Default.GetString(initiateResponse)
                                         .Split('&')
                                         .Select(p => p.Split('='))
                                         .ToDictionary(p => p[0], p => p.Length > 1 ? Uri.UnescapeDataString(p[1]) : null);

                    if (dictionaryResponse["PAY_REQUEST_ID"] != null && dictionaryResponse["CHECKSUM"] != null)
                    {
                        RemotePost remotePost = new RemotePost
                        {
                            FormName = "PayGate",
                            Method   = "POST",
                            Url      = "https://secure.paygate.co.za/payweb3/process.trans"
                        };
                        remotePost.Add("PAY_REQUEST_ID", dictionaryResponse["PAY_REQUEST_ID"]);
                        remotePost.Add("CHECKSUM", dictionaryResponse["CHECKSUM"]);
                        remotePost.Post();
                    }
                }
            }
        }