Exemple #1
0
        public override string ProcessResponse(HttpContext context)
        {
            //TODO handler notification process
            if (Sandbox)
            {
                return(NotificationMessahges.TestMode);
            }
            if (string.IsNullOrEmpty(SecretWord))
            {
                return("Secret word must be specified");
            }
            try
            {
                var form = context.Request.Form;
                if (!ValidateRequest(form))
                {
                    return(NotificationMessahges.InvalidRequestData);
                }

                var order = OrderService.GetOrderByNumber(form["vendor_order_id"]);
                if (order == null || (order.Sum / CurrencyValue).ToString("F2").Replace(",", ".") != form["invoice_usd_amount"])
                {
                    return(NotificationMessahges.InvalidRequestData);
                }

                OrderService.PayOrder(order.OrderID, true);
                return("");
            }
            catch (Exception ex)
            {
                return(NotificationMessahges.LogError(ex));
            }
        }
Exemple #2
0
        public override string ProcessResponse(HttpContext context)
        {
            var req = context.Request;

            if (!CheckData(req) || req["status"] != "PS")
            {
                return(NotificationMessahges.InvalidRequestData);
            }
            var paymentNumber = req["referenceId"];

            try
            {
                int orderID = 0;
                if (int.TryParse(paymentNumber, out orderID) && OrderService.GetOrder(orderID) != null && req["pg_result"].Trim() == "1")
                {
                    OrderService.PayOrder(orderID, true);
                    return(NotificationMessahges.SuccessfullPayment(paymentNumber));
                }
            }
            catch (Exception ex)
            {
                return(NotificationMessahges.LogError(ex));
            }
            return(NotificationMessahges.Fail);
        }
Exemple #3
0
        public override string ProcessResponse(HttpContext context)
        {
            var req = context.Request;


            if (!CheckData(req))
            {
                return(NotificationMessahges.InvalidRequestData);
            }


            var paymentNumber = req["lmi_payment_no"];
            int orderID;

            if (int.TryParse(paymentNumber, out orderID) &&
                OrderService.GetOrder(orderID) != null)
            {
                var order = OrderService.GetOrder(orderID);
                if (order != null && req["LMI_PAYMENT_AMOUNT"] == string.Format("{0:0.00}", order.Sum / CurrencyValue))
                {
                    OrderService.PayOrder(orderID, true);
                    return(NotificationMessahges.SuccessfullPayment(order.Number));
                }
            }
            return(NotificationMessahges.Fail);
        }
Exemple #4
0
        public override string ProcessResponse(HttpContext context)
        {
            var req     = context.Request;
            var orderID = 0;

            if (CheckFields(context) && req["status"] == "PAID" && int.TryParse(StringHelper.DecodeFrom64(req["issuer_id"]), out orderID) && OrderService.GetOrder(orderID) != null)
            {
                OrderService.PayOrder(orderID, true);
                context.Response.Clear();
                context.Response.Write("item_number=" + context.Request["item_number"] + "\n");
                context.Response.Write("status=ACCEPTED");
                context.Response.End();
                return(NotificationMessahges.SuccessfullPayment(orderID.ToString()));
            }
            return(NotificationMessahges.InvalidRequestData);
        }
Exemple #5
0
        public override string ProcessResponse(HttpContext context)
        {
            HttpRequest req     = context.Request;
            int         orderID = 0;

            if (CheckFields(req) && int.TryParse(req["pay_for"], out orderID))
            {
                Order order = OrderService.GetOrder(orderID);
                if (order != null)
                {
                    OrderService.PayOrder(orderID, true);
                    return(NotificationMessahges.SuccessfullPayment(orderID.ToString()));
                }
            }
            return(NotificationMessahges.InvalidRequestData);
        }
