/// <summary>
        /// Add order total to the request query parameters
        /// </summary>
        /// <param name="parameters">Query parameters</param>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        private void AddOrderTotalParameters(IDictionary <string, string> parameters, PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //round order total
            var roundedOrderTotal = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);

            parameters.Add("cmd", "_xclick");
            //parameters.Add("item_name", $"Order Number {postProcessPaymentRequest.Order.OrderNumber.ToString()}");
            //parameters.Add("amount", roundedOrderTotal.ToString("0.00", CultureInfo.InvariantCulture));

            //save order total that actually sent to PayPal (used for PDT order total validation)
            _genericAttributeService.SaveAttribute(postProcessPaymentRequest.Order, MOLPayHelper.OrderTotalSentToMOLPay, roundedOrderTotal);
        }
        /// <summary>
        /// Create common query parameters for the request
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Created query parameters</returns>
        private async Task <IDictionary <string, string> > CreateQueryParameters(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //get store location
            var storeLocation = _webHelper.GetStoreLocation();
            var stateProvince = "";
            var countryCode   = "";

            if (!String.IsNullOrEmpty(postProcessPaymentRequest.Order.ShippingAddress?.StateProvinceId))
            {
                var state = (await _serviceProvider.GetRequiredService <IStateProvinceService>().GetStateProvinceById(postProcessPaymentRequest.Order.ShippingAddress?.StateProvinceId));
                if (state != null)
                {
                    stateProvince = state.Abbreviation;
                }
            }
            if (!String.IsNullOrEmpty(postProcessPaymentRequest.Order.ShippingAddress?.CountryId))
            {
                var country = await _serviceProvider.GetRequiredService <ICountryService>().GetCountryById(postProcessPaymentRequest.Order.ShippingAddress?.CountryId);

                if (country != null)
                {
                    countryCode = country.TwoLetterIsoCode;
                }
            }


            //create query parameters
            return(new Dictionary <string, string> {
                //PayPal ID or an email address associated with your PayPal account
                ["business"] = _paypalStandardPaymentSettings.BusinessEmail,

                //the character set and character encoding
                ["charset"] = "utf-8",

                //set return method to "2" (the customer redirected to the return URL by using the POST method, and all payment variables are included)
                ["rm"] = "2",

                ["currency_code"] = postProcessPaymentRequest.Order.CustomerCurrencyCode,

                //order identifier
                ["invoice"] = postProcessPaymentRequest.Order.OrderNumber.ToString(),
                ["custom"] = postProcessPaymentRequest.Order.OrderGuid.ToString(),

                //PDT, IPN and cancel URL
                ["return"] = $"{storeLocation}Plugins/PaymentPayPalStandard/PDTHandler",
                ["notify_url"] = $"{storeLocation}Plugins/PaymentPayPalStandard/IPNHandler",
                ["cancel_return"] = $"{storeLocation}Plugins/PaymentPayPalStandard/CancelOrder",

                //shipping address, if exists
                ["no_shipping"] = postProcessPaymentRequest.Order.ShippingStatus == ShippingStatus.ShippingNotRequired ? "1" : "2",
                ["address_override"] = postProcessPaymentRequest.Order.ShippingStatus == ShippingStatus.ShippingNotRequired ? "0" : "1",
                ["first_name"] = postProcessPaymentRequest.Order.ShippingAddress?.FirstName,
                ["last_name"] = postProcessPaymentRequest.Order.ShippingAddress?.LastName,
                ["address1"] = postProcessPaymentRequest.Order.ShippingAddress?.Address1,
                ["address2"] = postProcessPaymentRequest.Order.ShippingAddress?.Address2,
                ["city"] = postProcessPaymentRequest.Order.ShippingAddress?.City,

                ["state"] = stateProvince,
                ["country"] = countryCode,
                ["zip"] = postProcessPaymentRequest.Order.ShippingAddress?.ZipPostalCode,
                ["email"] = postProcessPaymentRequest.Order.ShippingAddress?.Email
            });
        }
        /// <summary>
        /// Create common query parameters for the request
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Created query parameters</returns>
        private IDictionary <string, string> CreateQueryParameters(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //get store location
            var storeLocation = _webHelper.GetStoreLocation();
            var stateProvince = "";
            var countryCode   = "";

            if (!String.IsNullOrEmpty(postProcessPaymentRequest.Order.ShippingAddress?.StateProvinceId))
            {
                var state = EngineContext.Current.Resolve <IStateProvinceService>().GetStateProvinceById(postProcessPaymentRequest.Order.ShippingAddress?.StateProvinceId);
                if (state != null)
                {
                    stateProvince = state.Abbreviation;
                }
            }
            if (!String.IsNullOrEmpty(postProcessPaymentRequest.Order.ShippingAddress?.CountryId))
            {
                var country = EngineContext.Current.Resolve <ICountryService>().GetCountryById(postProcessPaymentRequest.Order.ShippingAddress?.CountryId);
                if (country != null)
                {
                    countryCode = country.TwoLetterIsoCode;
                }
            }

            Random random  = new System.Random();
            int    RandNum = random.Next(0, 1000000000);

            var status     = true;
            var merchantid = _molPayPaymentSettings.MerchantId;
            var vkey       = _molPayPaymentSettings.Vkey;

            var mpschannel = postProcessPaymentRequest.Order.PaymentMethodSystemName;

            //var roundedItemPrice = Math.Round(item.UnitPriceExclTax, 2);
            //roundedItemPrice.ToString("0.00", CultureInfo.InvariantCulture)

            var amount    = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);
            var mpsamount = amount.ToString("0.00", CultureInfo.InvariantCulture);

            var mpscurrency      = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)?.CurrencyCode;
            var billFirstName    = postProcessPaymentRequest.Order.BillingAddress?.FirstName;
            var billLastName     = postProcessPaymentRequest.Order.BillingAddress?.LastName;
            var mpsbill_name     = billFirstName + " " + billLastName;
            var mpsbill_mobile   = postProcessPaymentRequest.Order.BillingAddress?.PhoneNumber;
            var FirstUrl         = GetMOLPayUrl();
            var mpsorderid       = postProcessPaymentRequest.Order.OrderNumber;
            var SecondUrl        = FirstUrl + merchantid;
            var mpsvcode         = md5encode(mpsamount + merchantid + mpsorderid + vkey);
            var address1         = postProcessPaymentRequest.Order.BillingAddress?.Address1;
            var address2         = postProcessPaymentRequest.Order.BillingAddress?.Address2;
            var mpsbill_desc     = address1 + " " + address2;
            var mpsbill_email    = postProcessPaymentRequest.Order.BillingAddress?.Email;
            var invoice          = postProcessPaymentRequest.Order.OrderNumber.ToString();
            var custom           = postProcessPaymentRequest.Order.OrderGuid.ToString();
            var ChannelType      = _molPayPaymentSettings.ChannelType;
            var address_override = postProcessPaymentRequest.Order.ShippingStatus == ShippingStatus.ShippingNotRequired ? "0" : "1";
            var city             = postProcessPaymentRequest.Order.ShippingAddress?.City;
            var mpscountry       = countryCode;
            //var mpsapiversion = "3.16";
            var mpslangcode = "en";

            //var mpstimerbox = "#counter";

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

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

            //create query parameters
            return(new Dictionary <string, string>
            {
                ["status"] = status.ToString(),
                ["merchant_id"] = merchantid,
                ["amount"] = mpsamount.ToString(),
                ["orderid"] = mpsorderid.ToString(),
                ["bill_name"] = mpsbill_name,
                ["bill_email"] = mpsbill_email,
                ["bill_mobile"] = mpsbill_mobile,
                ["bill_desc"] = mpsbill_desc,
                ["country"] = countryCode,
                ["vcode"] = mpsvcode,
                ["currency"] = mpscurrency,
                ["channel"] = mpschannel,
                ["langcode"] = mpslangcode,
                ["returnurl"] = $"{storeLocation}Plugins/MOLPay/PDTHandler",
                ["callbackurl"] = $"{storeLocation}/Plugins/MOLPay/IPNHandler",
                //["cancelurl"] = $"{storeLocation}Plugins/MOLPay/CancelOrder",
            });
        }
Пример #4
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 Task PostProcessPaymentAsync(PostProcessPaymentRequest postProcessPaymentRequest)
 {
     return(Task.CompletedTask);
 }
