public void ParseIPN(int orderId, string transId, string status, int storeId, int portalId, string userName, int customerId, string sessionCode)
        {
            var ph = new PayPalHandler();
            try
            {

                var ot = new OrderDetailsCollection();
                var odinfo = new OrderDetailsInfo();
                var cms = new CartManageSQLProvider();
                var cf = new CommonInfo {StoreID = storeId, PortalID = portalId, AddedBy = userName};
                // UpdateOrderDetails
            
                var sqlH = new SQLHandler();
                // use split to split array we already have using "=" as delimiter
                // WcfSession ws = new WcfSession();
                odinfo.OrderID = orderId;//ws.GetSessionVariable("OrderID");
                odinfo.ResponseReasonText = status;
                odinfo.TransactionID = transId;
                ot.ObjOrderDetails = odinfo;
                ot.ObjCommonInfo = cf;
                odinfo.OrderStatusID = 8;
                AspxOrderController.UpdateOrderDetails(ot);

               
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        string selectedCurrency = string.Empty;
        string MainCurrency = string.Empty;
        try
        {
            StoreSettingConfig ssc = new StoreSettingConfig();
            MainCurrency = ssc.GetStoreSettingsByKey(StoreSetting.MainCurrency, GetStoreID, GetPortalID, GetCurrentCultureName);
            if (Session["SelectedCurrency"] != null)
            {
                if (Session["SelectedCurrency"].ToString() != "")
                {
                    selectedCurrency = Session["SelectedCurrency"].ToString();
                }
            }
            else
            {
                selectedCurrency = MainCurrency;
            } 

            string islive = Request.Form["custom"];
            string test = string.Empty;
            const string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
            const string strLive = "https://www.paypal.com/cgi-bin/webscr";
            test = bool.Parse(islive.Split('#')[6]) ? strSandbox : strLive;

            var req = (HttpWebRequest)WebRequest.Create(test);
                       req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(param);
            strRequest += "&cmd=_notify-validate";
            req.ContentLength = strRequest.Length;
                                                        var streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
            streamOut.Write(strRequest);
            streamOut.Close();
            var streamIn = new StreamReader(req.GetResponse().GetResponseStream());
            string strResponse = streamIn.ReadToEnd();
            streamIn.Close();
                                                                                                    if (strResponse == "VERIFIED")
            {
                string payerEmail = Request.Form["payer_email"];
                string paymentStatus = Request.Form["payment_status"];
                string receiverEmail = Request.Form["receiver_email"];
                string amount = Request.Form["mc_gross"];
                string invoice = Request.Form["invoice"];
                string addressName = Request.Form["address_name"];
                string addressStreet = Request.Form["address_street"];
                string addressCity = Request.Form["address_city"];
                string addressZip = Request.Form["address_zip"];
                string addressCountry = Request.Form["address_country"];
                string transID = Request.Form["txn_id"];
                string custom = Request.Form["custom"];
             
                string[] ids = custom.Split('#');
                int orderID = int.Parse(ids[0]);
                int storeID = int.Parse(ids[1]);
                int portalID = int.Parse(ids[2]);
                string userName = ids[3];
                int customerID = int.Parse(ids[4]);
                string sessionCode = ids[5];
                string pgid = ids[7];

                var tinfo = new TransactionLogInfo();
                var tlog = new TransactionLog();

                tinfo.TransactionID = transID;
                tinfo.AuthCode = "";
                tinfo.TotalAmount = decimal.Parse(amount);
                tinfo.ResponseCode = "1";
                tinfo.ResponseReasonText = "";
                tinfo.OrderID = orderID;
                tinfo.StoreID = storeID;
                tinfo.PortalID = portalID;
                tinfo.AddedBy = userName;
                tinfo.CustomerID = customerID;
                tinfo.SessionCode = sessionCode;
                tinfo.PaymentGatewayID = int.Parse(pgid);
                tinfo.PaymentStatus = paymentStatus;
                tinfo.PayerEmail = payerEmail;
                tinfo.CreditCard = "";
                tinfo.RecieverEmail = receiverEmail;
                tinfo.CurrencyCode = selectedCurrency;
                tlog.SaveTransactionLog(tinfo);
              

                if (paymentStatus.Equals("Completed"))
                {
                                                                                                                                                                                               var paypalobj = new PayPalHandler();
                    paypalobj.ParseIPN(orderID, transID, paymentStatus, storeID, portalID, userName, customerID, sessionCode);
                                   }
              

            }
            else if (strResponse == "INVALID")
            {
                           }
            else
            {
                           }
                   }
        catch (Exception ex)
        {
            ProcessException(ex);
                 }
    }
        public void ParseAfterIPN(string postData, AspxCommonInfo aspxCommonObj, string templateName, string addressPath)
        {
            var ph = new PayPalHandler();
            string transId = string.Empty;
            string orderStatus = string.Empty;

            try
            {
                //split response into string array using whitespace delimeter
                String[] stringArray = postData.Split('\n');

                // NOTE:
                /*
                * loop is set to start at 1 rather than 0 because first
                string in array will be single word SUCCESS or FAIL
                Only used to verify post data
                */
                var ot = new OrderDetailsCollection();
                var odinfo = new OrderDetailsInfo();
                var cms = new CartManageSQLProvider();
                var cf = new CommonInfo {StoreID = aspxCommonObj.StoreID, PortalID = aspxCommonObj.PortalID, AddedBy = aspxCommonObj.UserName};
                // UpdateOrderDetails
            
                var sqlH = new SQLHandler();
                // use split to split array we already have using "=" as delimiter
             
                int i;
                for (i = 1; i < stringArray.Length - 1; i++)
                {
                    String[] stringArray1 = stringArray[i].Split('=');

                    String sKey = stringArray1[0];
                    String sValue = HttpUtility.UrlDecode(stringArray1[1]);

                    // set string vars to hold variable names using a switch
                    switch (sKey)
                    {
                        case "payment_status":
                            odinfo.ResponseReasonText = Convert.ToString(sValue);
                            orderStatus = Convert.ToString(sValue);
                            break;

                        case "mc_fee":
                            // ph.PaymentFee = Convert.ToDouble(sValue);
                            break;

                        case "payer_email":
                            // ph.PayerEmail = Convert.ToString(sValue);
                            break;

                        case "Tx Token":
                            // ph.TxToken = Convert.ToString(sValue);
                            break;

                        case "txn_id":
                            odinfo.TransactionID = Convert.ToString(sValue);
                            transId = Convert.ToString(sValue);
                            break;

                    }
                }
             
                ot.ObjCommonInfo = cf;
                //odinfo.OrderStatusID = 8;
                //objad.UpdateOrderDetails(ot);
                if (odinfo.ResponseReasonText.ToLower().Trim() == "completed")
                {
                    if (HttpContext.Current.Session["OrderCollection"] != null)
                    {
                        var orderdata2 = (OrderDetailsCollection)HttpContext.Current.Session["OrderCollection"];
                        AspxOrderController.UpdateItemQuantity(orderdata2);
                    }
                }
                cms.ClearCartAfterPayment(aspxCommonObj);

                //invoice  transID
                if (HttpContext.Current.Session["OrderCollection"] != null)
                {
                    var orderdata = (OrderDetailsCollection)HttpContext.Current.Session["OrderCollection"];
                    orderdata.ObjOrderDetails.OrderStatus = orderStatus;
                    EmailTemplate.SendEmailForOrder(aspxCommonObj.PortalID, orderdata, addressPath, templateName, transId);
                }
                HttpContext.Current.Session.Remove("OrderCollection");
               
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void SaveErrorLog(string postData)
        {
            var ph = new PayPalHandler();

            try
            {
                //split response into string array using whitespace delimeter
                String[] stringArray = postData.Split('\n');

                // NOTE:
                /*
                * loop is set to start at 1 rather than 0 because first
                string in array will be single word SUCCESS or FAIL
                Only used to verify post data
                */

                int i;
                for (i = 1; i < stringArray.Length - 1; i++)
                {
                    String[] stringArray1 = stringArray[i].Split('=');

                    String sKey = stringArray1[0];
                    String sValue = HttpUtility.UrlDecode(stringArray1[1]);

                    // set string vars to hold variable names using a switch
                    switch (sKey)
                    {
                        case "payment_status":
                            //  odinfo.ResponseReasonText = Convert.ToString(sValue);
                            break;

                        case "mc_fee":
                            // ph.PaymentFee = Convert.ToDouble(sValue);
                            break;

                        case "payer_email":
                            // ph.PayerEmail = Convert.ToString(sValue);
                            break;

                        case "Tx Token":
                            // ph.TxToken = Convert.ToString(sValue);
                            break;

                        case "txn_id":
                            //  odinfo.TransactionID = Convert.ToString(sValue);
                            break;

                    }
                }

               
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    public static PayPalHandler ParseAfterIPN(string postData, int storeID, int portalID, string userName, int customerID, string sessionCode, string TemplateName, string addressPath)
    {
        String sKey, sValue;
        PayPalHandler ph = new PayPalHandler();
        string transID = string.Empty;
        try
        {
                       String[] StringArray = postData.Split('\n');

                       /*
            * loop is set to start at 1 rather than 0 because first
            string in array will be single word SUCCESS or FAIL
            Only used to verify post data
            */
            OrderDetailsCollection ot = new OrderDetailsCollection();
            OrderDetailsInfo odinfo = new OrderDetailsInfo();
            CartManageSQLProvider cms = new CartManageSQLProvider();
            CommonInfo cf = new CommonInfo();
            cf.StoreID = storeID;
            cf.PortalID = portalID;
            cf.AddedBy = userName;
                       AspxOrderDetails objad = new AspxOrderDetails();
            SQLHandler sqlH = new SQLHandler();
                       odinfo.OrderID = int.Parse(HttpContext.Current.Session["OrderID"].ToString());
            int i;
            for (i = 1; i < StringArray.Length - 1; i++)
            {
                String[] StringArray1 = StringArray[i].Split('=');

                sKey = StringArray1[0];
                sValue = HttpUtility.UrlDecode(StringArray1[1]);

                               switch (sKey)
                {
                    case "payment_status":
                        odinfo.ResponseReasonText = Convert.ToString(sValue);
                        break;

                    case "mc_fee":
                                               break;

                    case "payer_email":
                                               break;

                    case "Tx Token":
                                               break;

                    case "txn_id":
                        odinfo.TransactionID = Convert.ToString(sValue);
                        transID = Convert.ToString(sValue);
                        break;

                }
            }

            ot.ObjOrderDetails = odinfo;
            ot.ObjCommonInfo = cf;
            HttpContext.Current.Session.Remove("OrderID");
            HttpContext.Current.Session.Remove("OrderCollection");

            return ph;
        }
        catch (Exception ex)
        {
            
            throw ex;
        }

    }
    private void WebSuccess(string sageRedirectPath)
    {
        if (Session["OrderID"] != null)
        {
            int storeID = GetStoreID;
            int portalID = GetPortalID;
            string userName = GetUsername;
            int customerID = GetCustomerID;
            var orderdata = new OrderDetailsCollection();
            if (HttpContext.Current.Session["OrderCollection"] != null)
            {

                orderdata = (OrderDetailsCollection)HttpContext.Current.Session["OrderCollection"];
                _invoice = orderdata.ObjOrderDetails.InvoiceNumber;
                var pw = new PayPalWCFService();
                int i = orderdata.ObjOrderDetails.PaymentGatewayTypeID;
                List<PayPalSettingInfo> setting = pw.GetAllPayPalSetting(i, storeID, portalID);
                _authToken = setting[0].AuthToken;
                if (orderdata.GiftCardDetail != null && HttpContext.Current.Session["UsedGiftCard"] != null)
                {                      AspxGiftCardController.UpdateGiftCardUsage(orderdata.GiftCardDetail, orderdata.ObjCommonInfo.StoreID,
                                         orderdata.ObjCommonInfo.PortalID, orderdata.ObjOrderDetails.OrderID, orderdata.ObjCommonInfo.AddedBy,
                                         orderdata.ObjCommonInfo.CultureName);
                    HttpContext.Current.Session.Remove("UsedGiftCard");
                }
            }


           
                       _txToken = Request.QueryString.Get("tx");
            _query = string.Format("cmd=_notify-synch&tx={0}&at={1}", _txToken, _authToken);
                                  const string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
            const string strLive = "https://www.paypal.com/cgi-bin/webscr";
            string test = string.Empty;
            if (Session["IsTestPayPal"] != null)
            {

                test = bool.Parse(Session["IsTestPayPal"].ToString()) ? strSandbox : strLive;
            }
            var req = (HttpWebRequest)WebRequest.Create(test);

                       req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = _query.Length;

                       var stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
            stOut.Write(_query);
            stOut.Close();

                       var stIn = new StreamReader(req.GetResponse().GetResponseStream());
            _strResponse = stIn.ReadToEnd();
            stIn.Close();

                       if (_strResponse.StartsWith("SUCCESS"))
            {
                string sessionCode = HttpContext.Current.Session.SessionID;
                                                             try
                {
                    var paypalHandler = new PayPalHandler();
                    var aspxCommonObj = new AspxCommonInfo();
                    aspxCommonObj.StoreID = storeID;
                    aspxCommonObj.PortalID = portalID;
                    aspxCommonObj.UserName = userName;
                    aspxCommonObj.CustomerID = customerID;
                    aspxCommonObj.SessionCode = sessionCode;
                    int orderID = orderdata.ObjOrderDetails.OrderID;
                    paypalHandler.ParseAfterIPN(_strResponse, aspxCommonObj, TemplateName, _addressPath);

                    AspxGiftCardController.IssueGiftCard(orderdata.LstOrderItemsInfo,orderID, true, aspxCommonObj);
                    if (orderdata.GiftCardDetail != null && CheckOutSessions.Get<List<GiftCardUsage>>("UsedGiftCard").Count > 0)
                    {
                        AspxGiftCardController.UpdateGiftCardUsage(orderdata.GiftCardDetail, orderdata.ObjCommonInfo.StoreID,
                                             orderdata.ObjCommonInfo.PortalID, orderdata.ObjOrderDetails.OrderID, orderdata.ObjCommonInfo.AddedBy,
                                             orderdata.ObjCommonInfo.CultureName);

                    }
                }
                catch (Exception)
                {
                    lblerror.Text = GetSageMessage("Payment", "PaymentParsingIPNError");
                }
             
                String[] stringArray = _strResponse.Split('\n');
                int i;
                string status = string.Empty;
                for (i = 1; i < stringArray.Length - 1; i++)
                {
                    String[] stringArray1 = stringArray[i].Split('=');

                    String sKey = stringArray1[0];
                    String sValue = HttpUtility.UrlDecode(stringArray1[1]);

                                       switch (sKey)
                    {
                        case "txn_id":
                            _transID = Convert.ToString(sValue);
                            break;
                        case "payment_status":
                            status = Convert.ToString(sValue);
                            break;

                    }
                }
                lblOrderNo.Text = "#" + Session["OrderID"].ToString();
                lblTransaction.Text = _transID;
                lblInvoice.Text = _invoice;
                lblPaymentMethod.Text = "Paypal";
                lblDateTime.Text = DateTime.Now.ToString("dddd, dd MMMM yyyy ");
                if (status.ToLower().Trim() == "completed")
                {
                    lblerror.Text = GetSageMessage("Payment", "PaymentProcessed");
                }
                else if (status.ToLower().Trim() == "pending")
                {
                    lblerror.Text = GetSageMessage("Payment", "PaymentPending");
                }

                CheckOutHelper cHelper = new CheckOutHelper();
                cHelper.ClearSessions();
    
            }
            else
            {

                lblerror.Text = GetSageMessage("Payment", "PaymentError");
            }
        }
        else
        {
            Response.Redirect(sageRedirectPath, false);
        }
    }
    private void MobileSuccess(string sageRedirectPath)
    {
        try
        {

            if (Session["mb_OrderDetail"] != null)
            {
                var orderInfo = (OrderInfo) Session["mb_OrderDetail"];
                               var giftCardUsage = (List<GiftCardUsage>) Session["mb_GiftCardUsage"];
                var coupons = (List<CouponSession>)Session["mb_CouponSession"];
                               var billingAddress = (UserAddressInfo) Session["mb_BillingAddress"];
                var shippingAddress = (UserAddressInfo) Session["mb_ShippingAddress"];
                var itemsInfo = (List<OrderItem>) Session["mb_ItemDetails"];
                int storeId = orderInfo.StoreId;
                int portalId = orderInfo.PortalId;
                string userName = orderInfo.AddedBy;
                int customerId = orderInfo.CustomerId;
                bool isTestPaypal = false;



                _invoice = orderInfo.InvoiceNumber;
                if (!string.IsNullOrEmpty(orderInfo.TransactionId) && orderInfo.TransactionId.Trim() != "0")
                {
                    lblTransaction.Text = orderInfo.TransactionId;
                    lblInvoice.Text = orderInfo.InvoiceNumber;
                    lblPaymentMethod.Text = orderInfo.PaymentMethodName;
                    lblDateTime.Text = orderInfo.AddedOn.ToString("dddd, dd MMMM yyyy ");
                    lblOrderNo.Text = "#" + orderInfo.OrderId;
                }
                else
                {
                var pw = new PayPalWCFService();
                List<PayPalSettingInfo> setting = pw.GetAllPayPalSetting(orderInfo.PaymentGatewayTypeId, storeId,
                                                                         portalId);
                _authToken = setting[0].AuthToken;
                isTestPaypal = bool.Parse(setting[0].IsTestPaypal);

                if (giftCardUsage != null && giftCardUsage.Count > 0)
                {
                    AspxGiftCardController.UpdateGiftCardUsage(giftCardUsage, storeId,
                                                           portalId,
                                                           orderInfo.OrderId,
                                                           userName,
                                                           orderInfo.CultureName);

                }



               
                               _txToken = Request.QueryString.Get("tx");
                _query = string.Format("cmd=_notify-synch&tx={0}&at={1}", _txToken, _authToken);
                                              const string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
                const string strLive = "https://www.paypal.com/cgi-bin/webscr";
                string test;
                if (Session["IsTestPayPal"] != null)
                {
                    test = bool.Parse(Session["IsTestPayPal"].ToString()) ? strSandbox : strLive;
                }
                else
                {
                    test = isTestPaypal ? strSandbox : strLive;
                }
                var req = (HttpWebRequest) WebRequest.Create(test);

                               req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = _query.Length;

                               var stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
                stOut.Write(_query);
                stOut.Close();

                               var stIn = new StreamReader(req.GetResponse().GetResponseStream());
                _strResponse = stIn.ReadToEnd();
                stIn.Close();

                               if (_strResponse.StartsWith("SUCCESS"))
                {
                    string sessionCode = orderInfo.SessionCode;
                                                                             try
                    {
                        var paypalHandler = new PayPalHandler();
                                               
                                               paypalHandler.ParseAfterIPNMobile(orderInfo, coupons, itemsInfo, _strResponse,
                                                          billingAddress,
                                                          shippingAddress,
                                                          TemplateName,
                                                          _addressPath);


                    }
                    catch (Exception)
                    {
                        lblerror.Text = GetSageMessage("Payment", "PaymentParsingIPNError");
                    }
                 
                    String[] stringArray = _strResponse.Split('\n');
                    int i;
                    string status = string.Empty;
                    for (i = 1; i < stringArray.Length - 1; i++)
                    {
                        String[] stringArray1 = stringArray[i].Split('=');

                        String sKey = stringArray1[0];
                        String sValue = HttpUtility.UrlDecode(stringArray1[1]);

                                               switch (sKey)
                        {
                            case "txn_id":
                                _transID = Convert.ToString(sValue);
                                break;
                            case "payment_status":
                                status = Convert.ToString(sValue);
                                break;

                        }
                    }
                    lblOrderNo.Text = "#" + orderInfo.OrderId;
                    lblTransaction.Text = _transID;
                    lblInvoice.Text = _invoice;
                    lblPaymentMethod.Text = "Paypal";
                    lblDateTime.Text = DateTime.Now.ToString("dddd, dd MMMM yyyy ");
                    if (status.ToLower().Trim() == "completed")
                    {
                        lblerror.Text = GetSageMessage("Payment", "PaymentProcessed");
                    }
                    else if (status.ToLower().Trim() == "pending")
                    {
                        lblerror.Text = GetSageMessage("Payment", "PaymentPending");
                    }
                    Session.Clear();
                    }
                }
                Session.Clear();
            }
            else
            {
                Response.Redirect(sageRedirectPath);
            }
        }
        catch (Exception ex)
        {

            ProcessException(ex);
        }

    }