Exemple #6
0
        public override string ProcessResponse(HttpContext context)
        {
            HttpRequest req     = context.Request;
            int         orderID = 0;

            // пришел запрос с проверкой, необходимо отдать xml-ответ
            if (req["type"].IsNotEmpty() && req["type"] == "check")
            {
                context.Response.Write(GetCheckResponseXML(req));
                context.Response.End();
                return("");
            }

            // пришел запрос об оплате
            if (req["type"].IsNotEmpty() && req["type"] == "pay")
            {
                if (int.TryParse(req["pay_for"], out orderID))
                {
                    Order order = OrderService.GetOrder(orderID);
                    if (order != null)
                    {
                        OrderService.PayOrder(orderID, true);

                        context.Response.Write(GetPayResponseXML(0, orderID, req["order_amount"], req["onpay_id"], "OK", req["order_currency"]));
                        context.Response.End();
                        return("");
                    }
                }

                context.Response.Write(GetPayResponseXML(2, orderID, req["order_amount"], req["onpay_id"], "Error", req["order_currency"]));
                context.Response.End();
                return("");
            }


            if (CheckFields(req) && int.TryParse(req["pay_for"], out orderID))
            {
                Order order = OrderService.GetOrder(orderID);
                if (order != null)
                {
                    OrderService.PayOrder(orderID, true);
                    return(NotificationMessahges.SuccessfullPayment(orderID.ToString()));
                }
            }
            return("");
        }
Exemple #7
0
        public override string ProcessResponse(HttpContext context)
        {
            if (Sandbox)
            {
                return(NotificationMessahges.TestMode);
            }
            if (string.IsNullOrEmpty(context.Request["serial-number"]))
            {
                return(NotificationMessahges.InvalidRequestData);
            }
            var client = new WebClient();

            try
            {
                string data =
                    Encoding.Default.GetString(
                        client.UploadValues(
                            string.Format("https://checkout.google.com/api/checkout/v2/reportsForm/Merchant/{0}",
                                          MerchantID),
                            new NameValueCollection
                {
                    { "_type", "notification-history-request" },
                    { "serial-number", context.Request["serial-number"] }
                }));
                Dictionary <string, string> values = GetResponseValues(data);
                if (values == null || !values.ContainsKey("_type") || values["_type"] != "notification-history-response" ||
                    !values.ContainsKey("merchant-item-id"))
                {
                    return(NotificationMessahges.InvalidRequestData);
                }
                int orderID = OrderService.GetOrderIdByNumber(values["merchant-item-id"]);
                if (orderID == 0)
                {
                    return(NotificationMessahges.Fail);
                }

                OrderService.PayOrder(orderID, true);
                return(NotificationMessahges.SuccessfullPayment(values["merchant-item-id"]));
            }
            catch (Exception ex)
            {
                Debug.LogError(ex, "at GoogleCheckout");
                return(NotificationMessahges.Fail);
            }
        }
Exemple #8
0
        public override string ProcessResponse(HttpContext context)
        {
            var req = context.Request;

            if (!CheckData(req))
            {
                return(NotificationMessahges.InvalidRequestData);
            }
            var paymentNumber = req["orderId"];
            int orderID       = 0;

            if (int.TryParse(paymentNumber, out orderID) && OrderService.GetOrder(orderID) != null)
            {
                OrderService.PayOrder(orderID, true);
                return(NotificationMessahges.SuccessfullPayment(paymentNumber));
            }
            return(NotificationMessahges.Fail);
        }
Exemple #9
0
        public override string ProcessResponse(HttpContext context)
        {
            if (Sandbox)
            {
                return(NotificationMessahges.TestMode);
            }
            var response = new global::AuthorizeNet.SIMResponse(context.Request.Form);

            //TODO find out hash key
            if (!response.Validate("YOUR_MERCHANT_HASH_CODE", Login))
            {
                return(NotificationMessahges.InvalidRequestData);
            }

            //TODO ORDER PAYMENT TEST
            OrderService.PayOrder(OrderService.GetOrderIdByNumber(response.InvoiceNumber), true);
            return(NotificationMessahges.SuccessfullPayment(response.InvoiceNumber));
        }
Exemple #10
0
        public override string ProcessResponse(HttpContext context)
        {
            var req     = context.Request;
            var orderID = 0;

            if (CheckFields(context) && req["ik_inv_st"] == "success" && int.TryParse(req["ik_pm_no"], out orderID))
            {
                Order order = OrderService.GetOrder(orderID);
                if (order != null)
                {
                    OrderService.PayOrder(orderID, true);
                    return(NotificationMessahges.SuccessfullPayment(orderID.ToString()));
                }
            }
            else
            {
                Debug.LogError("exeption in interkassa 2.0. ik_inv_st:" + req["ik_inv_st"] + ", ik_pm_no:" + req["ik_pm_no"]);
            }
            return(NotificationMessahges.InvalidRequestData);
        }