Пример #5
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)
        {
            #region Dummy test card numbers
            //card type
            //card number
            //number length
            //issue no length
            //Mastercard
            //5100080000000000
            //16
            //0
            //Visa Delta - UK
            //4406080400000000
            //16
            //0
            //Visa Delta - Non UK
            //4462030000000000
            //16
            //0
            //Visa
            //4911830000000
            //13
            //0
            //Visa
            //4917610000000000
            //16
            //0
            //American Express
            //370000200000000
            //15
            //0
            //Diners
            //36700102000000
            //14
            //0
            //JCB
            //3528000700000000
            //16
            //0
            //Visa Electron (UK only)
            //4917300800000000
            //16
            //0
            //Solo
            //6334580500000000
            //16
            //0
            //Solo
            //633473060000000000
            //18
            //1
            //Discover Card
            //6011000400000000
            //16
            //0
            //Laser
            //630495060000000000
            //18
            //0
            //Maestro (UK only)
            //6759649826438453
            //16
            //0
            //Visa Purchasing
            //4484070000000000
            //16
            //0
            #endregion


            string returnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentWorldPay/Return";

            var remotePostHelper = new RemotePost();
            remotePostHelper.FormName = "WorldpayForm";
            remotePostHelper.Url      = GetWorldpayUrl();

            remotePostHelper.Add("instId", _worldPayPaymentSettings.InstanceId);
            remotePostHelper.Add("cartId", postProcessPaymentRequest.Order.Id.ToString());

            if (!string.IsNullOrEmpty(_worldPayPaymentSettings.CreditCard))
            {
                remotePostHelper.Add("paymentType", _worldPayPaymentSettings.CreditCard);
            }

            if (!string.IsNullOrEmpty(_worldPayPaymentSettings.CssName))
            {
                remotePostHelper.Add("MC_WorldPayCSSName", _worldPayPaymentSettings.CssName);
            }

            remotePostHelper.Add("currency", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode);
            remotePostHelper.Add("email", postProcessPaymentRequest.Order.BillingAddress.Email);
            remotePostHelper.Add("hideContact", "true");
            remotePostHelper.Add("noLanguageMenu", "true");
            remotePostHelper.Add("withDelivery", postProcessPaymentRequest.Order.ShippingStatus != ShippingStatus.ShippingNotRequired ? "true" : "false");
            remotePostHelper.Add("fixContact", "false");
            remotePostHelper.Add("amount", postProcessPaymentRequest.Order.OrderTotal.ToString(new CultureInfo("en-US", false).NumberFormat));
            remotePostHelper.Add("desc", _storeContext.CurrentStore.Name);
            remotePostHelper.Add("M_UserID", postProcessPaymentRequest.Order.CustomerId.ToString());
            remotePostHelper.Add("M_FirstName", postProcessPaymentRequest.Order.BillingAddress.FirstName);
            remotePostHelper.Add("M_LastName", postProcessPaymentRequest.Order.BillingAddress.LastName);
            remotePostHelper.Add("M_Addr1", postProcessPaymentRequest.Order.BillingAddress.Address1);
            remotePostHelper.Add("tel", postProcessPaymentRequest.Order.BillingAddress.PhoneNumber);
            remotePostHelper.Add("M_Addr2", postProcessPaymentRequest.Order.BillingAddress.Address2);
            remotePostHelper.Add("M_Business", postProcessPaymentRequest.Order.BillingAddress.Company);

            var cultureInfo = new CultureInfo(_workContext.WorkingLanguage.LanguageCulture);
            remotePostHelper.Add("lang", cultureInfo.TwoLetterISOLanguageName);

            var billingStateProvince = postProcessPaymentRequest.Order.BillingAddress.StateProvince;
            if (billingStateProvince != null)
            {
                remotePostHelper.Add("M_StateCounty", billingStateProvince.Abbreviation);
            }
            else
            {
                remotePostHelper.Add("M_StateCounty", "");
            }
            if (!_worldPayPaymentSettings.UseSandbox)
            {
                remotePostHelper.Add("testMode", "0");
            }
            else
            {
                remotePostHelper.Add("testMode", "100");
            }
            remotePostHelper.Add("postcode", postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode);
            var billingCountry = postProcessPaymentRequest.Order.BillingAddress.Country;
            if (billingCountry != null)
            {
                remotePostHelper.Add("country", billingCountry.TwoLetterIsoCode);
            }
            else
            {
                remotePostHelper.Add("country", "");
            }

            remotePostHelper.Add("address", postProcessPaymentRequest.Order.BillingAddress.Address1 + "," + (billingCountry != null ? billingCountry.Name : ""));
            remotePostHelper.Add("MC_callback", returnUrl);
            remotePostHelper.Add("name", postProcessPaymentRequest.Order.BillingAddress.FirstName + " " + postProcessPaymentRequest.Order.BillingAddress.LastName);

            if (postProcessPaymentRequest.Order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                remotePostHelper.Add("delvName", postProcessPaymentRequest.Order.ShippingAddress.FirstName + " " + postProcessPaymentRequest.Order.ShippingAddress.LastName);
                string delvAddress = postProcessPaymentRequest.Order.ShippingAddress.Address1;
                delvAddress += (!string.IsNullOrEmpty(postProcessPaymentRequest.Order.ShippingAddress.Address2)) ? " " + postProcessPaymentRequest.Order.ShippingAddress.Address2 : string.Empty;
                remotePostHelper.Add("delvAddress", delvAddress);
                remotePostHelper.Add("delvPostcode", postProcessPaymentRequest.Order.ShippingAddress.ZipPostalCode);
                var shippingCountry = postProcessPaymentRequest.Order.ShippingAddress.Country;
                remotePostHelper.Add("delvCountry", shippingCountry.TwoLetterIsoCode);
            }

            remotePostHelper.Post();
        }
        public string PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var sellerEmail ="*****@*****.**";
            var partner ="2088611703821661";

            const string inputCharset ="utf-8";
            const string service ="mobile.securitypay.pay";
            const string paymentType ="1";
            const string signType ="RSA";

            var order = postProcessPaymentRequest.Order;
            var outTradeNo = order.TradeNo;
            var payProductDescrpiton = "";
            var payProductName = "";
            var body = payProductDescrpiton;
            var subject = payProductName;
            var totalFee = order.OrderTotal.ToString(CultureInfo.InvariantCulture);
            var notifyUrl = _webHelper.GetStoreLocation(false) + "Order/AliMobileNotify"; //_webHelper.GetStoreLocation(false) +"Order/Notify";

            var paras = new SortedDictionary<string, string>()
            {
                {"service", service},
                {"partner", partner},
                {"seller_id", sellerEmail},
                {"out_trade_no", outTradeNo},
                {"subject", subject},
                {"body", body},
                {"total_fee", totalFee},
                {"payment_type", paymentType},
                {"notify_url", notifyUrl},
                {"_input_charset", InputCharset},
                {"it_b_pay","30m" }
            };

            var sign = CreatRsaSign(paras, inputCharset);
            sign = HttpUtility.UrlEncode(sign);

            var sb = new StringBuilder();
            foreach (var temp in paras)
            {
                sb.Append($"{temp.Key}={temp.Value}&");
            }
            var paymentString = sb.ToString().TrimEnd('&');
            paymentString += $"&sign={sign}";
            paymentString += $"&sign_type={signType}";
            return paymentString;
        }
 /// <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)
 {
     // we don't use this
 }
Пример #8
0
 public override PostProcessPaymentRequestResult PostProcessPayment(PostProcessPaymentRequest request)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Add order total to the request query parameters
        /// </summary>
        ///
        /// <param name="parameters">Query parameters</param>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        private void AddOrderTotalParameters(IDictionary <string, string> parameters, PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //round order total
            var roundedOrderTotal = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);

            parameters.Add("amount", roundedOrderTotal.ToString("0.00", CultureInfo.InvariantCulture));
        }
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            const string signType = "MD5";
            const string service = "create_direct_pay_by_user";
            const string paymentType = "1";
            const string showUrl = "http://www.alipay.com/";
            const string gateway = "https://www.alipay.com/cooperate/gateway.do?_input_charset=utf-8";

            var order = postProcessPaymentRequest.Order;
            var outTradeNo = order.TradeNo;
            var payProductDescrpiton = "商品描述";
            var payProductName = "测试商品";
            var body = payProductDescrpiton;
            var subject = payProductName;
            var totalFee = order.OrderTotal.ToString("F");
            var notifyUrl = _webHelper.GetStoreLocation(false) + "Order/AliNotify";
            var returnUrl = _webHelper.GetStoreLocation(false) + "Order/Return";

            var paras = new SortedDictionary<string, string>()
            {
                {"service", service},
                {"partner", _partner},
                {"seller_email", _sellerEmail},
                {"out_trade_no", outTradeNo},
                {"subject", subject},
                {"timeout_express", "30m"},
                {"body", body},
                {"total_fee", totalFee},
                {"show_url", showUrl},
                {"payment_type", paymentType},
                {"notify_url", notifyUrl},
                {"return_url", returnUrl},
                {"_input_charset", InputCharset}
            };

            var aliayUrl = CreatUrlSing(paras, InputCharset);

            using (var client = new HttpClient())
            {
                paras.Add("sign", aliayUrl);
                paras.Add("sign_type", signType);

                var httpcontents = new FormUrlEncodedContent(paras);
                var result = client.PostAsync(gateway, httpcontents).Result;
                var bytes = result.Content.ReadAsByteArrayAsync().Result;
                _httpContext.Response.BinaryWrite(bytes);
                _httpContext.Response.End();
            }
        }
Пример #11
0
 public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
 {
     throw new NotImplementedException();
 }
        public bool CheckOrderStatus(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var tradeno = postProcessPaymentRequest.Order.TradeNo;
            const string gateway = "https://openapi.alipay.com/gateway.do";
            const string method = "alipay.trade.query";
            const string signType = "RSA";

            var paras = new SortedDictionary<string, string>()
            {
                {"charset", InputCharset},
                {"timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
                {"method", method},
                {"app_id", AppId},
                {"format", "json"},
                {"version", "1.0"},
                {"sign_type", signType},
                {
                    "biz_content",
                    $@"{{""out_trade_no"":""{tradeno}""}}"
                }
            };

            var aliayUrl = CreatRsaSign(paras, InputCharset);

            using (var client = new HttpClient())
            {
                paras.Add("sign", aliayUrl);

                var httpcontents = new FormUrlEncodedContent(paras);
                var result = client.PostAsync(gateway, httpcontents).Result;
                var resultstr = result.Content.ReadAsStringAsync().Result;
                var jsonobj = JsonConvert.DeserializeObject<AliOrderDetail>(resultstr);
                if (jsonobj.alipay_trade_query_response.code == "10000" &&
                    jsonobj.alipay_trade_query_response.trade_status == "TRADE_SUCCESS" && CheckAliCharSign(jsonobj))
                {
                    return true;
                }
            }
            return false;
        }
        public WebChartResponse PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var webChartResponse = new WebChartResponse();
            var order = postProcessPaymentRequest.Order;
            var spbillCreateIp = _webHelper.GetCurrentIpAddress();
            var notifyUrl = _webHelper.GetStoreLocation(false) + "Order/WebChatMobileNotify";
            var noncestr = CommonHelper.GenerateRandomDigitCode(32);
            var paras = new SortedDictionary<string, string>()
            {
                {"body", ""},
                {"attach", ""},
                {"out_trade_no", order.TradeNo},
                {"total_fee", (order.OrderTotal*100).ToString(".")},
                {"goods_tag", ""},
                {"product_id", order.Id.ToString()},
                {"trade_type", "APP"},
                {"appid", Appid},
                {"mch_id", MchId},
                {"spbill_create_ip", spbillCreateIp},
                {"nonce_str", noncestr},
                {"notify_url", notifyUrl}
            };

            using (var client = new HttpClient())
            {
                var sign = MakeSign(paras, Key);
                paras.Add("sign", sign);

                var requestxml = RequestXml(paras);
                var httpContent = new StringContent(requestxml, Encoding.UTF8, "application/xml");
                var result = client.PostAsync(Paymenturl, httpContent).Result;
                using (var responsestream = result.Content.ReadAsStreamAsync().Result)
                {
                    var serializer = new XmlSerializer(typeof (WebCharReponse));
                    var response = serializer.Deserialize(responsestream) as WebCharReponse;
                    if (response == null || response.ReturnCode == "FAIL")
                    {
                        webChartResponse.Sucess = false;
                        webChartResponse.Message = "下单失败";
                        return webChartResponse;
                    }

                    var timestamp = Convert.ToInt32((DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds);
                    var mobilesignparameters = new SortedDictionary<string, string>()
                    {
                        {"appid", response.Appid},
                        {"partnerid", response.MchId},
                        {"prepayid", response.PrepayId},
                        {"package", "Sign=WXPay"},
                        {"noncestr", noncestr},
                        {"timestamp", timestamp.ToString(CultureInfo.InvariantCulture)}
                    };
                    webChartResponse.Sign = MakeSign(mobilesignparameters, Key);
                    webChartResponse.Appid = response.Appid;
                    webChartResponse.Partnerid = response.MchId;
                    webChartResponse.Prepayid = response.PrepayId;
                    webChartResponse.Package = "Sign=WXPay";
                    webChartResponse.Noncestr = noncestr;
                    webChartResponse.Timestamp = timestamp.ToString(CultureInfo.InvariantCulture);
                    return webChartResponse;
                }
            }
        }
        /// <summary>
        /// Checks the order status.
        /// </summary>
        /// <param name="postProcessPaymentRequest">The post process payment request.</param>
        /// <returns></returns>
        public bool CheckOrderStatus(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var order = postProcessPaymentRequest.Order;
            const string paymenturl = "https://api.mch.weixin.qq.com/pay/orderquery";

            var paras = new SortedDictionary<string, string>()
            {
                {"mch_id", MchId},
                {"out_trade_no", order.TradeNo},
                {"appid", Appid},
                {"nonce_str", CommonHelper.GenerateRandomDigitCode(16)},
            };

            using (var client = new HttpClient())
            {
                var sign = MakeSign(paras, Key);
                paras.Add("sign", sign);

                var requestxml = RequestXml(paras);
                var httpContent = new StringContent(requestxml, Encoding.UTF8, "application/xml");
                var result = client.PostAsync(paymenturl, httpContent).Result;
                using (var responsestream = result.Content.ReadAsStreamAsync().Result)
                {
                    var serializer = new XmlSerializer(typeof (WebChartOrderDetail));
                    var response = serializer.Deserialize(responsestream) as WebChartOrderDetail;
                    if (response != null && response.ReturnCode == "SUCCESS" && response.TradeState == "SUCCESS")
                    {
                        return true;
                    }
                }
            }
            return false;
        }
Пример #15
0
        /// <summary>
        /// Manually adjusts the net prices for cart items to avoid rounding differences with the PayPal API.
        /// </summary>
        /// <param name="paypalItems">PayPal line items</param>
        /// <param name="postProcessPaymentRequest">Post process paymenmt request object</param>
        /// <remarks>
        /// In detail: We add what we have thrown away in the checkout when we rounded prices to two decimal places.
        /// It's a workaround. Better solution would be to store the thrown away decimal places for each OrderItem in the database.
        /// More details: http://magento.xonu.de/magento-extensions/empfehlungen/magento-paypal-rounding-error-fix/
        /// </remarks>
        public void AdjustLineItemAmounts(List <PayPalLineItem> paypalItems, PostProcessPaymentRequest postProcessPaymentRequest)
        {
            try
            {
                var cartItems = paypalItems.Where(x => x.Type == PayPalItemType.CartItem);

                if (cartItems.Count() <= 0)
                {
                    return;
                }

                decimal totalSmartStore = Math.Round(postProcessPaymentRequest.Order.OrderSubtotalExclTax, 2);
                decimal totalPayPal = decimal.Zero;
                decimal delta, portion, rest;

                // calculate what PayPal calculates
                cartItems.Each(x => totalPayPal += (x.AmountRounded * x.Quantity));
                totalPayPal = Math.Round(totalPayPal, 2, MidpointRounding.AwayFromZero);

                // calculate difference
                delta = Math.Round(totalSmartStore - totalPayPal, 2);
                //"SM: {0}, PP: {1}, delta: {2}".FormatInvariant(totalSmartStore, totalPayPal, delta).Dump();

                if (delta == decimal.Zero)
                {
                    return;
                }

                // prepare lines... only lines with quantity = 1 are adjustable. if there is no one, create one.
                if (!cartItems.Any(x => x.Quantity == 1))
                {
                    var item = cartItems.First(x => x.Quantity > 1);
                    item.Quantity -= 1;
                    var newItem = item.Clone();
                    newItem.Quantity = 1;
                    paypalItems.Insert(paypalItems.IndexOf(item) + 1, newItem);
                }

                var cartItemsOneQuantity = paypalItems.Where(x => x.Type == PayPalItemType.CartItem && x.Quantity == 1);
                Debug.Assert(cartItemsOneQuantity.Count() > 0);

                SplitDifference(delta, cartItemsOneQuantity.Count(), out portion, out rest);

                if (portion != decimal.Zero)
                {
                    cartItems
                    .Where(x => x.Quantity == 1)
                    .Each(x => x.Amount = x.Amount + portion);
                }

                if (rest != decimal.Zero)
                {
                    var restItem = cartItems.First(x => x.Quantity == 1);
                    restItem.Amount = restItem.Amount + rest;
                }

                //"SM: {0}, PP: {1}, delta: {2} (portion: {3}, rest: {4})".FormatInvariant(totalSmartStore, totalPayPal, delta, portion, rest).Dump();
            }
            catch (Exception exception)
            {
                _logger.Error(exception);
            }
        }
        public IActionResult ConfirmParatikaPayment(string merchantPaymentId, string responseCode, string responseMsg)
        {
            var model = new PaymentInfoModel();
            var processPaymentRequest = new ProcessPaymentRequest();

            processPaymentRequest.OrderGuid = Guid.Parse(merchantPaymentId);
            HttpContext.Session.Set <ProcessPaymentRequest>("OrderPaymentInfo", processPaymentRequest);

            if (_orderSettings.CheckoutDisabled)
            {
                return(RedirectToRoute("ShoppingCart"));
            }

            var cart = _workContext.CurrentCustomer.ShoppingCartItems
                       .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                       .LimitPerStore(_storeContext.CurrentStore.Id)
                       .ToList();

            if (!cart.Any())
            {
                return(RedirectToRoute("ShoppingCart"));
            }

            if (_orderSettings.OnePageCheckoutEnabled)
            {
                return(RedirectToRoute("CheckoutOnePage"));
            }

            if (_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)
            {
                return(Challenge());
            }
            //Check whether payment workflow is required
            var isPaymentWorkflowRequired = _orderProcessingService.IsPaymentWorkflowRequired(cart);

            if (!isPaymentWorkflowRequired)
            {
                return(RedirectToRoute("CheckoutConfirm"));
            }

            //load payment method
            var paymentMethodSystemName = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer,
                                                                                         NopCustomerDefaults.SelectedPaymentMethodAttribute, _storeContext.CurrentStore.Id);
            var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(paymentMethodSystemName);

            if (paymentMethod == null)
            {
                return(RedirectToRoute("CheckoutPaymentMethod"));
            }

            var orderGuid = _session.Get <string>("MERCHANTPAYMENTID_" + _workContext.CurrentCustomer.Id);

            if (responseCode == "00")
            {
                try
                {
                    processPaymentRequest.StoreId    = _storeContext.CurrentStore.Id;
                    processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
                    processPaymentRequest.PaymentMethodSystemName = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer,
                                                                                                                   NopCustomerDefaults.SelectedPaymentMethodAttribute, _storeContext.CurrentStore.Id);
                    processPaymentRequest.OrderGuid = Guid.Parse(merchantPaymentId);
                    HttpContext.Session.Set <ProcessPaymentRequest>("OrderPaymentInfo", processPaymentRequest);
                    var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
                    if (placeOrderResult.Success)
                    {
                        HttpContext.Session.Set <ProcessPaymentRequest>("OrderPaymentInfo", null);
                        var postProcessPaymentRequest = new PostProcessPaymentRequest
                        {
                            Order = placeOrderResult.PlacedOrder,
                        };
                        _paymentService.PostProcessPayment(postProcessPaymentRequest);

                        if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
                        {
                            //redirection or POST has been done in PostProcessPayment
                            return(Content("Redirected"));
                        }

                        return(RedirectToRoute("CheckoutCompleted", new { orderId = placeOrderResult.PlacedOrder.Id }));
                    }

                    foreach (var error in placeOrderResult.Errors)
                    {
                        model.Error += error;
                    }
                }
                catch (Exception exc)
                {
                    _logger.Warning(exc.Message, exc);
                    model.Error += exc.Message;
                }
            }
            else
            {
                model.Error += _localizationService.GetResource("Plugins.Payments.Paratika.Fields.Error");
            }

            model.Error += responseMsg;
            return(RedirectToRoute("CheckoutPaymentMethod"));
        }
Пример #17
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)
 {
     //nothing
 }
Пример #18
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 customerValues = postProcessPaymentRequest.Order.DeserializeCustomValues();
            var isJsPay        = false;

            if (_httpContext.Session["isJsPay"] != null)
            {
                isJsPay = _httpContext.Session["isJsPay"].ToString().ToLower() == "true";
            }

            string openId = null;

            if (isJsPay)
            {
                var weiXinAuthentication =
                    _workContext.CurrentCustomer.ExternalAuthenticationRecords.FirstOrDefault(
                        q => q.ProviderSystemName == "ExternalAuth.WeiXin");
                if (weiXinAuthentication != null)
                {
                    openId = weiXinAuthentication.ExternalIdentifier;
                }
                else
                {
                    isJsPay = false;
                }
            }


            string productId, body;
            var    firstProduct = postProcessPaymentRequest.Order.OrderItems.FirstOrDefault();

            if (firstProduct != null)
            {
                productId = firstProduct.Product.Id.ToString(CultureInfo.InvariantCulture);
                body      = firstProduct.Product.GetLocalized(q => q.Name);
            }
            else
            {
                productId = postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture);
                body      = postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture);
            }

            string detail = string.Join(", ",
                                        postProcessPaymentRequest.Order.OrderItems.Select(q => q.Product.GetLocalized(p => p.Name)));
            string orderId = postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture);
            string total   = ((int)(postProcessPaymentRequest.Order.OrderTotal * 100)).ToString(CultureInfo.InvariantCulture);

            var post = new RemotePost();

            post.FormName = "weixinpayment";
            post.Method   = "POST";
            post.Add("orderid", postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture));
            post.Add("total", postProcessPaymentRequest.Order.OrderTotal.ToString("0.00"));
            if (isJsPay && !string.IsNullOrWhiteSpace(openId))
            {
                var jsApiPay = new JsApiPay(_weiXinPaymentSettings, Path.Combine(_webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()), "onepagecheckout"));
                jsApiPay.Openid   = openId;
                jsApiPay.TotalFee = total;

                var unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(postProcessPaymentRequest.Order.Id, _webHelper.GetCurrentIpAddress(), _notifyUrl);

                var data = new WxPayData();


                var timestamp = CommonExtension.GetCurrentTimeStamp().ToString();
                var nonceStr  = Guid.NewGuid().ToString("N");



                data.SetValue("appId", _weiXinPaymentSettings.AppId);
                data.SetValue("timeStamp", timestamp);
                data.SetValue("nonceStr", nonceStr);
                data.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
                data.SetValue("signType", "MD5");
                var sign = data.MakeSign(_weiXinPaymentSettings.AppSecret);


                post.Add("appId", _weiXinPaymentSettings.AppId);
                post.Add("timeStamp", timestamp);
                post.Add("nonceStr", nonceStr);
                post.Add("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
                post.Add("signType", "MD5");
                post.Add("paySign", sign);

                post.Url = Path.Combine(_webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()), "Plugins/PaymentWeiXin/JsApiPayment/");
                post.Post();
            }
            else
            {
                post.Url = Path.Combine(_webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()), "Plugins/PaymentWeiXin/ProcessPayment");
                post.Add("nativeUrl", GetUrlForMethodOne(postProcessPaymentRequest.Order.Id));
                //var result = Unifiedorder(productId, body, detail, orderId, total);
                //post.Add("result", HttpUtility.HtmlEncode(result));
                post.Post();
            }
        }