Exemple #11
0
        private string ProcessResponseReturn(HttpContext context)
        {
            var req     = context.Request;
            int orderId = 0;

            if (int.TryParse(req["InvId"], out orderId))
            {
                if (CheckFields(req))
                {
                    Order order = OrderService.GetOrder(orderId);
                    if (order != null)
                    {
                        OrderService.PayOrder(orderId, true);
                        return(NotificationMessahges.SuccessfullPayment(orderId.ToString()));
                    }
                }
                return(NotificationMessahges.InvalidRequestData);
            }
            return(string.Empty);
        }
Exemple #12
0
        public override string ProcessResponse(HttpContext context)
        {
            //1.	RESULT (Результат операции. 0 – одобрено 2 – отклонена 3 – технические проблемы )
            //2.	RC (Код ответа ISO8583)
            //3.	CURRENCY (Валюта)
            //4.	ORDER
            //5.	RRN (Номер операции в платёжной системе)
            //6.	INT_REF (Внутренний код операции)
            //7.	AUTHCODE (Код авторизации. Может отсутствовать)
            //8.	PAN (Замаскированный номер карты)
            //9.	TRTYPE (Тип операции. 0 – авторизация (начальный платеж пользователя), 21 – завершение расчёта, 24 – возврат.)
            //10.	TIMESTAMP
            //11.	SIGN (Используется для безопасности клиента)
            //12.	AMOUNT
            var req = context.Request;

            if (!CheckData(req))
            {
                return(NotificationMessahges.InvalidRequestData);
            }

            var paymentNumber = req["ORDER"];

            if (string.IsNullOrEmpty(req["AMOUNT"]) || string.IsNullOrEmpty(req["ORDER"]) || string.IsNullOrEmpty(req["RRN"]) || string.IsNullOrEmpty(req["INT_REF"]))
            {
                return(NotificationMessahges.Fail);
            }

            int orderID;

            if (int.TryParse(paymentNumber, out orderID))
            {
                var order = OrderService.GetOrder(orderID);
                if (order != null)
                {
                    SaveResponceParametr(orderID, req["AMOUNT"], req["ORDER"], req["RRN"], req["INT_REF"]);
                    return(NotificationMessahges.SuccessfullPayment(order.Number));
                }
            }
            return(NotificationMessahges.Fail);
        }
Exemple #13
0
        public override string ProcessResponse(HttpContext context)
        {
            var req = context.Request;

            if (!ValidateResponseSign(req.Form))
            {
                return(NotificationMessahges.InvalidRequestData);
            }
            int orderId;

            if (Int32.TryParse(req["OrderID"], out orderId))
            {
                var order = OrderService.GetOrder(orderId);
                if (order != null)
                {
                    OrderService.PayOrder(order.OrderID, true);
                    return(NotificationMessahges.SuccessfullPayment(order.OrderID.ToString()));
                }
            }
            return(NotificationMessahges.Fail);
        }
Exemple #14
0
        public override string ProcessResponse(HttpContext context)
        {
            var req = context.Request;

            Debug.LogError(req.Url.AbsoluteUri);

            if (SuccessUrl.Contains(req.RawUrl))
            {
                return(Resources.Resource.Client_Payment_SuccessfullyPaid);
            }

            // Параметр LMI_SECRET_KEY передается только по https. Без https проверка неполучится. Раскомментировать если требуется проверка.
            if (context.Request.IsSecureConnection && !CheckData(req))
            {
                return(NotificationMessahges.InvalidRequestData);
            }


            var paymentNumber = req["lmi_payment_no"];
            int orderID;

            if (int.TryParse(paymentNumber, out orderID))
            {
                var order = OrderService.GetOrder(orderID);
                if (order != null && req["LMI_PAYMENT_AMOUNT"] == string.Format("{0:0.00}", order.Sum / CurrencyValue).Replace(",", "."))
                {
                    if (req["LMI_PREREQUEST"] == "1")
                    {
                        return("YES");
                    }
                    else
                    {
                        OrderService.PayOrder(orderID, true);
                        return(NotificationMessahges.SuccessfullPayment(order.Number));
                    }
                }
            }
            return(NotificationMessahges.Fail);
        }