Пример #19
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)
 {
 }
        public CheckoutPlaceOrderModel PlaceOrder()
        {
            var model = new CheckoutPlaceOrderModel();

            try
            {
                var processPaymentRequest = _session.Get <ProcessPaymentRequest>(Defaults.ProcessPaymentRequestKey);

                if (processPaymentRequest == null)
                {
                    model.RedirectToCart = true;
                    return(model);
                }

                //prevent 2 orders being placed within an X seconds time frame
                if (!_payPalExpressCheckoutService.IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
                {
                    throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));
                }

                //place order
                processPaymentRequest.StoreId    = _storeContext.CurrentStore.Id;
                processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
                processPaymentRequest.PaymentMethodSystemName = "Payments.PayPalExpressCheckout";
                var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);

                if (placeOrderResult.Success)
                {
                    var doExpressCheckoutPaymentResponseType = _session.Get <DoExpressCheckoutPaymentResponseType>(Defaults.CheckoutPaymentResponseTypeKey);
                    doExpressCheckoutPaymentResponseType?.LogOrderNotes(placeOrderResult.PlacedOrder.OrderGuid);
                    _session.Remove(Defaults.ProcessPaymentRequestKey);
                    var postProcessPaymentRequest = new PostProcessPaymentRequest
                    {
                        Order = placeOrderResult.PlacedOrder
                    };
                    _paymentService.PostProcessPayment(postProcessPaymentRequest);

                    if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
                    {
                        //redirection or POST has been done in PostProcessPayment
                        model.IsRedirected = true;
                        return(model);
                    }

                    model.CompletedId = placeOrderResult.PlacedOrder.Id;
                    return(model);
                }

                foreach (var error in placeOrderResult.Errors)
                {
                    model.Warnings.Add(error);
                }
            }
            catch (Exception exc)
            {
                _logger.Warning(exc.Message, exc);
                model.Warnings.Add(exc.Message);
            }

            return(model);
        }
        /// <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 builder = new StringBuilder();

            builder.Append(GetPaypalUrl());
            string cmd = string.Empty;

            if (_paypalStandardPaymentSettings.PassProductNamesAndTotals)
            {
                cmd = "_cart";
            }
            else
            {
                cmd = "_xclick";
            }
            builder.AppendFormat("?cmd={0}&business={1}", cmd, HttpUtility.UrlEncode(_paypalStandardPaymentSettings.BusinessEmail));
            if (_paypalStandardPaymentSettings.PassProductNamesAndTotals)
            {
                builder.AppendFormat("&upload=1");

                //get the items in the cart
                decimal cartTotal = decimal.Zero;
                var     cartItems = postProcessPaymentRequest.Order.OrderItems;
                int     x         = 1;
                foreach (var item in cartItems)
                {
                    var unitPriceExclTax = item.UnitPriceExclTax;
                    var priceExclTax     = item.PriceExclTax;
                    //round
                    var unitPriceExclTaxRounded = Math.Round(unitPriceExclTax, 2);
                    builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(item.Product.Name));
                    builder.AppendFormat("&amount_" + x + "={0}", unitPriceExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
                    builder.AppendFormat("&quantity_" + x + "={0}", item.Quantity);
                    x++;
                    cartTotal += priceExclTax;
                }

                //the checkout attributes that have a dollar value and send them to Paypal as items to be paid for
                var caValues = _checkoutAttributeParser.ParseCheckoutAttributeValues(postProcessPaymentRequest.Order.CheckoutAttributesXml);
                foreach (var val in caValues)
                {
                    var attPrice = _taxService.GetCheckoutAttributePrice(val, false, postProcessPaymentRequest.Order.Customer);
                    //round
                    var attPriceRounded = Math.Round(attPrice, 2);
                    if (attPrice > decimal.Zero) //if it has a price
                    {
                        var ca = val.CheckoutAttribute;
                        if (ca != null)
                        {
                            var attName = ca.Name;                                                                                         //set the name
                            builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(attName));                              //name
                            builder.AppendFormat("&amount_" + x + "={0}", attPriceRounded.ToString("0.00", CultureInfo.InvariantCulture)); //amount
                            builder.AppendFormat("&quantity_" + x + "={0}", 1);                                                            //quantity
                            x++;
                            cartTotal += attPrice;
                        }
                    }
                }

                //order totals

                //shipping
                var orderShippingExclTax        = postProcessPaymentRequest.Order.OrderShippingExclTax;
                var orderShippingExclTaxRounded = Math.Round(orderShippingExclTax, 2);
                if (orderShippingExclTax > decimal.Zero)
                {
                    builder.AppendFormat("&item_name_" + x + "={0}", "Shipping fee");
                    builder.AppendFormat("&amount_" + x + "={0}", orderShippingExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
                    builder.AppendFormat("&quantity_" + x + "={0}", 1);
                    x++;
                    cartTotal += orderShippingExclTax;
                }

                //payment method additional fee
                var paymentMethodAdditionalFeeExclTax        = postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax;
                var paymentMethodAdditionalFeeExclTaxRounded = Math.Round(paymentMethodAdditionalFeeExclTax, 2);
                if (paymentMethodAdditionalFeeExclTax > decimal.Zero)
                {
                    builder.AppendFormat("&item_name_" + x + "={0}", "Payment method fee");
                    builder.AppendFormat("&amount_" + x + "={0}", paymentMethodAdditionalFeeExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
                    builder.AppendFormat("&quantity_" + x + "={0}", 1);
                    x++;
                    cartTotal += paymentMethodAdditionalFeeExclTax;
                }

                //tax
                var orderTax        = postProcessPaymentRequest.Order.OrderTax;
                var orderTaxRounded = Math.Round(orderTax, 2);
                if (orderTax > decimal.Zero)
                {
                    //builder.AppendFormat("&tax_1={0}", orderTax.ToString("0.00", CultureInfo.InvariantCulture));

                    //add tax as item
                    builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode("Sales Tax"));                          //name
                    builder.AppendFormat("&amount_" + x + "={0}", orderTaxRounded.ToString("0.00", CultureInfo.InvariantCulture)); //amount
                    builder.AppendFormat("&quantity_" + x + "={0}", 1);                                                            //quantity

                    cartTotal += orderTax;
                    x++;
                }

                if (cartTotal > postProcessPaymentRequest.Order.OrderTotal)
                {
                    /* Take the difference between what the order total is and what it should be and use that as the "discount".
                     * The difference equals the amount of the gift card and/or reward points used.
                     */
                    decimal discountTotal = cartTotal - postProcessPaymentRequest.Order.OrderTotal;
                    discountTotal = Math.Round(discountTotal, 2);
                    //gift card or rewared point amount applied to cart in nopCommerce - shows in Paypal as "discount"
                    builder.AppendFormat("&discount_amount_cart={0}", discountTotal.ToString("0.00", CultureInfo.InvariantCulture));
                }
            }
            else
            {
                //pass order total
                builder.AppendFormat("&item_name=Order Number {0}", postProcessPaymentRequest.Order.Id);
                var orderTotal = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);
                builder.AppendFormat("&amount={0}", orderTotal.ToString("0.00", CultureInfo.InvariantCulture));
            }

            builder.AppendFormat("&custom={0}", postProcessPaymentRequest.Order.OrderGuid);
            builder.AppendFormat("&charset={0}", "utf-8");
            builder.Append(string.Format("&no_note=1&currency_code={0}", HttpUtility.UrlEncode(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode)));
            builder.AppendFormat("&invoice={0}", postProcessPaymentRequest.Order.Id);
            builder.AppendFormat("&rm=2", new object[0]);
            if (postProcessPaymentRequest.Order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                builder.AppendFormat("&no_shipping=2", new object[0]);
            }
            else
            {
                builder.AppendFormat("&no_shipping=1", new object[0]);
            }

            string returnUrl       = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/PDTHandler";
            string cancelReturnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/CancelOrder";

            builder.AppendFormat("&return={0}&cancel_return={1}", HttpUtility.UrlEncode(returnUrl), HttpUtility.UrlEncode(cancelReturnUrl));

            //Instant Payment Notification (server to server message)
            if (_paypalStandardPaymentSettings.EnableIpn)
            {
                string ipnUrl;
                if (String.IsNullOrWhiteSpace(_paypalStandardPaymentSettings.IpnUrl))
                {
                    ipnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/IPNHandler";
                }
                else
                {
                    ipnUrl = _paypalStandardPaymentSettings.IpnUrl;
                }
                builder.AppendFormat("&notify_url={0}", ipnUrl);
            }

            //address
            builder.AppendFormat("&address_override={0}", _paypalStandardPaymentSettings.AddressOverride ? "1" : "0");
            builder.AppendFormat("&first_name={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.FirstName));
            builder.AppendFormat("&last_name={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.LastName));
            builder.AppendFormat("&address1={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Address1));
            builder.AppendFormat("&address2={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Address2));
            builder.AppendFormat("&city={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.City));
            //if (!String.IsNullOrEmpty(postProcessPaymentRequest.Order.BillingAddress.PhoneNumber))
            //{
            //    //strip out all non-digit characters from phone number;
            //    string billingPhoneNumber = System.Text.RegularExpressions.Regex.Replace(postProcessPaymentRequest.Order.BillingAddress.PhoneNumber, @"\D", string.Empty);
            //    if (billingPhoneNumber.Length >= 10)
            //    {
            //        builder.AppendFormat("&night_phone_a={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(0, 3)));
            //        builder.AppendFormat("&night_phone_b={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(3, 3)));
            //        builder.AppendFormat("&night_phone_c={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(6, 4)));
            //    }
            //}
            if (postProcessPaymentRequest.Order.BillingAddress.StateProvince != null)
            {
                builder.AppendFormat("&state={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.StateProvince.Abbreviation));
            }
            else
            {
                builder.AppendFormat("&state={0}", "");
            }
            if (postProcessPaymentRequest.Order.BillingAddress.Country != null)
            {
                builder.AppendFormat("&country={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Country.TwoLetterIsoCode));
            }
            else
            {
                builder.AppendFormat("&country={0}", "");
            }
            builder.AppendFormat("&zip={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode));
            builder.AppendFormat("&email={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Email));
            _httpContext.Response.Redirect(builder.ToString());
        }
Пример #22
0
 /// <summary>
 /// 请求付款流程(需要重定向到一个第三方的支付网关使用的URL)
 /// </summary>
 /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
 public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
 {
     //顺溜支付在商城中做付款操作PaymentMethodType=Standard,所以不用跳转到其它地址支付,此方法就不会被调用
 }
Пример #23
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)
        {
            // Datos necesarios para Zona Virtual
            ProcessPaymentRequest test = new ProcessPaymentRequest();

            ZPagos.ZPagos     Pagos     = new ZPagos.ZPagos();
            ZPagosDemo.ZPagos PagosDemo = new ZPagosDemo.ZPagos();


            string[] lista_codigos = new string[1] {
                ""
            };
            string[] lista_nit_codigos = new string[1] {
                ""
            };

            double[] lista_codigos_servicio_multicredito = new double[1] {
                0
            };
            double[] lista_valores_con_iva = new double[1] {
                0
            };
            double[] lista_valores_iva = new double[1] {
                0
            };
            string Respuesta = "";
            //string Tienda = postProcessPaymentRequest.Order. _storeContext.CurrentStore.Name;
            // var form = this.Request.Form;
            //var order = _orderService.GetOrderByGuid(test.OrderGuid);
            // Respuesta = _workContext.CurrentCustomer.BillingAddress.FirstName.ToString();
            var order_id_temp = this.GenerateUniquePayementFromZP(new Random().Next(1, int.MaxValue)); //new Random().Next(1, int.MaxValue);

            //var askOrder = this.aksOrder();

            HttpContext.Current.Session.Add("payment_id", order_id_temp);
            HttpContext.Current.Session.Add("order_id", postProcessPaymentRequest.Order.Id.ToString());
            double Total_con_iva = 0;

            foreach (var item in postProcessPaymentRequest.Order.OrderItems)
            {
                Total_con_iva += (double)item.Product.Price * item.Quantity;
                //Respuesta += " " + item.Product.Price + " " + _workContext.CurrentCustomer.BillingAddress.FirstName.ToString() + _workContext.CurrentCustomer.BillingAddress.LastName;
            }
            ;  // order.BillingAddress.Email;
            Total_con_iva = Double.Parse(postProcessPaymentRequest.Order.OrderTotal.ToString());
            if (_ZonaVirtualPaymentSettings.RutaTienda.IndexOf("demo") > 0)
            {
                Respuesta = PagosDemo.inicio_pagoV2(_ZonaVirtualPaymentSettings.ID_Tienda,
                                                    _ZonaVirtualPaymentSettings.ID_Clave,
                                                    Total_con_iva,
                                                    0,
                                                    order_id_temp.ToString(),
                                                    "Compra en tienda: " + _ZonaVirtualPaymentSettings.NombreTienda,
                                                    postProcessPaymentRequest.Order.Customer.Email,
                                                    postProcessPaymentRequest.Order.Customer.Id.ToString(),
                                                    "0",
                                                    postProcessPaymentRequest.Order.Customer.BillingAddress.FirstName,
                                                    postProcessPaymentRequest.Order.Customer.BillingAddress.LastName,
                                                    postProcessPaymentRequest.Order.Customer.BillingAddress.PhoneNumber,
                                                    "Orden ID: " + postProcessPaymentRequest.Order.Id.ToString(),
                                                    "_",
                                                    "_",
                                                    _ZonaVirtualPaymentSettings.CodigoServicio.ToString(),
                                                    null, null, null, null, 0);
            }
            else
            {
                Respuesta = Pagos.inicio_pagoV2(_ZonaVirtualPaymentSettings.ID_Tienda,
                                                _ZonaVirtualPaymentSettings.ID_Clave,
                                                Total_con_iva,
                                                0,
                                                order_id_temp.ToString(),
                                                "Compra en tienda: " + _ZonaVirtualPaymentSettings.NombreTienda,
                                                postProcessPaymentRequest.Order.Customer.Email,
                                                postProcessPaymentRequest.Order.Customer.Id.ToString(),
                                                "0",
                                                postProcessPaymentRequest.Order.Customer.BillingAddress.FirstName,
                                                postProcessPaymentRequest.Order.Customer.BillingAddress.LastName,
                                                postProcessPaymentRequest.Order.Customer.BillingAddress.PhoneNumber,
                                                "Orden ID: " + postProcessPaymentRequest.Order.Id.ToString(),
                                                "_",
                                                "_",
                                                _ZonaVirtualPaymentSettings.CodigoServicio.ToString(),
                                                null, null, null, null, 0);
            }

            string URL = _ZonaVirtualPaymentSettings.RutaTienda + "?estado_pago=iniciar_pago&identificador=" + Respuesta;


            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", "FormName"));
            System.Web.HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", "FormName", "POST", URL));
            System.Web.HttpContext.Current.Response.Write("</form>");
            System.Web.HttpContext.Current.Response.Write("</body></html>");
            System.Web.HttpContext.Current.Response.End();
        }
Пример #24
0
        public PostProcessPaymentResponse PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var resp = new PostProcessPaymentResponse();

            return(resp);
        }
Пример #25
0
        /// <summary>
        /// Get all PayPal line items
        /// </summary>
        /// <param name="postProcessPaymentRequest">Post process paymenmt request object</param>
        /// <param name="checkoutAttributeValues">List with checkout attribute values</param>
        /// <param name="cartTotal">Receives the calculated cart total amount</param>
        /// <returns>All items for PayPal Standard API</returns>
        public List <PayPalLineItem> GetLineItems(PostProcessPaymentRequest postProcessPaymentRequest, out decimal cartTotal)
        {
            cartTotal = decimal.Zero;

            var order = postProcessPaymentRequest.Order;
            var lst   = new List <PayPalLineItem>();

            // order items
            foreach (var orderItem in order.OrderItems)
            {
                var item = new PayPalLineItem()
                {
                    Type     = PayPalItemType.CartItem,
                    Name     = orderItem.Product.GetLocalized(x => x.Name),
                    Quantity = orderItem.Quantity,
                    Amount   = orderItem.UnitPriceExclTax
                };
                lst.Add(item);

                cartTotal += orderItem.PriceExclTax;
            }

            // checkout attributes.... are included in order total
            //foreach (var caValue in checkoutAttributeValues)
            //{
            //	var attributePrice = _taxService.GetCheckoutAttributePrice(caValue, false, order.Customer);

            //	if (attributePrice > decimal.Zero && caValue.CheckoutAttribute != null)
            //	{
            //		var item = new PayPalLineItem()
            //		{
            //			Type = PayPalItemType.CheckoutAttribute,
            //			Name = caValue.CheckoutAttribute.GetLocalized(x => x.Name),
            //			Quantity = 1,
            //			Amount = attributePrice
            //		};
            //		lst.Add(item);

            //		cartTotal += attributePrice;
            //	}
            //}

            // shipping
            if (order.OrderShippingExclTax > decimal.Zero)
            {
                var item = new PayPalLineItem()
                {
                    Type     = PayPalItemType.Shipping,
                    Name     = T("Plugins.Payments.PayPalStandard.ShippingFee").Text,
                    Quantity = 1,
                    Amount   = order.OrderShippingExclTax
                };
                lst.Add(item);

                cartTotal += order.OrderShippingExclTax;
            }

            // payment fee
            if (order.PaymentMethodAdditionalFeeExclTax > decimal.Zero)
            {
                var item = new PayPalLineItem()
                {
                    Type     = PayPalItemType.PaymentFee,
                    Name     = T("Plugins.Payments.PayPalStandard.PaymentMethodFee").Text,
                    Quantity = 1,
                    Amount   = order.PaymentMethodAdditionalFeeExclTax
                };
                lst.Add(item);

                cartTotal += order.PaymentMethodAdditionalFeeExclTax;
            }

            // tax
            if (order.OrderTax > decimal.Zero)
            {
                var item = new PayPalLineItem()
                {
                    Type     = PayPalItemType.Tax,
                    Name     = T("Plugins.Payments.PayPalStandard.SalesTax").Text,
                    Quantity = 1,
                    Amount   = order.OrderTax
                };
                lst.Add(item);

                cartTotal += order.OrderTax;
            }

            return(lst);
        }
Пример #26
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 service   = "create_forex_trade";
            var partner   = _aliPayPaymentSettings.Partner;
            var notifyUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentAliPay/Notify";
            var returnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentAliPay/Return";


            var subject      = _storeContext.CurrentStore.Name;
            var inputCharset = @"UTF-8";
            var body         = _storeContext.CurrentStore.Name;
            var outTradeNo   = postProcessPaymentRequest.Order.Id.ToString();
            var rmbFee       = postProcessPaymentRequest.Order.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture);

            //string sellerEmail = _aliPayPaymentSettings.SellerEmail;

            var key = _aliPayPaymentSettings.Key;


            string[] param =
            {
                "service=" + service,
                "partner=" + partner,
                "notify_url=" + notifyUrl,
                "return_url=" + returnUrl,
                "subject=" + subject,
                "_input_charset=" + inputCharset,
                "body=" + body,
                "out_trade_no=" + outTradeNo,
                "rmb_fee=" + rmbFee,
                "currency=AUD"
            };

            var sortedParam = BubbleSort(param);
            var sign        = GetSign(sortedParam, inputCharset, key);
            var signType    = "MD5";

            var finalParamList = sortedParam.ToList();

            finalParamList.Add("sign=" + sign);
            finalParamList.Add("sign_type=" + signType);


            var post = new RemotePost {
                FormName = "alipaysubmit"
            };
            var url   = @"https://mapi.alipay.com/gateway.do";
            var count = 0;

            foreach (var paramItem in finalParamList)
            {
                if (count > 0)
                {
                    url += @"&";
                }
                else
                {
                    url += @"?";
                }

                url += paramItem;
                count++;
            }

            post.Url = url;
            //post.Url = Path.Combine(_webHelper.GetStoreHost(_webHelper.IsCurrentConnectionSecured()), "Plugins/PaymentAlipay/ProcessPayment");
            //post.Add("url", url);
            //post.Add("orderid", postProcessPaymentRequest.Order.Id.ToString(CultureInfo.InvariantCulture));
            //post.Add("total", postProcessPaymentRequest.Order.OrderTotal.ToString("0.00"));
            post.Post();
        }
        /// <summary>
        /// Add order items to the request query parameters
        /// </summary>
        /// <param name="parameters">Query parameters</param>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        private async Task AddItemsParameters(IDictionary <string, string> parameters, PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //upload order items
            parameters.Add("cmd", "_cart");
            parameters.Add("upload", "1");

            var cartTotal        = decimal.Zero;
            var roundedCartTotal = decimal.Zero;
            var itemCount        = 1;

            //add shopping cart items
            foreach (var item in postProcessPaymentRequest.Order.OrderItems)
            {
                var product = await _productService.GetProductById(item.ProductId);

                var roundedItemPrice = Math.Round(item.UnitPriceExclTax, 2);

                //add query parameters
                parameters.Add($"item_name_{itemCount}", product.Name);
                parameters.Add($"amount_{itemCount}", roundedItemPrice.ToString("0.00", CultureInfo.InvariantCulture));
                parameters.Add($"quantity_{itemCount}", item.Quantity.ToString());

                cartTotal        += (item.PriceExclTax);
                roundedCartTotal += roundedItemPrice * item.Quantity;
                itemCount++;
            }

            //add checkout attributes as order items
            var checkoutAttributeValues = await _checkoutAttributeParser.ParseCheckoutAttributeValue(postProcessPaymentRequest.Order.CheckoutAttributesXml);

            var currencyService = _serviceProvider.GetRequiredService <ICurrencyService>();
            var workContext     = _serviceProvider.GetRequiredService <IWorkContext>();
            var customer        = await _serviceProvider.GetRequiredService <ICustomerService>().GetCustomerById(postProcessPaymentRequest.Order.CustomerId);

            foreach (var attributeValue in checkoutAttributeValues)
            {
                var attributePrice = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, false, customer);

                if (attributePrice.checkoutPrice > 0)
                {
                    decimal roundedAttributePrice = Math.Round(await currencyService.ConvertFromPrimaryStoreCurrency(attributePrice.checkoutPrice, workContext.WorkingCurrency), 2);
                    //add query parameters
                    if (attributeValue.ca != null)
                    {
                        parameters.Add($"item_name_{itemCount}", attributeValue.ca.Name);
                        parameters.Add($"amount_{itemCount}", roundedAttributePrice.ToString("0.00", CultureInfo.InvariantCulture));
                        parameters.Add($"quantity_{itemCount}", "1");

                        cartTotal        += attributePrice.checkoutPrice;
                        roundedCartTotal += roundedAttributePrice;
                        itemCount++;
                    }
                }
            }

            //add shipping fee as a separate order item, if it has price
            var roundedShippingPrice = Math.Round(postProcessPaymentRequest.Order.OrderShippingExclTax, 2);

            if (roundedShippingPrice > decimal.Zero)
            {
                parameters.Add($"item_name_{itemCount}", "Shipping fee");
                parameters.Add($"amount_{itemCount}", roundedShippingPrice.ToString("0.00", CultureInfo.InvariantCulture));
                parameters.Add($"quantity_{itemCount}", "1");

                cartTotal        += (postProcessPaymentRequest.Order.OrderShippingExclTax);
                roundedCartTotal += roundedShippingPrice;
                itemCount++;
            }

            //add payment method additional fee as a separate order item, if it has price
            var roundedPaymentMethodPrice = Math.Round(postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax, 2);

            if (roundedPaymentMethodPrice > decimal.Zero)
            {
                parameters.Add($"item_name_{itemCount}", "Payment method fee");
                parameters.Add($"amount_{itemCount}", roundedPaymentMethodPrice.ToString("0.00", CultureInfo.InvariantCulture));
                parameters.Add($"quantity_{itemCount}", "1");

                cartTotal        += (postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax);
                roundedCartTotal += roundedPaymentMethodPrice;
                itemCount++;
            }

            //add tax as a separate order item, if it has positive amount
            var roundedTaxAmount = Math.Round(postProcessPaymentRequest.Order.OrderTax, 2);

            if (roundedTaxAmount > decimal.Zero)
            {
                parameters.Add($"item_name_{itemCount}", "Tax amount");
                parameters.Add($"amount_{itemCount}", roundedTaxAmount.ToString("0.00", CultureInfo.InvariantCulture));
                parameters.Add($"quantity_{itemCount}", "1");

                cartTotal        += (postProcessPaymentRequest.Order.OrderTax);
                roundedCartTotal += roundedTaxAmount;
                itemCount++;
            }

            if (cartTotal > postProcessPaymentRequest.Order.OrderTotal)
            {
                //get the difference between what the order total is and what it should be and use that as the "discount"
                var discountTotal = Math.Round(cartTotal - (postProcessPaymentRequest.Order.OrderTotal), 2);
                roundedCartTotal -= discountTotal;

                //gift card or rewarded point amount applied to cart in nopCommerce - shows in PayPal as "discount"
                parameters.Add("discount_amount_cart", discountTotal.ToString("0.00", CultureInfo.InvariantCulture));
            }

            //save order total that actually sent to PayPal (used for PDT order total validation)
            await _genericAttributeService.SaveAttribute(postProcessPaymentRequest.Order, PaypalHelper.OrderTotalSentToPayPal, roundedCartTotal);
        }
Пример #28
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 myUtility      = new PayuHelper();
            var orderId        = postProcessPaymentRequest.Order.Id;
            var billingAddress = _addressService.GetAddressById(postProcessPaymentRequest.Order.BillingAddressId);
            var countryName    = string.Empty;
            var stateName      = string.Empty;

            if (billingAddress != null)
            {
                var country = _countryService.GetCountryById((int)billingAddress.CountryId);
                if (country != null)
                {
                    countryName = country.ThreeLetterIsoCode;
                }

                if (billingAddress.StateProvinceId != null)
                {
                    var state = _stateProvinceService.GetStateProvinceById((int)billingAddress.StateProvinceId);
                    if (state != null)
                    {
                        stateName = state.Abbreviation;
                    }
                }
            }

            var threeletter     = string.Empty;
            var abbreviation    = string.Empty;
            var shippingaddress = _addressService.GetAddressById((int)postProcessPaymentRequest.Order.ShippingAddressId);

            if (shippingaddress != null)
            {
                var country = _countryService.GetCountryById((int)shippingaddress.CountryId);
                if (country != null)
                {
                    threeletter = country.ThreeLetterIsoCode;
                }

                if (shippingaddress.StateProvinceId != null)
                {
                    var state = _stateProvinceService.GetStateProvinceById((int)shippingaddress.StateProvinceId);
                    if (state != null)
                    {
                        abbreviation = state.Abbreviation;
                    }
                }
            }


            var remotePostHelper = new RemotePost();

            remotePostHelper.FormName = "PayuForm";
            remotePostHelper.Url      = _PayuPaymentSettings.PayUri;
            remotePostHelper.Add("key", _PayuPaymentSettings.MerchantId.ToString());
            remotePostHelper.Add("amount", postProcessPaymentRequest.Order.OrderTotal.ToString(new CultureInfo("en-US", false).NumberFormat));
            remotePostHelper.Add("productinfo", "productinfo");
            remotePostHelper.Add("Currency", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode);
            remotePostHelper.Add("Order_Id", orderId.ToString());
            remotePostHelper.Add("txnid", orderId.ToString());
            remotePostHelper.Add("service_provider", "payu_paisa");
            remotePostHelper.Add("surl", _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayu/Return");
            remotePostHelper.Add("furl", _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayu/Return");
            remotePostHelper.Add("hash", myUtility.getchecksum(_PayuPaymentSettings.MerchantId.ToString(),
                                                               postProcessPaymentRequest.Order.Id.ToString(), postProcessPaymentRequest.Order.OrderTotal.ToString(new CultureInfo("en-US", false).NumberFormat),
                                                               "productinfo", billingAddress?.FirstName.ToString(),
                                                               billingAddress?.Email.ToString(), _PayuPaymentSettings.Key));


            //Billing details
            remotePostHelper.Add("firstname", billingAddress?.FirstName.ToString());
            remotePostHelper.Add("billing_cust_address", billingAddress?.Address1);
            remotePostHelper.Add("phone", billingAddress?.PhoneNumber);
            remotePostHelper.Add("email", billingAddress?.Email.ToString());
            remotePostHelper.Add("billing_cust_city", billingAddress?.City);

            remotePostHelper.Add("billing_cust_state", stateName);

            remotePostHelper.Add("billing_zip_code", billingAddress?.ZipPostalCode);

            remotePostHelper.Add("billing_cust_country", countryName);


            //Delivery details

            if (postProcessPaymentRequest.Order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                remotePostHelper.Add("delivery_cust_name", shippingaddress.FirstName);
                remotePostHelper.Add("delivery_cust_address", shippingaddress.Address1);
                remotePostHelper.Add("delivery_cust_notes", string.Empty);
                remotePostHelper.Add("delivery_cust_tel", shippingaddress.PhoneNumber);
                remotePostHelper.Add("delivery_cust_city", shippingaddress.City);

                remotePostHelper.Add("delivery_cust_state", abbreviation);

                remotePostHelper.Add("delivery_zip_code", shippingaddress?.ZipPostalCode);


                remotePostHelper.Add("delivery_cust_country", threeletter);
            }

            //  remotePostHelper.Add("Merchant_Param", _PayuPaymentSettings.MerchantParam);
            remotePostHelper.Post();
        }
        /// <summary>
        /// Add order items to the request query parameters
        /// </summary>
        /// <param name="parameters">Query parameters</param>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        private void AddItemsParameters(IDictionary <string, string> parameters, PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //upload order items
            parameters.Add("cmd", "_cart");
            parameters.Add("upload", "1");

            var cartTotal        = decimal.Zero;
            var roundedCartTotal = decimal.Zero;
            var itemCount        = 1;

            //add shopping cart items
            foreach (var item in postProcessPaymentRequest.Order.OrderItems)
            {
                var product = _productService.GetProductById(item.ProductId);

                var roundedItemPrice = Math.Round(item.UnitPriceExclTax, 2);

                //add query parameters
                parameters.Add($"item_name_{itemCount}", product.Name);
                //parameters.Add($"amount_{itemCount}", roundedItemPrice.ToString("0.00", CultureInfo.InvariantCulture));
                //parameters.Add($"quantity_{itemCount}", item.Quantity.ToString());

                cartTotal        += item.PriceExclTax;
                roundedCartTotal += roundedItemPrice * item.Quantity;
                itemCount++;
            }

            //add checkout attributes as order items
            var checkoutAttributeValues = _checkoutAttributeParser.ParseCheckoutAttributeValues(postProcessPaymentRequest.Order.CheckoutAttributesXml);
            var customer = EngineContext.Current.Resolve <ICustomerService>().GetCustomerById(postProcessPaymentRequest.Order.CustomerId);

            foreach (var attributeValue in checkoutAttributeValues)
            {
                var attributePrice = _taxService.GetCheckoutAttributePrice(attributeValue, false, customer);
                if (attributePrice > 0)
                {
                    var roundedAttributePrice = Math.Round(attributePrice, 2);

                    //add query parameters
                    var attribute = EngineContext.Current.Resolve <ICheckoutAttributeService>().GetCheckoutAttributeById(attributeValue.CheckoutAttributeId);
                    if (attribute != null)
                    {
                        parameters.Add($"item_name_{itemCount}", attribute.Name);
                        //parameters.Add($"amount_{itemCount}", roundedAttributePrice.ToString("0.00", CultureInfo.InvariantCulture));
                        //parameters.Add($"quantity_{itemCount}", "1");

                        cartTotal        += attributePrice;
                        roundedCartTotal += roundedAttributePrice;
                        itemCount++;
                    }
                }
            }

            //add shipping fee as a separate order item, if it has price
            var roundedShippingPrice = Math.Round(postProcessPaymentRequest.Order.OrderShippingExclTax, 2);

            if (roundedShippingPrice > decimal.Zero)
            {
                parameters.Add($"item_name_{itemCount}", "Shipping fee");
                //parameters.Add($"amount_{itemCount}", roundedShippingPrice.ToString("0.00", CultureInfo.InvariantCulture));
                //parameters.Add($"quantity_{itemCount}", "1");

                cartTotal        += postProcessPaymentRequest.Order.OrderShippingExclTax;
                roundedCartTotal += roundedShippingPrice;
                itemCount++;
            }

            //add payment method additional fee as a separate order item, if it has price
            var roundedPaymentMethodPrice = Math.Round(postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax, 2);

            if (roundedPaymentMethodPrice > decimal.Zero)
            {
                parameters.Add($"item_name_{itemCount}", "Payment method fee");
                //parameters.Add($"amount_{itemCount}", roundedPaymentMethodPrice.ToString("0.00", CultureInfo.InvariantCulture));
                //parameters.Add($"quantity_{itemCount}", "1");

                cartTotal        += postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax;
                roundedCartTotal += roundedPaymentMethodPrice;
                itemCount++;
            }

            //add tax as a separate order item, if it has positive amount
            var roundedTaxAmount = Math.Round(postProcessPaymentRequest.Order.OrderTax, 2);

            if (roundedTaxAmount > decimal.Zero)
            {
                parameters.Add($"item_name_{itemCount}", "Tax amount");
                //parameters.Add($"amount_{itemCount}", roundedTaxAmount.ToString("0.00", CultureInfo.InvariantCulture));
                //parameters.Add($"quantity_{itemCount}", "1");

                cartTotal        += postProcessPaymentRequest.Order.OrderTax;
                roundedCartTotal += roundedTaxAmount;
                itemCount++;
            }

            if (cartTotal > postProcessPaymentRequest.Order.OrderTotal)
            {
                //get the difference between what the order total is and what it should be and use that as the "discount"
                var discountTotal = Math.Round(cartTotal - postProcessPaymentRequest.Order.OrderTotal, 2);
                roundedCartTotal -= discountTotal;

                //gift card or rewarded point amount applied to cart in nopCommerce - shows in MOLPay as "discount"
                parameters.Add("discount_amount_cart", discountTotal.ToString("0.00", CultureInfo.InvariantCulture));
            }

            //save order total that actually sent to MOLPay (used for PDT order total validation)
            _genericAttributeService.SaveAttribute(postProcessPaymentRequest.Order, MOLPayHelper.OrderTotalSentToMOLPay, roundedCartTotal);
        }
Пример #30
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)
        {
            //string gateway = "https://www.alipay.com/cooperate/gateway.do?";
            //string gateway = "https://mapi.alipay.com/gateway.do?";
            string service = "create_direct_pay_by_user";

            string seller_email  = _aliPayPaymentSettings.SellerEmail;
            string sign_type     = "MD5";
            string key           = _aliPayPaymentSettings.Key;
            string partner       = _aliPayPaymentSettings.Partner;
            string input_charset = "utf-8";

            string show_url = "http://www.alipay.com/";

            string out_trade_no = postProcessPaymentRequest.Order.Id.ToString();
            string subject      = _storeContext.CurrentStore.Name;
            string body         = "Order from " + _storeContext.CurrentStore.Name;
            string total_fee    = postProcessPaymentRequest.Order.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture);
            //string total_fee = "0.01";

            string notify_url = _webHelper.GetStoreLocation(false) + "Plugins/PaymentAliPay/Notify";
            string return_url = _webHelper.GetStoreLocation(false) + "Plugins/PaymentAliPay/Return/" + out_trade_no;

            string[] para =
            {
                "service=" + service,
                "partner=" + partner,
                "seller_email=" + seller_email,
                "out_trade_no=" + out_trade_no,
                "subject=" + subject,
                "body=" + body,
                "total_fee=" + total_fee,
                "show_url=" + show_url,
                "payment_type=1",
                "notify_url=" + notify_url,
                "return_url=" + return_url,
                "_input_charset=" + input_charset
            };

            string aliay_url = CreatUrl(
                para,
                input_charset,
                key
                );
            var post = new RemotePost();

            post.FormName = "alipaysubmit";
            // post.Url = "https://www.alipay.com/cooperate/gateway.do?_input_charset=utf-8";
            post.Url    = "https://mapi.alipay.com/gateway.do?_input_charset=utf-8";
            post.Method = "POST";

            post.Add("service", service);
            post.Add("partner", partner);
            post.Add("seller_email", seller_email);
            post.Add("out_trade_no", out_trade_no);
            post.Add("subject", subject);
            post.Add("body", body);
            post.Add("total_fee", total_fee);
            post.Add("show_url", show_url);
            post.Add("return_url", return_url);
            post.Add("notify_url", notify_url);
            post.Add("payment_type", "1");
            post.Add("sign", aliay_url);
            post.Add("sign_type", sign_type);

            post.Post();
        }
Пример #31
0
        /// <summary>
        /// Get all PayPal line items
        /// </summary>
        /// <param name="postProcessPaymentRequest">Post process paymenmt request object</param>
        /// <param name="checkoutAttributeValues">List with checkout attribute values</param>
        /// <param name="cartTotal">Receives the calculated cart total amount</param>
        /// <returns>All items for PayPal Standard API</returns>
        public List <PayPalLineItem> GetLineItems(PostProcessPaymentRequest postProcessPaymentRequest, out decimal cartTotal)
        {
            cartTotal = decimal.Zero;

            var order = postProcessPaymentRequest.Order;
            var lst   = new List <PayPalLineItem>();

            // Order items... checkout attributes are included in order total
            foreach (var orderItem in order.OrderItems)
            {
                var item = new PayPalLineItem
                {
                    Type     = PayPalItemType.CartItem,
                    Name     = orderItem.Product.GetLocalized(x => x.Name),
                    Quantity = orderItem.Quantity,
                    Amount   = orderItem.UnitPriceExclTax
                };
                lst.Add(item);

                cartTotal += orderItem.PriceExclTax;
            }

            // Shipping
            if (order.OrderShippingExclTax > decimal.Zero)
            {
                var item = new PayPalLineItem
                {
                    Type     = PayPalItemType.Shipping,
                    Name     = T("Plugins.Payments.PayPalStandard.ShippingFee").Text,
                    Quantity = 1,
                    Amount   = order.OrderShippingExclTax
                };
                lst.Add(item);

                cartTotal += order.OrderShippingExclTax;
            }

            // Payment fee
            if (order.PaymentMethodAdditionalFeeExclTax > decimal.Zero)
            {
                var item = new PayPalLineItem
                {
                    Type     = PayPalItemType.PaymentFee,
                    Name     = T("Plugins.Payments.PayPal.PaymentMethodFee").Text,
                    Quantity = 1,
                    Amount   = order.PaymentMethodAdditionalFeeExclTax
                };
                lst.Add(item);

                cartTotal += order.PaymentMethodAdditionalFeeExclTax;
            }

            // Tax
            if (order.OrderTax > decimal.Zero)
            {
                var item = new PayPalLineItem
                {
                    Type     = PayPalItemType.Tax,
                    Name     = T("Plugins.Payments.PayPalStandard.SalesTax").Text,
                    Quantity = 1,
                    Amount   = order.OrderTax
                };
                lst.Add(item);

                cartTotal += order.OrderTax;
            }

            return(lst);
        }