Exemple #15
0
/*
 *      <response>
 *          <version>1.2</version>
 *          <merchant_id></merchant_id>
 *          <order_id> ORDER_123456</order_id>
 *          <amount>1.01</amount>
 *          <currency>UAH</currency>
 *          <description>Comment</description>
 *          <status>success</status>
 *          <code></code>
 *          <transaction_id>31</transaction_id>
 *          <pay_way>card</pay_way>
 *          <sender_phone>+3801234567890</sender_phone>
 *          <goods_id>1234</goods_id>
 *          <pays_count>5</pays_count>
 *      </response>
 */
        public override string ProcessResponse(HttpContext context)
        {
            var req     = context.Request;
            var orderID = 0;

            try
            {
                if (!string.IsNullOrEmpty(req["operation_xml"]) && !string.IsNullOrEmpty(req["signature"]))
                {
                    var xml = Encoding.UTF8.GetString(Convert.FromBase64String(req["operation_xml"]));

                    if (xml.IsNotEmpty())
                    {
                        var xdoc = XDocument.Parse(xml);

                        var elOrderId = xdoc.Root.Element("order_id").Value;
                        var elStatus  = xdoc.Root.Element("status").Value;

                        if (int.TryParse(elOrderId.Replace("ORDER_", ""), out orderID) && elStatus == "success")
                        {
                            OrderService.PayOrder(orderID, true);
                            return(NotificationMessahges.SuccessfullPayment(elOrderId));
                        }
                        else
                        {
                            Debug.LogError("LiqPay: status " + xdoc.Root.Element("status").Value
                                           + ", code " + xdoc.Root.Element("code").Value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }

            return(NotificationMessahges.InvalidRequestData);
        }
Exemple #16
0
        public override string ProcessResponse(HttpContext context)
        {
            var req = context.Request;

            if (!req["LMI_PREREQUEST"].IsNullOrEmpty() && req["LMI_PREREQUEST"] == "1")
            {
                return("YES");
            }

            if (!CheckData(req))
            {
                return(NotificationMessahges.InvalidRequestData);
            }
            var paymentNumber = req["LMI_PAYMENT_NO"];
            int orderID       = 0;

            if (int.TryParse(paymentNumber, out orderID) && OrderService.GetOrder(orderID) != null)
            {
                OrderService.PayOrder(orderID, true);
                return(NotificationMessahges.SuccessfullPayment(paymentNumber));
            }
            return(NotificationMessahges.Fail);
        }
Exemple #17
0
        public override string ProcessResponse(HttpContext context)
        {
            var req = context.Request;

            if (!CheckData(req))
            {
                return(NotificationMessahges.InvalidRequestData);
            }
            var paymentNumber = req["OrderID"];
            int orderID       = 0;

            if (int.TryParse(paymentNumber, out orderID) &&
                OrderService.GetOrder(orderID) != null &&
                (req["Approved"].ToUpper() == "APPROVED" && req["ReturnCode"][0] == 'Y'))
            {
                var order = OrderService.GetOrder(orderID);
                if (order != null && req["FullTotal"] == (order.Sum / CurrencyValue).ToString("F2").Replace(",", "."))
                {
                    OrderService.PayOrder(orderID, true);
                    return(NotificationMessahges.SuccessfullPayment(order.Number));
                }
            }
            return(NotificationMessahges.Fail);
        }
Exemple #18
0
        public override string ProcessResponse(HttpContext context)
        {
            HttpRequest req = context.Request;

            if (req["operation"].IsNotEmpty() && req["operation"] == "test")
            {
                context.Response.Write("SUCCESS");
                context.Response.End();
                return(string.Empty);
            }

            int orderID = 0;

            if (CheckFields(req) && int.TryParse(req["merchant_order_id"], out orderID))
            {
                Order order = OrderService.GetOrder(orderID);
                if (order != null)
                {
                    OrderService.PayOrder(orderID, true);
                    return(NotificationMessahges.SuccessfullPayment(orderID.ToString()));
                }
            }
            return(NotificationMessahges.InvalidRequestData);
        }
Exemple #19
0
        public override string ProcessResponse(HttpContext context)
        {
            //TODO some other response processing
            if (Sandbox)
            {
                return(NotificationMessahges.TestMode);
            }

            try
            {
                if (context.Request.UrlReferrer == null || context.Request.UrlReferrer.Host != "www.eway.com.au")
                {
                    return(NotificationMessahges.InvalidRequestData);
                }
                var form         = context.Request.Form;
                var orderNumber  = form["ewayTrxnNumber"];
                var status       = Convert.ToBoolean(form["ewayTrxnStatus"]);
                var sum          = Convert.ToDecimal(form["eWAYReturnAmount"].Replace(",", "").Replace("$", "").Replace(".", ""));
                var responseText = form["eWAYresponseText"];


                var order = OrderService.GetOrderByNumber(orderNumber);
                if (status && order.Sum != sum / 100)
                {
                    return(NotificationMessahges.InvalidRequestData);
                }

                //TODO ORDER PAYMENT
                OrderService.PayOrder(order.OrderID, true);
                return(NotificationMessahges.SuccessfullPayment(orderNumber));
            }
            catch (Exception ex)
            {
                return(NotificationMessahges.LogError(ex));
            }
        }
Exemple #20
0
        public override string ProcessResponse(HttpContext context)
        {
            //if (Sandbox)
            //    return NotificationMessahges.TestMode;
            //if (string.IsNullOrEmpty(context.Request["tx"]))
            //    return NotificationMessahges.InvalidRequestData;
            //var tx = context.Request["tx"];
            try
            {
                bool   IsValidRequest = false;
                string orderNumber    = string.Empty;
                string mc_gross       = string.Empty;

                if (!string.IsNullOrEmpty(GetPrm(context, "verify_sign")))
                {
                    string strFormValues = Encoding.ASCII.GetString(context.Request.BinaryRead(context.Request.ContentLength));
                    string strNewValue;

                    // Create the request back
                    var req = (HttpWebRequest)WebRequest.Create(GetUrl());

                    // Set values for the request back
                    req.Method        = "POST";
                    req.ContentType   = "application/x-www-form-urlencoded";
                    strNewValue       = strFormValues + "&cmd=_notify-validate";
                    req.ContentLength = strNewValue.Length;

                    // Write the request back IPN strings
                    using (StreamWriter stOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
                        stOut.Write(strNewValue);

                    // send the request, read the response
                    using (HttpWebResponse strResponse = (HttpWebResponse)req.GetResponse())
                    {
                        using (Stream IPNResponseStream = strResponse.GetResponseStream())
                        {
                            Encoding encode = Encoding.GetEncoding("utf-8");
                            using (StreamReader readStream = new StreamReader(IPNResponseStream, encode))
                            {
                                char[] read = new char[256];
                                // Reads 256 characters at a time.
                                int count = readStream.Read(read, 0, 256);
                                while (count > 0)
                                {
                                    // Dumps the 256 characters to a string and displays the string to the console.
                                    String IPNResponse = new String(read, 0, count);
                                    count = readStream.Read(read, 0, 256);
                                    // if IPN response was VERIFIED..perform VERIFIED handling
                                    //for this example - send email of raw IPN string
                                    if (IPNResponse == "VERIFIED")
                                    {
                                        IsValidRequest = true;
                                    }
                                }
                                //tidy up, close streams
                                readStream.Close();
                                strResponse.Close();
                            }
                        }
                    }
                    orderNumber = GetPrm(context, "invoice");
                    mc_gross    = GetPrm(context, "mc_gross");
                }
                else if (!string.IsNullOrEmpty(GetPrm(context, "tx")))
                {
                    var req = (HttpWebRequest)WebRequest.Create(GetUrl());
                    req.Method      = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";

                    string formContent = string.Format("cmd=_notify-synch&at={0}&tx={1}", PDTCode, GetPrm(context, "tx"));
                    req.ContentLength = formContent.Length;

                    using (var sw = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
                        sw.Write(formContent);

                    string response;
                    using (var sr = new StreamReader(req.GetResponse().GetResponseStream()))
                        response = HttpUtility.UrlDecode(sr.ReadToEnd());

                    var success = response.Split('\n').Select(l => l.Trim()).First();
                    if (success != null && success.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase))
                    {
                        IsValidRequest = true;

                        orderNumber =
                            response.Split('\n').FirstOrDefault(
                                line => line.Contains('=') && line.Trim().Substring(0, line.IndexOf('=')) == "invoice");

                        mc_gross =
                            response.Split('\n').FirstOrDefault(
                                line => line.Contains('=') && line.Trim().Substring(0, line.IndexOf('=')) == "mc_gross");

                        if (!string.IsNullOrEmpty(orderNumber))
                        {
                            orderNumber = orderNumber.Substring(orderNumber.IndexOf('=') + 1);
                        }

                        if (!string.IsNullOrEmpty(mc_gross))
                        {
                            mc_gross = mc_gross.Substring(mc_gross.IndexOf('=') + 1);
                        }
                    }
                }

                if (IsValidRequest && !string.IsNullOrEmpty(orderNumber) && !string.IsNullOrEmpty(mc_gross))
                {
                    Order order = OrderService.GetOrder(OrderService.GetOrderIdByNumber(orderNumber));
                    if (order != null)
                    {
                        var provider = new System.Globalization.CultureInfo(System.Globalization.CultureInfo.InvariantCulture.LCID);
                        provider.NumberFormat.NumberDecimalSeparator = ".";
                        decimal Summ;
                        decimal.TryParse(mc_gross, System.Globalization.NumberStyles.AllowDecimalPoint, provider, out Summ);
                        if (Summ < Math.Round(CurrencyService.ConvertCurrency(order.Sum, CurrencyValue, order.OrderCurrency.CurrencyValue), 2))
                        {
                            return(NotificationMessahges.Fail);
                        }

                        string           fileName = System.IO.Path.GetFileName(context.Request.FilePath);
                        NotificationType ntFile   = Payment.NotificationType.None;
                        switch (fileName.ToLower())
                        {
                        case "paymentnotification.ashx":
                            ntFile = Payment.NotificationType.Handler;
                            break;

                        case "paymentreturnurl.aspx":
                            ntFile = Payment.NotificationType.ReturnUrl;
                            break;
                        }

                        if (((this.NotificationType & ntFile) == Payment.NotificationType.Handler) || ((this.NotificationType & ntFile) == Payment.NotificationType.ReturnUrl))
                        {
                            OrderService.PayOrder(order.OrderID, true);
                        }

                        return(NotificationMessahges.SuccessfullPayment(orderNumber));
                    }
                }

                return(NotificationMessahges.Fail);

                //string formContent = string.Format("cmd=_notify-validate");
                //req.ContentLength = formContent.Length;

                //using (var sw = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
                //    sw.Write(formContent);

                //string response;
                //using (var sr = new StreamReader(req.GetResponse().GetResponseStream()))
                //    response = HttpUtility.UrlDecode(sr.ReadToEnd());

                //var success = response.Split('\n').Select(l => l.Trim()).First();
                //if (success != null && success.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase))
                //{
                //    var orderNumber =
                //        response.Split('\n').FirstOrDefault(
                //            line => line.Contains('=') && line.Trim().Substring(0, line.IndexOf('=')) == "invoice");
                //    if (!string.IsNullOrEmpty(orderNumber))
                //        OrderService.PayOrder(OrderService.GetOrderIdByNumber(orderNumber), true);

                //    return NotificationMessahges.SuccessfullPayment(orderNumber);
                //}
                //return NotificationMessahges.Fail;
            }
            catch (Exception ex)
            {
                return(NotificationMessahges.LogError(ex));
            }
            //TODO ORDER PAYMENT TEST
        }
        public override string ProcessResponse(HttpContext context)
        {
            if (!string.IsNullOrEmpty(context.Request["token"]) && !string.IsNullOrEmpty(context.Request["PayerID"]))
            {
                var currencyCode = string.Empty;
                var totalOrder   = string.Empty;
                var orderNumber  = string.Empty;

                var requestGetDetailsUrl =
                    string.Format("https://api-3t.{0}paypal.com/nvp", Sandbox ? "sandbox." : string.Empty) +
                    "?USER="******"&PWD=" + Password +
                    "&SIGNATURE=" + Signature +
                    "&METHOD=GetExpressCheckoutDetails" +
                    "&VERSION=106.0" +
                    "&RETURNURL=" + HttpUtility.UrlEncode(this.NotificationUrl) +
                    "&CANCELURL=" + HttpUtility.UrlEncode(this.CancelUrl) +
                    "&LOCALECODE=" + CultureInfo.CurrentCulture.TwoLetterISOLanguageName +
                    "&TOKEN=" + context.Request["token"] +
                    "&BUTTONSOURCE=AdVantShop_Cart";

                WebRequest requestGetDetails = WebRequest.Create(requestGetDetailsUrl);

                requestGetDetails.Method = "GET";

                var stringRequestDetails =
                    (new StreamReader(requestGetDetails.GetResponse().GetResponseStream())).ReadToEnd();

                if (!string.IsNullOrEmpty(stringRequestDetails))
                {
                    foreach (var param in HttpUtility.UrlDecode(stringRequestDetails).Split(new[] { '&' }))
                    {
                        var pair = param.Split(new[] { '=' });
                        if (pair.Count() == 2 && string.Equals(pair[0], "CURRENCYCODE"))
                        {
                            currencyCode = pair[1];
                        }
                        else if (pair.Count() == 2 && string.Equals(pair[0], "AMT"))
                        {
                            totalOrder = pair[1];
                        }
                        else if (pair.Count() == 2 && string.Equals(pair[0], "INVNUM"))
                        {
                            orderNumber = pair[1];
                        }
                    }
                }

                Debug.LogError("---" + currencyCode + "---" + totalOrder + "---" + orderNumber);

                Order order = null;
                if (!string.IsNullOrEmpty(orderNumber))
                {
                    order = OrderService.GetOrderByNumber(orderNumber);
                    if (order == null)
                    {
                        return(NotificationMessahges.Fail);
                    }
                }

                var requestUrl =
                    string.Format("https://api-3t.{0}paypal.com/nvp", Sandbox ? "sandbox." : string.Empty) +
                    "?USER="******"&PWD=" + Password +
                    "&SIGNATURE=" + Signature +
                    "&METHOD=DoExpressCheckoutPayment" +
                    "&VERSION=106.0" +
                    "&TOKEN=" + context.Request["token"] +
                    "&PAYERID=" + context.Request["PayerID"] +
                    "&PAYMENTREQUEST_0_AMT=" + totalOrder +
                    "&PAYMENTREQUEST_0_CURRENCYCODE=" + currencyCode +
                    "&PAYMENTREQUEST_0_PAYMENTACTION=Sale" +
                    "&BUTTONSOURCE=AdVantShop_Cart";
                if (order != null && order.ShippingContact != null)
                {
                    var country = CountryService.GetCountryByName(order.ShippingContact.Country);

                    requestUrl +=
                        "&PAYMENTREQUEST_0_SHIPTONAME=" + HttpUtility.UrlEncode(order.ShippingContact.Name) +
                        "&PAYMENTREQUEST_0_SHIPTOSTREET=" + HttpUtility.UrlEncode(order.ShippingContact.Address) +
                        "&PAYMENTREQUEST_0_SHIPTOCITY=" + HttpUtility.UrlEncode(order.ShippingContact.City) +
                        "&PAYMENTREQUEST_0_SHIPTOSTATE=" + HttpUtility.UrlEncode(order.ShippingContact.Zone) +
                        "&PAYMENTREQUEST_0_SHIPTOZIP=" + HttpUtility.UrlEncode(order.ShippingContact.Zip) +
                        "&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=" + HttpUtility.UrlEncode(country.Iso2);
                }
                for (int m = 0; m < order.OrderItems.Count; ++m)
                {
                    requestUrl += string.Format(
                        "&L_PAYMENTREQUEST_0_NAME{0}={1}&L_PAYMENTREQUEST_0_DESC{0}={2}&L_PAYMENTREQUEST_0_AMT{0}={3}&L_PAYMENTREQUEST_0_QTY{0}={4}&L_PAYMENTREQUEST_0_ITEMCATEGORY{0}=Physical",
                        m,
                        HttpUtility.UrlEncode(order.OrderItems[m].Name),
                        HttpUtility.UrlEncode(string.Empty),
                        HttpUtility.UrlEncode(order.OrderItems[m].Price.ToString().Replace(",", ".")),
                        HttpUtility.UrlEncode(order.OrderItems[m].Amount.ToString()));
                }
                if (order.TotalDiscount != 0)
                {
                    requestUrl += string.Format(
                        "&L_PAYMENTREQUEST_0_NAME{0}={1}&L_PAYMENTREQUEST_0_DESC{0}={2}&L_PAYMENTREQUEST_0_AMT{0}={3}&L_PAYMENTREQUEST_0_QTY{0}={4}&L_PAYMENTREQUEST_0_ITEMCATEGORY{0}=Physical",
                        order.OrderItems.Count,
                        HttpUtility.UrlEncode(Resources.Resource.Admin_PaymentMethod_PayPalExpressCheckout_OrderDiscount),
                        HttpUtility.UrlEncode(string.Empty),
                        HttpUtility.UrlEncode(Math.Round((-1 * Math.Round(order.TotalDiscount, 2)), 2).ToString().Replace(",", ".")),
                        HttpUtility.UrlEncode("1"));
                }

                var request = WebRequest.Create(requestUrl);

                request.Method = "GET";

                var str = (new StreamReader(request.GetResponse().GetResponseStream())).ReadToEnd();

                Debug.LogError("---" + str + "---");

                if (!string.IsNullOrEmpty(str))
                {
                    foreach (var param in HttpUtility.UrlDecode(str).Split(new[] { '&' }))
                    {
                        var pair = param.Split(new[] { '=' });
                        if (pair.Count() == 2 && string.Equals(pair[0], "ACK"))
                        {
                            if (string.Equals(pair[1], "Success") && order != null)
                            {
                                OrderService.PayOrder(order.OrderID, true);
                                return(NotificationMessahges.SuccessfullPayment(order.Number));
                            }
                            break;
                        }
                    }
                }
            }

            return(NotificationMessahges.Fail);
        }
Exemple #22
0
        public override string ProcessResponse(HttpContext context)
        {
            if (Sandbox)
            {
                return(NotificationMessahges.TestMode);
            }
            if (string.IsNullOrEmpty(context.Request["ordernumber"]) && string.IsNullOrWhiteSpace(context.Request["billnumber"]))
            {
                return(NotificationMessahges.InvalidRequestData);
            }
            string orderNumber = context.Request["ordernumber"];
            string billnumber  = context.Request["billnumber"];

            try
            {
                if (Delay)
                {
                    //if 2 stage
                    var client = new WebClient();
                    var data   =
                        client.UploadValues(
                            //string.Format("https://{0}/charge/charge.cfm", Sandbox ? "test.paysecure.ru" : PayUrl),//"secure.paysecure.ru"
                            Sandbox ? "https://test.paysecure.ru/charge/charge.cfm" : UrlWorkingMode,//"secure.paysecure.ru"
                            new NameValueCollection
                    {
                        { "Billnumber", billnumber },
                        { "Merchant_ID", MerchantID.ToString() },
                        { "Login", Login },
                        { "Password", Password },
                        //XML
                        { "Format", "3" }
                    });


                    var xml   = new XmlDocument();
                    var temp  = Encoding.UTF8.GetString(data).ToLower();
                    var start = temp.IndexOf("<!doctype");
                    var end   = temp.IndexOf("]>");
                    temp = temp.Remove(start, (end + 2) - start);
                    xml.LoadXml(temp);
                    if (xml.DocumentElement != null && xml.DocumentElement.Name != "result")
                    {
                        throw new Exception("Invalid XML response");
                    }
                    if (xml.DocumentElement != null)
                    {
                        var orders = xml.DocumentElement.SelectNodes(string.Format("descendant::order[ordernumber='{0}' and response_code='AS000' and orderstate='Approved' ]", orderNumber.ToLower()));
                        if (orders != null && orders.Count > 0)
                        {
                            OrderService.PayOrder(OrderService.GetOrderIdByNumber(orderNumber), true);
                        }
                        else
                        {
                            return(NotificationMessahges.InvalidRequestData);
                        }
                    }
                }
                else
                {
                    //if 1 stage
                    OrderService.PayOrder(OrderService.GetOrderIdByNumber(orderNumber), true);
                }
                return(NotificationMessahges.SuccessfullPayment(orderNumber));
            }
            catch (Exception ex)
            {
                return(NotificationMessahges.LogError(ex));
            }
        }