Пример #32
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 Task PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
 {
     //nothing
     return(Task.CompletedTask);
 }
Пример #33
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 override void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            if (postProcessPaymentRequest.Order.PaymentStatus == PaymentStatus.Paid)
            {
                return;
            }

            var store    = _services.StoreService.GetStoreById(postProcessPaymentRequest.Order.StoreId);
            var settings = _services.Settings.LoadSetting <PayPalStandardPaymentSettings>(postProcessPaymentRequest.Order.StoreId);

            var builder = new StringBuilder();

            builder.Append(settings.GetPayPalUrl());

            string orderNumber = postProcessPaymentRequest.Order.GetOrderNumber();
            string cmd         = (settings.PassProductNamesAndTotals ? "_cart" : "_xclick");

            builder.AppendFormat("?cmd={0}&business={1}", cmd, HttpUtility.UrlEncode(settings.BusinessEmail));

            if (settings.PassProductNamesAndTotals)
            {
                builder.AppendFormat("&upload=1");

                int     index     = 0;
                decimal cartTotal = decimal.Zero;
                //var caValues = _checkoutAttributeParser.ParseCheckoutAttributeValues(postProcessPaymentRequest.Order.CheckoutAttributesXml);

                var lineItems = GetLineItems(postProcessPaymentRequest, out cartTotal);

                AdjustLineItemAmounts(lineItems, postProcessPaymentRequest);

                foreach (var item in lineItems.OrderBy(x => (int)x.Type))
                {
                    ++index;
                    builder.AppendFormat("&item_name_" + index + "={0}", HttpUtility.UrlEncode(item.Name));
                    builder.AppendFormat("&amount_" + index + "={0}", item.AmountRounded.ToString("0.00", CultureInfo.InvariantCulture));
                    builder.AppendFormat("&quantity_" + index + "={0}", item.Quantity);
                }

                #region old code

                //var cartItems = postProcessPaymentRequest.Order.OrderItems;
                //int x = 1;
                //foreach (var item in cartItems)
                //{
                //	var unitPriceExclTax = item.UnitPriceExclTax;
                //	var priceExclTax = item.PriceExclTax;
                //	//round
                //	var unitPriceExclTaxRounded = Math.Round(unitPriceExclTax, 2);

                //	builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(item.Product.Name));
                //	builder.AppendFormat("&amount_" + x + "={0}", unitPriceExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
                //	builder.AppendFormat("&quantity_" + x + "={0}", item.Quantity);
                //	x++;
                //	cartTotal += priceExclTax;
                //}

                ////the checkout attributes that have a dollar value and send them to Paypal as items to be paid for
                //foreach (var val in caValues)
                //{
                //	var attPrice = _taxService.GetCheckoutAttributePrice(val, false, postProcessPaymentRequest.Order.Customer);
                //	//round
                //	var attPriceRounded = Math.Round(attPrice, 2);
                //	if (attPrice > decimal.Zero) //if it has a price
                //	{
                //		var ca = val.CheckoutAttribute;
                //		if (ca != null)
                //		{
                //			var attName = ca.Name; //set the name
                //			builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(attName)); //name
                //			builder.AppendFormat("&amount_" + x + "={0}", attPriceRounded.ToString("0.00", CultureInfo.InvariantCulture)); //amount
                //			builder.AppendFormat("&quantity_" + x + "={0}", 1); //quantity
                //			x++;
                //			cartTotal += attPrice;
                //		}
                //	}
                //}

                ////order totals

                ////shipping
                //var orderShippingExclTax = postProcessPaymentRequest.Order.OrderShippingExclTax;
                //var orderShippingExclTaxRounded = Math.Round(orderShippingExclTax, 2);
                //if (orderShippingExclTax > decimal.Zero)
                //{
                //	builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(_localizationService.GetResource("Plugins.Payments.PayPalStandard.ShippingFee")));
                //	builder.AppendFormat("&amount_" + x + "={0}", orderShippingExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
                //	builder.AppendFormat("&quantity_" + x + "={0}", 1);
                //	x++;
                //	cartTotal += orderShippingExclTax;
                //}

                ////payment method additional fee
                //var paymentMethodAdditionalFeeExclTax = postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax;
                //var paymentMethodAdditionalFeeExclTaxRounded = Math.Round(paymentMethodAdditionalFeeExclTax, 2);
                //if (paymentMethodAdditionalFeeExclTax > decimal.Zero)
                //{
                //	builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(_localizationService.GetResource("Plugins.Payments.PayPalStandard.PaymentMethodFee")));
                //	builder.AppendFormat("&amount_" + x + "={0}", paymentMethodAdditionalFeeExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
                //	builder.AppendFormat("&quantity_" + x + "={0}", 1);
                //	x++;
                //	cartTotal += paymentMethodAdditionalFeeExclTax;
                //}

                ////tax
                //var orderTax = postProcessPaymentRequest.Order.OrderTax;
                //var orderTaxRounded = Math.Round(orderTax, 2);
                //if (orderTax > decimal.Zero)
                //{
                //	//builder.AppendFormat("&tax_1={0}", orderTax.ToString("0.00", CultureInfo.InvariantCulture));

                //	//add tax as item
                //	builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(_localizationService.GetResource("Plugins.Payments.PayPalStandard.SalesTax")));
                //	builder.AppendFormat("&amount_" + x + "={0}", orderTaxRounded.ToString("0.00", CultureInfo.InvariantCulture)); //amount
                //	builder.AppendFormat("&quantity_" + x + "={0}", 1); //quantity

                //	cartTotal += orderTax;
                //	x++;
                //}

                #endregion

                if (cartTotal > postProcessPaymentRequest.Order.OrderTotal)
                {
                    // Take the difference between what the order total is and what it should be and use that as the "discount".
                    // The difference equals the amount of the gift card and/or reward points used.
                    decimal discountTotal = cartTotal - postProcessPaymentRequest.Order.OrderTotal;
                    discountTotal = Math.Round(discountTotal, 2);

                    //gift card or rewared point amount applied to cart in SmartStore.NET - shows in Paypal as "discount"
                    builder.AppendFormat("&discount_amount_cart={0}", discountTotal.ToString("0.00", CultureInfo.InvariantCulture));
                }
            }
            else
            {
                //pass order total
                string totalItemName = "{0} {1}".FormatWith(T("Checkout.OrderNumber"), orderNumber);
                builder.AppendFormat("&item_name={0}", HttpUtility.UrlEncode(totalItemName));
                var orderTotal = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);
                builder.AppendFormat("&amount={0}", orderTotal.ToString("0.00", CultureInfo.InvariantCulture));
            }

            builder.AppendFormat("&custom={0}", postProcessPaymentRequest.Order.OrderGuid);
            builder.AppendFormat("&charset={0}", "utf-8");
            builder.Append(string.Format("&no_note=1&currency_code={0}", HttpUtility.UrlEncode(store.PrimaryStoreCurrency.CurrencyCode)));
            builder.AppendFormat("&invoice={0}", HttpUtility.UrlEncode(orderNumber));
            builder.AppendFormat("&rm=2", new object[0]);

            Address address = null;

            if (postProcessPaymentRequest.Order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                address = postProcessPaymentRequest.Order.ShippingAddress ?? postProcessPaymentRequest.Order.BillingAddress;

                // 0 means the buyer is prompted to include a shipping address.
                builder.AppendFormat("&no_shipping={0}", settings.IsShippingAddressRequired ? "2" : "1");
            }
            else
            {
                address = postProcessPaymentRequest.Order.BillingAddress;

                builder.AppendFormat("&no_shipping=1", new object[0]);
            }

            var returnUrl       = _services.WebHelper.GetStoreLocation(store.SslEnabled) + "Plugins/SmartStore.PayPal/PayPalStandard/PDTHandler";
            var cancelReturnUrl = _services.WebHelper.GetStoreLocation(store.SslEnabled) + "Plugins/SmartStore.PayPal/PayPalStandard/CancelOrder";
            builder.AppendFormat("&return={0}&cancel_return={1}", HttpUtility.UrlEncode(returnUrl), HttpUtility.UrlEncode(cancelReturnUrl));

            //Instant Payment Notification (server to server message)
            if (settings.EnableIpn)
            {
                string ipnUrl;
                if (String.IsNullOrWhiteSpace(settings.IpnUrl))
                {
                    ipnUrl = _services.WebHelper.GetStoreLocation(store.SslEnabled) + "Plugins/SmartStore.PayPal/PayPalStandard/IPNHandler";
                }
                else
                {
                    ipnUrl = settings.IpnUrl;
                }
                builder.AppendFormat("&notify_url={0}", ipnUrl);
            }

            // Address
            builder.AppendFormat("&address_override={0}", settings.UsePayPalAddress ? "0" : "1");
            builder.AppendFormat("&first_name={0}", HttpUtility.UrlEncode(address.FirstName));
            builder.AppendFormat("&last_name={0}", HttpUtility.UrlEncode(address.LastName));
            builder.AppendFormat("&address1={0}", HttpUtility.UrlEncode(address.Address1));
            builder.AppendFormat("&address2={0}", HttpUtility.UrlEncode(address.Address2));
            builder.AppendFormat("&city={0}", HttpUtility.UrlEncode(address.City));
            //if (!String.IsNullOrEmpty(address.PhoneNumber))
            //{
            //    //strip out all non-digit characters from phone number;
            //    string billingPhoneNumber = System.Text.RegularExpressions.Regex.Replace(address.PhoneNumber, @"\D", string.Empty);
            //    if (billingPhoneNumber.Length >= 10)
            //    {
            //        builder.AppendFormat("&night_phone_a={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(0, 3)));
            //        builder.AppendFormat("&night_phone_b={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(3, 3)));
            //        builder.AppendFormat("&night_phone_c={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(6, 4)));
            //    }
            //}
            if (address.StateProvince != null)
            {
                builder.AppendFormat("&state={0}", HttpUtility.UrlEncode(address.StateProvince.Abbreviation));
            }
            else
            {
                builder.AppendFormat("&state={0}", "");
            }

            if (address.Country != null)
            {
                builder.AppendFormat("&country={0}", HttpUtility.UrlEncode(address.Country.TwoLetterIsoCode));
            }
            else
            {
                builder.AppendFormat("&country={0}", "");
            }

            builder.AppendFormat("&zip={0}", HttpUtility.UrlEncode(address.ZipPostalCode));
            builder.AppendFormat("&email={0}", HttpUtility.UrlEncode(address.Email));

            postProcessPaymentRequest.RedirectUrl = builder.ToString();
        }
Пример #34
0
        public ActionResult ConfirmOrder(FormCollection form)
        {
            //validation
            var storeId  = _storeContext.CurrentStore.Id;
            var customer = _workContext.CurrentCustomer;
            var cart     = customer.GetCartItems(ShoppingCartType.ShoppingCart, storeId);

            if (cart.Count == 0)
            {
                return(RedirectToRoute("ShoppingCart"));
            }

            if ((customer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
            {
                return(new HttpUnauthorizedResult());
            }

            var model = new CheckoutConfirmModel();
            PlaceOrderResult          placeOrderResult          = null;
            PostProcessPaymentRequest postProcessPaymentRequest = null;

            try
            {
                var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
                    if (IsPaymentWorkflowRequired(cart))
                    {
                        return(RedirectToAction("PaymentMethod"));
                    }

                    processPaymentRequest = new ProcessPaymentRequest();
                }

                //prevent 2 orders being placed within an X seconds time frame
                if (!IsMinimumOrderPlacementIntervalValid(customer))
                {
                    throw new Exception(T("Checkout.MinOrderPlacementInterval"));
                }

                //place order
                processPaymentRequest.StoreId    = storeId;
                processPaymentRequest.CustomerId = customer.Id;
                processPaymentRequest.PaymentMethodSystemName = customer.GetAttribute <string>(SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, storeId);

                var placeOrderExtraData = new Dictionary <string, string>();
                placeOrderExtraData["CustomerComment"]               = form["customercommenthidden"];
                placeOrderExtraData["SubscribeToNewsLetter"]         = form["SubscribeToNewsLetterHidden"];
                placeOrderExtraData["AcceptThirdPartyEmailHandOver"] = form["AcceptThirdPartyEmailHandOverHidden"];

                placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest, placeOrderExtraData);

                if (!placeOrderResult.Success)
                {
                    model.Warnings.AddRange(placeOrderResult.Errors.Select(x => HtmlUtils.ConvertPlainTextToHtml(x)));
                }
            }
            catch (Exception exception)
            {
                Logger.Warn(exception, exception.Message);

                if (!model.Warnings.Any(x => x == exception.Message))
                {
                    model.Warnings.Add(exception.Message);
                }
            }

            if (placeOrderResult == null || !placeOrderResult.Success || model.Warnings.Any())
            {
                return(View(model));
            }

            try
            {
                postProcessPaymentRequest = new PostProcessPaymentRequest
                {
                    Order = placeOrderResult.PlacedOrder
                };

                _paymentService.PostProcessPayment(postProcessPaymentRequest);
            }
            catch (Exception exception)
            {
                NotifyError(exception);
            }
            finally
            {
                _httpContext.Session["OrderPaymentInfo"] = null;
                _httpContext.RemoveCheckoutState();
            }

            if (postProcessPaymentRequest != null && postProcessPaymentRequest.RedirectUrl.HasValue())
            {
                return(Redirect(postProcessPaymentRequest.RedirectUrl));
            }

            return(RedirectToAction("Completed"));
        }
        /// <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 order    = postProcessPaymentRequest.Order;
            var customer = order.Customer;


            var rokOrderItems = new List <OmniKassa.Model.Order.OrderItem>();

            foreach (var orderItem in order.OrderItems)
            {
                decimal amount = Decimal.Round(orderItem.UnitPriceInclTax, 2);
                decimal tax    = Decimal.Round(orderItem.UnitPriceInclTax - orderItem.UnitPriceExclTax, 2);

                var rokOrderItem = new OmniKassa.Model.Order.OrderItem.Builder()
                                   .WithId(orderItem.OrderItemGuid.ToString())
                                   .WithQuantity(orderItem.Quantity)
                                   .WithName(orderItem.Product.Name)
                                   .WithDescription(orderItem.Product.ShortDescription)
                                   .WithAmount(Money.FromDecimal(OmniKassa.Model.Enums.Currency.EUR, amount))
                                   .WithTax(Money.FromDecimal(OmniKassa.Model.Enums.Currency.EUR, tax))
                                   .WithItemCategory(ItemCategory.PHYSICAL)
                                   .WithVatCategory(VatCategory.LOW)
                                   .Build();

                rokOrderItems.Add(rokOrderItem);
            }

            CustomerInformation rokCustomerInformation = new CustomerInformation.Builder()
                                                         .WithTelephoneNumber(customer.BillingAddress.PhoneNumber)
                                                         .WithEmailAddress(customer.Email)
                                                         .Build();

            Address rokShippingDetails = new Address.Builder()
                                         .WithFirstName(customer.ShippingAddress.FirstName)
                                         .WithLastName(customer.ShippingAddress.LastName)
                                         .WithStreet(customer.ShippingAddress.Address1)
                                         .WithHouseNumber(customer.ShippingAddress.Address2)
                                         .WithPostalCode(customer.ShippingAddress.ZipPostalCode)
                                         .WithCity(customer.ShippingAddress.City)
                                         .WithCountryCode(CountryCode.NL)
                                         .Build();

            Address rokBillingDetails = new Address.Builder()
                                        .WithFirstName(customer.BillingAddress.FirstName)
                                        .WithLastName(customer.BillingAddress.LastName)
                                        .WithStreet(customer.BillingAddress.Address1)
                                        .WithHouseNumber(customer.BillingAddress.Address2)
                                        .WithPostalCode(customer.BillingAddress.ZipPostalCode)
                                        .WithCity(customer.BillingAddress.City)
                                        .WithCountryCode(CountryCode.NL)
                                        .Build();

            var rokOrder = new MerchantOrder.Builder()
                           .WithMerchantOrderId(order.CustomOrderNumber)
                           .WithDescription(order.CustomOrderNumber)
                           .WithOrderItems(rokOrderItems)
                           .WithAmount(Money.FromDecimal(OmniKassa.Model.Enums.Currency.EUR, Decimal.Round(order.OrderTotal, 2)))
                           .WithCustomerInformation(rokCustomerInformation)
                           .WithShippingDetail(rokShippingDetails)
                           .WithBillingDetail(rokBillingDetails)
                           .WithLanguage(Language.NL)
                           .WithMerchantReturnURL(GetReturnUrl())
                           .Build();

            String redirectUrl = _raboOmniKassaPaymentManager.AnnounceMerchantOrder(rokOrder);

            Debug.WriteLine(redirectUrl);

            _httpContextAccessor.HttpContext.Response.Redirect(redirectUrl);
        }
        /// <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 order = postProcessPaymentRequest.Order;
            const string paymenturl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            var spbillCreateIp = _webHelper.GetCurrentIpAddress();
            var notifyUrl = _webHelper.GetStoreLocation(false) + "Order/Notify";

            var paras = new SortedDictionary<string, string>()
            {
                {"body", "测试商品"},
                {"attach", "测试商品"},
                {"out_trade_no", order.TradeNo},
                {"total_fee", (order.OrderTotal*100).ToString(".")},
                {"time_start", DateTime.Now.ToString("yyyyMMddHHmmss")},
                {"time_expire", DateTime.Now.AddMinutes(5).ToString("yyyyMMddHHmmss")},
                {"goods_tag", "商品标记"},
                {"trade_type", "NATIVE"},
                {"product_id", order.Id.ToString()},
                {"appid", Appid},
                {"mch_id", MchId},
                {"spbill_create_ip", spbillCreateIp},
                {"nonce_str", CommonHelper.GenerateRandomDigitCode(16)},
                {"notify_url", notifyUrl}
            };

            using (var client = new HttpClient())
            {
                var sign = MakeSign(paras);
                paras.Add("sign", sign);

                var requestxml = RequestXml(paras);
                var httpContent = new StringContent(requestxml, Encoding.UTF8, "application/xml");
                var result = client.PostAsync(paymenturl, httpContent).Result;
                using (var responsestream = result.Content.ReadAsStreamAsync().Result)
                {
                    var serializer = new XmlSerializer(typeof(WebCharReponse));
                    var response = serializer.Deserialize(responsestream) as WebCharReponse;
                    if (response == null || response.ResultCode == "FAIL") return;
                    var weburl = response.CodeUrl;
                    var qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
                    var qrCode = qrEncoder.Encode(weburl);
                    var renderer = new GraphicsRenderer(new FixedCodeSize(200, QuietZoneModules.Zero));
                    _httpContext.Response.ContentType = "image/jpeg";
                    renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, _httpContext.Response.OutputStream);
                    _httpContext.Response.End();
                }
            }
        }