示例#1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            AspxCommonInfo aspxCommonObj = new AspxCommonInfo();
            aspxCommonObj.StoreID     = GetStoreID;
            aspxCommonObj.PortalID    = GetPortalID;
            aspxCommonObj.UserName    = GetUsername;
            aspxCommonObj.CultureName = GetCurrentCultureName;
            if (!IsPostBack)
            {
                StoreSettingConfig ssc = new StoreSettingConfig();
                if (Session["CurrencyCode"] != null && Session["CurrencyCode"] != "")
                {
                    SelectedCurrency = Session["CurrencyCode"].ToString();
                }
                else
                {
                    SelectedCurrency = ssc.GetStoreSettingsByKey(StoreSetting.MainCurrency, GetStoreID, GetPortalID, GetCurrentCultureName);
                }
                IncludeJs("Currencyconversion", "/js/CurrencyFormat/jquery.formatCurrency-1.4.0.js", "/js/CurrencyFormat/jquery.formatCurrency.all.js", "/js/FancyDropDown/fancyDropDown.js", "/Modules/AspxCommerce/AspxCurrencyConverter/js/AspxCurrencyConverter.js");//
                IncludeCss("Currencyconversion", "/Templates/" + TemplateName + "/css/FancyDropDown/fancy.css");
                StoreID      = GetStoreID;
                PortalID     = GetPortalID;
                CultureName  = GetCurrentCultureName;
                MainCurrency = ssc.GetStoreSettingsByKey(StoreSetting.MainCurrency, StoreID, PortalID, CultureName);

                MyAccoutURL = ssc.GetStoreSettingsByKey(StoreSetting.MyAccountURL, StoreID, PortalID, CultureName);
                SingleAddressCheckOutURL = ssc.GetStoreSettingsByKey(StoreSetting.SingleCheckOutURL, StoreID, PortalID, CultureName);
                CompareItemListURL       = ssc.GetStoreSettingsByKey(StoreSetting.CompareItemURL, StoreID, PortalID, CultureName);
                MyCartURL       = ssc.GetStoreSettingsByKey(StoreSetting.ShoppingCartURL, StoreID, PortalID, CultureName);
                AdditionalCVR   = ssc.GetStoreSettingsByKey(StoreSetting.AdditionalCVR, StoreID, PortalID, CultureName);
                ItemMgntPageURL = ssc.GetStoreSettingsByKey(StoreSetting.ItemMgntPageURL, StoreID, PortalID, CultureName);
                if (Session["Region"] != null && Session["Region"] != "")
                {
                    Region = Session["Region"].ToString();
                }
                else
                {
                    Region = StoreSetting.GetRegionFromCurrencyCode(SelectedCurrency, StoreID, PortalID);
                }

                AspxCommerceWebService aws = new AspxCommerceWebService();
                aws.GetCurrencyRateOnChange(aspxCommonObj, MainCurrency, SelectedCurrency, Region);
                if (Session["CurrencyRate"] != null && Session["CurrencyRate"] != "")
                {
                    currencyRate = Math.Round(double.Parse(Session["CurrencyRate"].ToString()), 4);
                }
            }
            IncludeLanguageJS();
            //BindCurrencyList();
        }
        catch (Exception ex)
        {
            ProcessException(ex);
        }
    }
示例#2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ModuleServicePath = ResolveUrl("~") + "Modules/AspxCommerce/AspxCommerceServices/";

            aspxCommonObj.StoreID     = GetStoreID;
            aspxCommonObj.PortalID    = GetPortalID;
            aspxCommonObj.CultureName = GetCurrentCultureName;
            AspxCommerceWebService   objHeavyDiscount = new AspxCommerceWebService();
            HeavyDiscountSettingInfo objSettingInfo   = objHeavyDiscount.GetHeavyDiscountSetting(aspxCommonObj);
            NoOfItemShown            = objSettingInfo.NoOfItemShown;
            EnableHeavyDiscountItems = objSettingInfo.EnableModule;
            HeavyDiscountPercent     = objSettingInfo.DiscountValue;
        }
        IncludeLanguageJS();
    }
    private void StartProccess()
    {
        try
        {
            var ssc = new StoreSettingConfig();
            Currency = ssc.GetStoreSettingsByKey(StoreSetting.MainCurrency, OrderDetail.StoreId, OrderDetail.PortalId, OrderDetail.CultureName);
            AspxCommonInfo aspxCommonObj = new AspxCommonInfo();
            aspxCommonObj.StoreID  = OrderDetail.StoreId;
            aspxCommonObj.PortalID = OrderDetail.PortalId;
            if (PaypalSupportedCurrency.paypalSupportedCurrency.Split(',').Where(s => string.Compare(Currency, s, true) == 0).Count() > 0)
            {
                Rate             = 1;
                SelectedCurrency = Currency;
            }
            else
            {
                var aws = new AspxCommerceWebService();
                Rate             = aws.GetCurrencyRateOnChange(aspxCommonObj, Currency, "USD", "en-US");
                Currency         = "USD";
                SelectedCurrency = Currency;

                //Some time if selected currency does not exist in currency table then it returns 1,
                //if we take 1 as rate then it will convert same as previous amount
                // So avoid Transaction by making it 0
                if (Rate == 1)
                {
                    Rate = 0;
                }
            }
            if (Rate != 0)
            {
                // Set Transaction Currency code in session to save transactionLog table
                Session["SelectedCurrency"] = SelectedCurrency;
                LoadSetting();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
示例#4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                if (Session["GoogleCheckOutData"] != null)
                {
                    string[] data = Session["GoogleCheckOutData"].ToString().Split('#');
                    storeID     = int.Parse(data[0].ToString());
                    portalID    = int.Parse(data[1].ToString());
                    userName    = data[2];
                    customerID  = int.Parse(data[3].ToString());
                    sessionCode = data[4].ToString();
                    cultureName = data[5];
                    itemIds     = data[6];
                    couponCode  = data[7];
                    Spath       = ResolveUrl("~/Modules/AspxCommerce/AspxCommerceServices/");

                    StoreSettingConfig ssc = new StoreSettingConfig();
                    MainCurrency = ssc.GetStoreSettingsByKey(StoreSetting.MainCurrency, storeID, portalID, cultureName);
                    AspxCommonInfo aspxCommonObj = new AspxCommonInfo();
                    aspxCommonObj.StoreID  = storeID;
                    aspxCommonObj.PortalID = portalID;
                    if (GoogleCheckOutSupportedCurrency.googleCheckOutSupportedCurrency.Split(',').Where(s => string.Compare(MainCurrency, s, true) == 0).Count() > 0)
                    {
                        rate             = 1;
                        SelectedCurrency = MainCurrency;
                    }
                    else
                    {
                        AspxCommerceWebService aws = new AspxCommerceWebService();
                        rate             = aws.GetCurrencyRateOnChange(aspxCommonObj, MainCurrency, "USD", "en-US");
                        MainCurrency     = "USD";
                        SelectedCurrency = MainCurrency;

                        /* Some time if selected currency does not exist in currency table then it returns 1,
                         *    if we take 1 as rate then it will convert same as previous amount
                         *     So avoid Transaction by making it 0 */
                        if (rate == 1)
                        {
                            rate = 0;
                        }
                    }

                    if (rate != 0)
                    {
                        // Set Transaction Currency code in session to save transactionLog table
                        //Session["SelectedCurrency"] = SelectedCurrency;
                        LoadSetting();
                    }
                    else
                    {
                        lblnotity.Text    = "Something goes wrong, hit refresh or go back to checkout";
                        clickhere.Visible = false;
                    }
                    HttpContext.Current.Session.Remove("GoogleCheckOutData");
                }
                else
                {
                    lblnotity.Text    = "Something goes wrong, hit refresh or go back to checkout";
                    clickhere.Visible = false;
                }
            }
            catch (Exception ex)
            {
                lblnotity.Text    = "Something goes wrong, hit refresh or go back to checkout";
                clickhere.Visible = false;
                ProcessException(ex);
            }
        }
    }
    protected void SendConfrimMessage()
    {
        try
        {
            if (Session["OrderID"] != null)
            {
                string transID            = string.Empty; // transaction ID from Relay Response
                int    responseCode       = 1;            // response code, defaulted to Invalid
                string responsereasontext = string.Empty;
                responsereasontext = "Transaction occured Successfully";
                int    responsereasonCode         = 1;
                string purchaseorderNo            = string.Empty;
                string invoice                    = string.Empty;
                string paymentmethod              = string.Empty;
                OrderDetailsCollection orderdata2 = new OrderDetailsCollection();
                if (HttpContext.Current.Session["OrderCollection"] != null)
                {
                    orderdata2 = (OrderDetailsCollection)HttpContext.Current.Session["OrderCollection"];
                }
                invoice = orderdata2.ObjOrderDetails.InvoiceNumber.ToString();
                Random random = new Random();
                purchaseorderNo = (random.Next(0, 1000)).ToString();
                string timeStamp = ((int)(DateTime.UtcNow - new DateTime(2011, 1, 1)).TotalSeconds).ToString();
                transID               = (random.Next(99999, 111111)).ToString();
                lblTransaction.Text   = transID;
                lblInvoice.Text       = invoice;
                lblPaymentMethod.Text = "Cash On Delivery";
                lblDateTime.Text      = DateTime.Now.ToString("dddd, dd MMMM yyyy ");
                int    storeID     = int.Parse(GetStoreID.ToString());
                int    portalID    = int.Parse(GetPortalID.ToString());
                string userName    = GetUsername.ToString();
                int    customerID  = int.Parse(GetCustomerID.ToString());
                string sessionCode = HttpContext.Current.Session.SessionID.ToString();
                string result      = CashOnDelivery.Parse(transID, invoice, purchaseorderNo, responseCode, responsereasonCode, responsereasontext, storeID, portalID, userName, customerID, sessionCode);
                lblerror.Text = result.ToString();
                lblerror.Text = GetSageMessage("Payment", "PaymentProcessed");
                TransactionLogInfo tinfo = new TransactionLogInfo();
                TransactionLog     Tlog  = new TransactionLog();

                tinfo.TransactionID      = transID;
                tinfo.AuthCode           = "";
                tinfo.TotalAmount        = decimal.Parse(orderdata2.ObjOrderDetails.GrandTotal.ToString());
                tinfo.ResponseCode       = responseCode.ToString();
                tinfo.ResponseReasonText = responsereasontext;
                tinfo.OrderID            = orderdata2.ObjOrderDetails.OrderID;
                tinfo.StoreID            = orderdata2.ObjCommonInfo.StoreID;
                tinfo.PortalID           = orderdata2.ObjCommonInfo.PortalID;
                tinfo.AddedBy            = orderdata2.ObjCommonInfo.AddedBy;
                tinfo.CustomerID         = orderdata2.ObjOrderDetails.CustomerID;
                tinfo.SessionCode        = orderdata2.ObjOrderDetails.SessionCode;
                tinfo.PaymentGatewayID   = orderdata2.ObjOrderDetails.PaymentGatewayTypeID;
                tinfo.PaymentStatus      = "Processed";
                tinfo.CreditCard         = "";
                Tlog.SaveTransactionLog(tinfo);

                AspxCommerceWebService clSes = new AspxCommerceWebService();
                if (Session["IsFreeShipping"] != null)
                {
                    HttpContext.Current.Session.Remove("IsFreeShipping");
                }
                if (Session["DiscountAmount"] != null)
                {
                    HttpContext.Current.Session.Remove("DiscountAmount");
                }
                if (Session["CouponCode"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponCode");
                }
                if (Session["CouponApplied"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponApplied");
                }
                if (Session["DiscountAll"] != null)
                {
                    HttpContext.Current.Session.Remove("DiscountAll");
                }
                if (Session["TaxAll"] != null)
                {
                    HttpContext.Current.Session.Remove("TaxAll");
                }
                if (Session["ShippingCostAll"] != null)
                {
                    HttpContext.Current.Session.Remove("ShippingCostAll");
                }
                if (Session["GrandTotalAll"] != null)
                {
                    HttpContext.Current.Session.Remove("GrandTotalAll");
                }
                if (Session["Gateway"] != null)
                {
                    HttpContext.Current.Session.Remove("Gateway");
                }

                //invoice  transID

                if (Session["OrderCollection"] != null)
                {
                    OrderDetailsCollection orderdata = new OrderDetailsCollection();
                    orderdata = (OrderDetailsCollection)Session["OrderCollection"];
                    try
                    {
                        EmailTemplate.SendEmailForOrder(GetPortalID, orderdata, addressPath, TemplateName, transID);
                    }
                    catch
                    {
                        lblerror.Text = "";
                        lblerror.Text = GetSageMessage("Payment", "EmailSendOrderProblem");
                    }
                    clSes.ClearSessionVariable("OrderCollection");
                }
            }
            else
            {
                Response.Redirect(sageRedirectPath, false);
            }
        }
        catch (Exception ex)
        {
            ProcessException(ex);
        }
    }
示例#6
0
    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)
                {   //updating giftcard used in chekout
                    AspxGiftCardController.UpdateGiftCardUsage(orderdata.GiftCardDetail, orderdata.ObjCommonInfo.StoreID,
                                                               orderdata.ObjCommonInfo.PortalID, orderdata.ObjOrderDetails.OrderID, orderdata.ObjCommonInfo.AddedBy,
                                                               orderdata.ObjCommonInfo.CultureName);
                    HttpContext.Current.Session.Remove("UsedGiftCard");
                }
            }


            // authToken = "QMtOC54_YHYUkoggkMZ81ivNWSxPXduIqS5oMynafeUGRL1Rv5OTtUd4rvq";

            //read in txn token from querystring
            _txToken = Request.QueryString.Get("tx");
            _query   = string.Format("cmd=_notify-synch&tx={0}&at={1}", _txToken, _authToken);
            // Create the request back
            // string url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
            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);

            // Set values for the request back
            req.Method        = "POST";
            req.ContentType   = "application/x-www-form-urlencoded";
            req.ContentLength = _query.Length;

            // Write the request back IPN strings
            var stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
            stOut.Write(_query);
            stOut.Close();

            // Do the request to PayPal and get the response
            var stIn = new StreamReader(req.GetResponse().GetResponseStream());
            _strResponse = stIn.ReadToEnd();
            stIn.Close();

            // If response was SUCCESS, parse response string and output details
            if (_strResponse.StartsWith("SUCCESS"))
            {
                string sessionCode = HttpContext.Current.Session.SessionID;
                //for localhost
                // PayPalHandler pdt = PayPalHandler.Parse(strResponse, storeID, portalID, userName, customerID, sessionCode);
                //for live site
                try
                {
                    var paypalHandler = new PayPalHandler();
                    var aspxCommonObj = new AspxCommonInfo();
                    aspxCommonObj.StoreID     = storeID;
                    aspxCommonObj.PortalID    = portalID;
                    aspxCommonObj.UserName    = userName;
                    aspxCommonObj.CustomerID  = customerID;
                    aspxCommonObj.SessionCode = sessionCode;
                    paypalHandler.ParseAfterIPN(_strResponse, aspxCommonObj, TemplateName, _addressPath);

                    AspxGiftCardController.IssueGiftCard(orderdata.LstOrderItemsInfo, false, aspxCommonObj);
                    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");
                    }
                }
                catch (Exception)
                {
                    lblerror.Text = GetSageMessage("Payment", "PaymentParsingIPNError");
                }
                var clSes = new AspxCommerceWebService();

                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]);

                    // set string vars to hold variable names using a switch
                    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");
                }

                if (Session["IsFreeShipping"] != null)
                {
                    HttpContext.Current.Session.Remove("IsFreeShipping");
                }
                if (Session["OrderID"] != null)
                {
                    HttpContext.Current.Session.Remove("OrderID");
                }
                if (Session["DiscountAmount"] != null)
                {
                    HttpContext.Current.Session.Remove("DiscountAmount");
                }
                if (Session["IsCouponInPercent"] != null)
                {
                    HttpContext.Current.Session.Remove("IsCouponInPercent");
                }
                if (Session["CouponPercentValue"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponPercentValue");
                }
                if (Session["CouponSessionPercentAmount"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponSessionPercentAmount");
                }
                if (Session["CouponSessionAmount"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponSessionAmount");
                }
                if (Session["CouponCode"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponCode");
                }
                if (Session["CouponApplied"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponApplied");
                }
                Session.Remove("IsTestPayPal");
                if (Session["DiscountAll"] != null)
                {
                    HttpContext.Current.Session.Remove("DiscountAll");
                }
                if (Session["TaxAll"] != null)
                {
                    HttpContext.Current.Session.Remove("TaxAll");
                }
                if (Session["ShippingCostAll"] != null)
                {
                    HttpContext.Current.Session.Remove("ShippingCostAll");
                }
                if (Session["GrandTotalAll"] != null)
                {
                    HttpContext.Current.Session.Remove("GrandTotalAll");
                }
                if (Session["Gateway"] != null)
                {
                    HttpContext.Current.Session.Remove("Gateway");
                }
            }
            else
            {
                lblerror.Text = GetSageMessage("Payment", "PaymentError");
            }
        }
        else
        {
            Response.Redirect(sageRedirectPath, false);
        }
    }
示例#7
0
    private void MobileSuccess(string sageRedirectPath)
    {
        try
        {
            if (Session["mb_OrderDetail"] != null)
            {
                var orderInfo = (OrderInfo)Session["mb_OrderDetail"];
                //Session["mb_IsCheckoutFromMobile"];
                var    giftCardUsage     = (List <GiftCardUsage>)Session["mb_GiftCardUsage"];
                var    couponCode        = Session["mb_CouponCode"].ToString();
                var    couponCodeApplied = int.Parse(Session["mb_CouponCodeApplied"].ToString());
                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);
                    }



                    // authToken = "QMtOC54_YHYUkoggkMZ81ivNWSxPXduIqS5oMynafeUGRL1Rv5OTtUd4rvq";

                    //read in txn token from querystring
                    _txToken = Request.QueryString.Get("tx");
                    _query   = string.Format("cmd=_notify-synch&tx={0}&at={1}", _txToken, _authToken);
                    // Create the request back
                    // string url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
                    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);

                    // Set values for the request back
                    req.Method        = "POST";
                    req.ContentType   = "application/x-www-form-urlencoded";
                    req.ContentLength = _query.Length;

                    // Write the request back IPN strings
                    var stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
                    stOut.Write(_query);
                    stOut.Close();

                    // Do the request to PayPal and get the response
                    var stIn = new StreamReader(req.GetResponse().GetResponseStream());
                    _strResponse = stIn.ReadToEnd();
                    stIn.Close();

                    // If response was SUCCESS, parse response string and output details
                    if (_strResponse.StartsWith("SUCCESS"))
                    {
                        string sessionCode = orderInfo.SessionCode;
                        //for localhost
                        // PayPalHandler pdt = PayPalHandler.Parse(strResponse, storeID, portalID, userName, customerID, sessionCode);
                        //for live site
                        try
                        {
                            var paypalHandler = new PayPalHandler();
                            //Get billing address by orderId
                            var couponUsage = "";
                            if (!string.IsNullOrEmpty(couponCode))
                            {
                                couponUsage = couponCode + "#" + couponCodeApplied;
                            }
                            //get shipping address by orderId
                            paypalHandler.ParseAfterIPNMobile(orderInfo, couponUsage, itemsInfo, _strResponse,
                                                              billingAddress,
                                                              shippingAddress,
                                                              TemplateName,
                                                              _addressPath);
                        }
                        catch (Exception)
                        {
                            lblerror.Text = GetSageMessage("Payment", "PaymentParsingIPNError");
                        }
                        var clSes = new AspxCommerceWebService();

                        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]);

                            // set string vars to hold variable names using a switch
                            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);
        }
    }
示例#8
0
        public static List <CommonRateList> GetRate(ItemListDetails itemsDetail)
        {
            try
            {
                System.Net.ServicePointManager.Expect100Continue = false;
                var rateInfo = new List <CommonRateList>();
                //to get Dynamic Fuctions info
                List <MethodList> rateMethods = GetAllMethodsFromProvider(itemsDetail.CommonInfo.StoreID,
                                                                          itemsDetail.CommonInfo.PortalID);
                WareHouseAddress originAddress = GetWareHouseAddress(itemsDetail.CommonInfo.StoreID,
                                                                     itemsDetail.CommonInfo.PortalID);


                itemsDetail.WareHouseAddress = originAddress;


                if (itemsDetail.BasketItems.Count > 0)
                {
                    foreach (var method in rateMethods)
                    {
                        List <ParamList> paramList = GetParamsOfMethod(method.DynamicMethodId, itemsDetail.CommonInfo.StoreID, itemsDetail.CommonInfo.PortalID);
                        foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
                        {
                            Type type            = ass.GetType(method.NameSpace + "." + method.ClassName, false);
                            var  paramCollection = new List <object>();


                            if (type != null)
                            {
                                for (int i = 0; i < paramList.Count; i++)
                                {
                                    var param = ass.GetType(method.NameSpace + "." + paramList[i].ParameterName, false);
                                    //  Type listType = typeof (List<>).MakeGenericType(new Type[] {param});
                                    Type t = itemsDetail.GetType();

                                    if (param != null)
                                    {
                                        switch (paramList[i].ParameterType)
                                        {
                                        case "list":
                                            //itemslist
                                            var itemsList =
                                                DynamicUtility.TransferDataToList(itemsDetail.BasketItems,
                                                                                  itemsDetail,
                                                                                  param, method.AssemblyName);
                                            paramCollection.Add(itemsList);
                                            break;

                                        default:
                                            var pa = DynamicUtility.PassMembersValue(itemsDetail, param,
                                                                                     method.AssemblyName);
                                            paramCollection.Add(pa);
                                            break;
                                        }
                                    }
                                    if (param == null && paramList[i].ParameterName != "")
                                    {
                                        switch (paramList[i].ParameterName)
                                        {
                                        case "storeId":
                                            paramCollection.Add(itemsDetail.CommonInfo.StoreID);
                                            break;

                                        case "portalId":
                                            paramCollection.Add(itemsDetail.CommonInfo.PortalID);
                                            break;

                                        case "providerId":
                                            paramCollection.Add(method.ShippingProviderId);
                                            break;
                                        }
                                    }

                                    // Type listType1 = param1.MakeGenericType(new Type[] { param1 });
                                    //  ((method.ClassName) Activator.CreateInstance(Type.GetType(method.ClassName)));
                                    // DynamicUtility.Cast<listType>(originAddress);
                                }



                                //var obj = new Object[] {originAddress, da, packagedimension};

                                object     instance = Activator.CreateInstance(type);
                                MethodInfo fn       = type.GetMethod(method.MethodName);
                                var        obj      = paramCollection.ToArray();
                                System.Net.ServicePointManager.Expect100Continue = false;
                                var rateResponse = fn.Invoke(instance,
                                                             BindingFlags.InvokeMethod | BindingFlags.Public |
                                                             BindingFlags.Static,
                                                             null, obj, null);

                                List <CommonRateList> cl = DynamicUtility.CastToList <CommonRateList>(rateResponse);

                                //list of available shipping method of store
                                rateInfo.AddRange(cl);
                                break;
                            }
                        }
                    }
                }
                //GetProvidersAvailableMethod
                var allowedshippingMethods = GetProvidersAvailableMethod(itemsDetail.CommonInfo.StoreID,
                                                                         itemsDetail.CommonInfo.PortalID, itemsDetail.CommonInfo.CultureName);
                //filtering allowed shipping methods only
                var filterdmethods = new List <CommonRateList>();
                //  filterdmethods = rateInfo.Where(x => allowedshippingMethods.Any(y => x.ShippingMethodName == y.ShippingMethodName)).
                // ToList();

                AspxCommerceWebService    coreService = new AspxCommerceWebService();
                List <ShippingMethodInfo> flatRates   =
                    coreService.GetShippingMethodByWeight(itemsDetail.CommonInfo.StoreID,
                                                          itemsDetail.CommonInfo.PortalID,
                                                          itemsDetail.CommonInfo.
                                                          CustomerID,
                                                          itemsDetail.CommonInfo.UserName,
                                                          itemsDetail.CommonInfo.
                                                          CultureName,
                                                          itemsDetail.CommonInfo.
                                                          SessionCode);
                foreach (var item in flatRates)
                {
                    var cr = new CommonRateList
                    {
                        CurrencyCode       = "",
                        ImagePath          = item.ImagePath,
                        ShippingMethodId   = item.ShippingMethodID,
                        DeliveryTime       = item.DeliveryTime,
                        ShippingMethodName = item.ShippingMethodName,
                        TotalCharges       = decimal.Parse(item.ShippingCost)
                    };
                    //filterdmethods.Insert(0, cr);
                    filterdmethods.Add(cr);
                }

                foreach (var commonRateList in allowedshippingMethods)
                {
                    foreach (var info in rateInfo)
                    {
                        if (info.ShippingMethodName == commonRateList.ShippingMethodName)
                        {
                            var filterdmethod = info;
                            filterdmethod.ShippingMethodId = commonRateList.ShippingMethodID;
                            filterdmethods.Add(filterdmethod);
                            break;
                        }
                    }
                }


                return(filterdmethods);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public static List<CommonRateList> GetRate(ItemListDetails itemsDetail)
        {
            try
            {
                System.Net.ServicePointManager.Expect100Continue = false;
                var rateInfo = new List<CommonRateList>();
                //to get Dynamic Fuctions info
                List<MethodList> rateMethods = GetAllMethodsFromProvider(itemsDetail.CommonInfo.StoreID,
                                                                         itemsDetail.CommonInfo.PortalID);
                WareHouseAddress originAddress = GetWareHouseAddress(itemsDetail.CommonInfo.StoreID,
                                                                     itemsDetail.CommonInfo.PortalID);


                itemsDetail.WareHouseAddress = originAddress;


                if (itemsDetail.BasketItems.Count > 0)
                {

                    foreach (var method in rateMethods)
                    {
                        List<ParamList> paramList = GetParamsOfMethod(method.DynamicMethodId, itemsDetail.CommonInfo.StoreID,itemsDetail.CommonInfo.PortalID);
                        foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
                        {
                            Type type = ass.GetType(method.NameSpace + "." + method.ClassName, false);
                            var paramCollection = new List<object>();


                            if (type != null)
                            {

                                for (int i = 0; i < paramList.Count; i++)
                                {
                                    var param = ass.GetType(method.NameSpace + "." + paramList[i].ParameterName, false);
                                    //  Type listType = typeof (List<>).MakeGenericType(new Type[] {param});
                                    Type t = itemsDetail.GetType();

                                    if (param != null)
                                    {
                                        switch (paramList[i].ParameterType)
                                        {
                                            case "list":
                                                //itemslist
                                                var itemsList =
                                                    DynamicUtility.TransferDataToList(itemsDetail.BasketItems,
                                                                                      itemsDetail,
                                                                                      param, method.AssemblyName);
                                                paramCollection.Add(itemsList);
                                                break;

                                            default:
                                                var pa = DynamicUtility.PassMembersValue(itemsDetail, param,
                                                                                         method.AssemblyName);
                                                paramCollection.Add(pa);
                                                break;

                                        }
                                    }
                                    if (param == null && paramList[i].ParameterName != "")
                                    {
                                        switch (paramList[i].ParameterName)
                                        {
                                            case "storeId":
                                                paramCollection.Add(itemsDetail.CommonInfo.StoreID);
                                                break;
                                            case "portalId":
                                                paramCollection.Add(itemsDetail.CommonInfo.PortalID);
                                                break;
                                            case "providerId":
                                                paramCollection.Add(method.ShippingProviderId);
                                                break;
                                        }
                                    }

                                    // Type listType1 = param1.MakeGenericType(new Type[] { param1 });
                                    //  ((method.ClassName) Activator.CreateInstance(Type.GetType(method.ClassName)));
                                    // DynamicUtility.Cast<listType>(originAddress);
                                }



                                //var obj = new Object[] {originAddress, da, packagedimension};

                                object instance = Activator.CreateInstance(type);
                                MethodInfo fn = type.GetMethod(method.MethodName);
                                var obj = paramCollection.ToArray();
                                System.Net.ServicePointManager.Expect100Continue = false;
                                var rateResponse = fn.Invoke(instance,
                                                             BindingFlags.InvokeMethod | BindingFlags.Public |
                                                             BindingFlags.Static,
                                                             null, obj, null);

                                List<CommonRateList> cl = DynamicUtility.CastToList<CommonRateList>(rateResponse);

                                //list of available shipping method of store
                                rateInfo.AddRange(cl);
                                break;
                            }

                        }

                    }
                }
                //GetProvidersAvailableMethod
                var allowedshippingMethods = GetProvidersAvailableMethod(itemsDetail.CommonInfo.StoreID,
                                                                         itemsDetail.CommonInfo.PortalID, itemsDetail.CommonInfo.CultureName);
                //filtering allowed shipping methods only
                var filterdmethods = new List<CommonRateList>();
                //  filterdmethods = rateInfo.Where(x => allowedshippingMethods.Any(y => x.ShippingMethodName == y.ShippingMethodName)).
                // ToList();

                AspxCommerceWebService coreService = new AspxCommerceWebService();
                List<ShippingMethodInfo> flatRates =
                    coreService.GetShippingMethodByWeight(itemsDetail.CommonInfo.StoreID,
                                                          itemsDetail.CommonInfo.PortalID,
                                                          itemsDetail.CommonInfo.
                                                              CustomerID,
                                                          itemsDetail.CommonInfo.UserName,
                                                          itemsDetail.CommonInfo.
                                                              CultureName,
                                                          itemsDetail.CommonInfo.
                                                              SessionCode);
                foreach (var item in flatRates)
                {
                    var cr = new CommonRateList
                    {
                        CurrencyCode = "",
                        ImagePath = item.ImagePath,
                        ShippingMethodId = item.ShippingMethodID,
                        DeliveryTime = item.DeliveryTime,
                        ShippingMethodName = item.ShippingMethodName,
                        TotalCharges = decimal.Parse(item.ShippingCost)
                    };
                    //filterdmethods.Insert(0, cr);
                    filterdmethods.Add(cr);
                }

                foreach (var commonRateList in allowedshippingMethods)
                {
                    foreach (var info in rateInfo)
                    {
                        if (info.ShippingMethodName == commonRateList.ShippingMethodName)
                        {
                            var filterdmethod = info;
                            filterdmethod.ShippingMethodId = commonRateList.ShippingMethodID;
                            filterdmethods.Add(filterdmethod);
                            break;
                        }
                    }
                }


                return filterdmethods;
            }
            catch (Exception e)
            {

                throw e;
            }
        }
    protected void SendConfrimMessage()
    {
        try
        {
            if (Session["OrderID"] != null)
            {
                string transID = string.Empty; // transaction ID from Relay Response
                int responseCode = 1; // response code, defaulted to Invalid
                string responsereasontext = string.Empty;
                responsereasontext = "Transaction occured Successfully";
                int responsereasonCode = 1;
                string purchaseorderNo = string.Empty;
                string invoice = string.Empty;
                string paymentmethod = string.Empty;
                OrderDetailsCollection orderdata2 = new OrderDetailsCollection();
                if (HttpContext.Current.Session["OrderCollection"] != null)
                {
                  
                    orderdata2 = (OrderDetailsCollection)HttpContext.Current.Session["OrderCollection"];
                   
                }
                invoice = orderdata2.ObjOrderDetails.InvoiceNumber.ToString();
                Random random = new Random();
                purchaseorderNo = (random.Next(0, 1000)).ToString();
                string timeStamp = ((int)(DateTime.UtcNow - new DateTime(2011, 1, 1)).TotalSeconds).ToString();
                transID = (random.Next(99999, 111111)).ToString();
                lblTransaction.Text = transID;
                lblInvoice.Text = invoice;
                lblPaymentMethod.Text = "Cash On Delivery";
                lblDateTime.Text = DateTime.Now.ToString("dddd, dd MMMM yyyy ");
                int storeID = int.Parse(GetStoreID.ToString());
                int portalID = int.Parse(GetPortalID.ToString());
                string userName = GetUsername.ToString();
                int customerID = int.Parse(GetCustomerID.ToString());
                string sessionCode = HttpContext.Current.Session.SessionID.ToString();
                string result = CashOnDelivery.Parse(transID, invoice, purchaseorderNo, responseCode, responsereasonCode, responsereasontext, storeID, portalID, userName, customerID, sessionCode);
                lblerror.Text = result.ToString();
                lblerror.Text = GetSageMessage("Payment", "PaymentProcessed"); 
                TransactionLogInfo tinfo = new TransactionLogInfo();
                TransactionLog Tlog = new TransactionLog();

                tinfo.TransactionID = transID;
                tinfo.AuthCode = "";
                tinfo.TotalAmount = decimal.Parse(orderdata2.ObjOrderDetails.GrandTotal.ToString());
                tinfo.ResponseCode = responseCode.ToString();
                tinfo.ResponseReasonText = responsereasontext;
                tinfo.OrderID = orderdata2.ObjOrderDetails.OrderID;
                tinfo.StoreID =  orderdata2.ObjCommonInfo.StoreID;
                tinfo.PortalID = orderdata2.ObjCommonInfo.PortalID;
                tinfo.AddedBy = orderdata2.ObjCommonInfo.AddedBy;
                tinfo.CustomerID = orderdata2.ObjOrderDetails.CustomerID;
                tinfo.SessionCode = orderdata2.ObjOrderDetails.SessionCode;
                tinfo.PaymentGatewayID = orderdata2.ObjOrderDetails.PaymentGatewayTypeID;
                tinfo.PaymentStatus = "Processed";
                tinfo.CreditCard = "";
                Tlog.SaveTransactionLog(tinfo);

                AspxCommerceWebService clSes = new AspxCommerceWebService();
                if (Session["IsFreeShipping"] != null)
                {
                    HttpContext.Current.Session.Remove("IsFreeShipping");
                }
                if (Session["DiscountAmount"] != null)
                {
                    HttpContext.Current.Session.Remove("DiscountAmount");

                }
                if (Session["CouponCode"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponCode");
                }
                if (Session["CouponApplied"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponApplied");
                }
                if (Session["DiscountAll"] != null)
                {
                    HttpContext.Current.Session.Remove("DiscountAll");
                }
                if (Session["TaxAll"] != null)
                {
                    HttpContext.Current.Session.Remove("TaxAll");
                }
                if (Session["ShippingCostAll"] != null)
                {
                    HttpContext.Current.Session.Remove("ShippingCostAll");
                }
                if (Session["GrandTotalAll"] != null)
                {
                    HttpContext.Current.Session.Remove("GrandTotalAll");
                }
                if (Session["Gateway"] != null)
                {
                    HttpContext.Current.Session.Remove("Gateway");
                }  

                //invoice  transID

                if (Session["OrderCollection"] != null)
                {
                    OrderDetailsCollection orderdata = new OrderDetailsCollection();
                    orderdata = (OrderDetailsCollection)Session["OrderCollection"];
                    try
                    {
                        EmailTemplate.SendEmailForOrder(GetPortalID, orderdata, addressPath, TemplateName, transID);
                    }
                    catch
                    {
                        lblerror.Text = "";
                        lblerror.Text= GetSageMessage("Payment", "EmailSendOrderProblem");
                    }
                    clSes.ClearSessionVariable("OrderCollection");
                }
            }
            else
            {
                Response.Redirect(sageRedirectPath, false);
            }
        }
        catch (Exception ex)
        {
            ProcessException(ex);
        }
    }
    public string SendPaymentInfoAIM(OrderDetailsCollection OrderDetail, string TemplateName, string addressPath)
    {
        WebClient objRequest = new WebClient();

        System.Collections.Specialized.NameValueCollection objInf = new System.Collections.Specialized.NameValueCollection(30);

        string strError;

        //OrderDetail.ObjOrderDetails.CustomerID = int.Parse(Crypto.GenerateCustomerID());
        OrderDetail.ObjOrderDetails.InvoiceNumber       = Crypto.GenerateInvoiceNumber();
        OrderDetail.ObjOrderDetails.PurchaseOrderNumber = Crypto.GeneratePurchaseOrderNumber();

        //merchant generated field
        objInf.Add("x_version", OrderDetail.ObjOrderDetails.Version);
        objInf.Add("x_delim_data", OrderDetail.ObjOrderDetails.DelimData);
        objInf.Add("x_login", OrderDetail.ObjOrderDetails.APILogin);
        objInf.Add("x_tran_key", OrderDetail.ObjOrderDetails.TransactionKey);
        objInf.Add("x_relay_response", OrderDetail.ObjOrderDetails.RelayResponse);
        objInf.Add("x_delim_char", OrderDetail.ObjOrderDetails.DelimChar);
        objInf.Add("x_encap_char", OrderDetail.ObjOrderDetails.EncapeChar);
        objInf.Add("x_invoice_num", OrderDetail.ObjOrderDetails.InvoiceNumber);
        objInf.Add("x_cust_id", OrderDetail.ObjOrderDetails.CustomerID.ToString());
        objInf.Add("x_po_num", OrderDetail.ObjOrderDetails.PurchaseOrderNumber);
        //for (int i = 0; i < arr; i++)
        //{

        //}

        // Billing Address
        objInf.Add("x_first_name", OrderDetail.ObjBillingAddressInfo.FirstName);
        objInf.Add("x_last_name", OrderDetail.ObjBillingAddressInfo.LastName);
        objInf.Add("x_company", OrderDetail.ObjBillingAddressInfo.CompanyName);
        objInf.Add("x_email", OrderDetail.ObjBillingAddressInfo.EmailAddress);
        objInf.Add("x_address", OrderDetail.ObjBillingAddressInfo.Address);
        objInf.Add("x_city", OrderDetail.ObjBillingAddressInfo.City);
        objInf.Add("x_state", OrderDetail.ObjBillingAddressInfo.State);
        objInf.Add("x_zip", OrderDetail.ObjBillingAddressInfo.Zip);
        objInf.Add("x_country", OrderDetail.ObjBillingAddressInfo.Country);
        objInf.Add("x_phone", OrderDetail.ObjBillingAddressInfo.Phone);
        objInf.Add("x_fax", OrderDetail.ObjBillingAddressInfo.Fax);
        objInf.Add("x_email_customer", OrderDetail.ObjOrderDetails.IsEmailCustomer);

        if (OrderDetail.ObjOrderDetails.IsMultipleCheckOut == false)
        {
            //shipping address
            objInf.Add("x_ship_to_first_name", OrderDetail.ObjShippingAddressInfo.FirstName);
            objInf.Add("x_ship_to_last_name", OrderDetail.ObjShippingAddressInfo.LastName);
            objInf.Add("x_ship_to_company", OrderDetail.ObjShippingAddressInfo.CompanyName);
            objInf.Add("x_ship_to_address", OrderDetail.ObjShippingAddressInfo.Address);
            objInf.Add("x_ship_to_city", OrderDetail.ObjShippingAddressInfo.City);
            objInf.Add("x_ship_to_state", OrderDetail.ObjShippingAddressInfo.State);
            objInf.Add("x_ship_to_zip", OrderDetail.ObjShippingAddressInfo.Zip);
            objInf.Add("x_ship_to_country", OrderDetail.ObjShippingAddressInfo.Country);
        }
        // Card Details
        objInf.Add("x_card_num", OrderDetail.ObjPaymentInfo.CardNumber);
        objInf.Add("x_card_type", OrderDetail.ObjPaymentInfo.CardType);
        objInf.Add("x_exp_date", OrderDetail.ObjPaymentInfo.ExpireDate);
        if (OrderDetail.ObjPaymentInfo.PaymentMethodCode == "CC")
        {
            // Authorization code of the card (CCV)
            objInf.Add("x_card_code", OrderDetail.ObjPaymentInfo.CardCode.ToString());
            objInf.Add("x_method", OrderDetail.ObjPaymentInfo.PaymentMethodCode);
            objInf.Add("x_type", OrderDetail.ObjPaymentInfo.TransactionType);
            string amount = Regex.Replace(OrderDetail.ObjOrderDetails.GrandTotal.ToString("0.00"), @"[A-Z]", String.Empty);
            objInf.Add("x_amount", amount);
            objInf.Add("x_description", OrderDetail.ObjOrderDetails.Remarks);
            objInf.Add("x_test_request", OrderDetail.ObjOrderDetails.IsTest);
        }
        else
        {
            //bank
            objInf.Add("x_bank_aba_code", OrderDetail.ObjPaymentInfo.RoutingNumber);
            objInf.Add("x_bank_acct_num", OrderDetail.ObjPaymentInfo.AccountNumber);
            objInf.Add("x_bank_acct_type", OrderDetail.ObjPaymentInfo.AccountType);
            objInf.Add("x_bank_name", OrderDetail.ObjPaymentInfo.BankName);
            objInf.Add("x_bank_acct_name", OrderDetail.ObjPaymentInfo.AccountHolderName);
            objInf.Add("x_echeck_type", OrderDetail.ObjPaymentInfo.ChequeType);
            objInf.Add("x_bank_check_number", OrderDetail.ObjPaymentInfo.ChequeNumber);
        }

        // Currency setting. Check the guide for other supported currencies
        objInf.Add("x_currency_code", OrderDetail.ObjOrderDetails.CurrencyCode);
        objRequest.BaseAddress = "https://test.authorize.net/gateway/transact.dll";

        try
        {
            // POST request
            byte[]   objRetBytes;
            string[] objRetVals;

            objRetBytes =
                objRequest.UploadValues(objRequest.BaseAddress, "POST", objInf);
            objRetVals =
                System.Text.Encoding.ASCII.GetString(objRetBytes).Split(",".ToCharArray());

            // Process Return Values
            OrderDetail.ObjOrderDetails.ResponseCode       = int.Parse(objRetVals[0].Trim(char.Parse("|")));
            OrderDetail.ObjOrderDetails.ResponseReasonCode = int.Parse(objRetVals[2].Trim(char.Parse("|")));
            if (objRetVals[0].Trim(char.Parse("|")) == "1")
            {
                // Returned Authorisation Code
                //response.AuthorizationCode = objRetVals[4].Trim(char.Parse("|"));
                // Returned Transaction ID
                OrderDetail.ObjOrderDetails.TransactionID = Convert.ToString(objRetVals[6].Trim(char.Parse("|")));
                strError = "Transaction completed successfully.";
                AspxCommerceWebService asws = new AspxCommerceWebService();
                OrderDetail.ObjOrderDetails.OrderStatusID = 8;
                OrderDetail.ObjOrderDetails.TransactionID = Convert.ToString(objRetVals[6].Trim(char.Parse("|")));
                asws.AddOrderDetails(OrderDetail);
                CartManageSQLProvider cms           = new CartManageSQLProvider();
                AspxCommonInfo        aspxCommonObj = new AspxCommonInfo();
                aspxCommonObj.CustomerID  = OrderDetail.ObjOrderDetails.CustomerID;
                aspxCommonObj.SessionCode = OrderDetail.ObjOrderDetails.SessionCode;
                aspxCommonObj.StoreID     = OrderDetail.ObjCommonInfo.StoreID;
                aspxCommonObj.PortalID    = OrderDetail.ObjCommonInfo.PortalID;
                cms.ClearCartAfterPayment(aspxCommonObj);
            }
            else
            {
                // Error!
                strError = objRetVals[3].Trim(char.Parse("|")) + " (" +
                           objRetVals[2].Trim(char.Parse("|")) + ")";

                if (objRetVals[2].Trim(char.Parse("|")) == "44")
                {
                    // CCV transaction decline
                    strError += "Our Card Code Verification (CCV) returned " +
                                "the following error: ";

                    switch (objRetVals[38].Trim(char.Parse("|")))
                    {
                    case "N":
                        strError += "Card Code does not match.";
                        break;

                    case "P":
                        strError += "Card Code was not processed.";
                        break;

                    case "S":
                        strError += "Card Code should be on card but was not indicated.";
                        break;

                    case "U":
                        strError += "Issuer was not certified for Card Code.";
                        break;
                    }
                }

                if (objRetVals[2].Trim(char.Parse("|")) == "45")
                {
                    if (strError.Length > 1)
                    {
                        strError += "<br />n";
                    }

                    // AVS transaction decline
                    strError += "Our Address Verification System (AVS) " +
                                "returned the following error: ";

                    switch (objRetVals[5].Trim(char.Parse("|")))
                    {
                    case "A":
                        strError += " the zip code entered does not match " +
                                    "the billing address.";
                        break;

                    case "B":
                        strError += " no information was provided for the AVS check.";
                        break;

                    case "E":
                        strError += " a general error occurred in the AVS system.";
                        break;

                    case "G":
                        strError += " the credit card was issued by a non-US bank.";
                        break;

                    case "N":
                        strError += " neither the entered street address nor zip " +
                                    "code matches the billing address.";
                        break;

                    case "P":
                        strError += " AVS is not applicable for this transaction.";
                        break;

                    case "R":
                        strError += " please retry the transaction; the AVS system " +
                                    "was unavailable or timed out.";
                        break;

                    case "S":
                        strError += " the AVS service is not supported by your " +
                                    "credit card issuer.";
                        break;

                    case "U":
                        strError += " address information is unavailable for the " +
                                    "credit card.";
                        break;

                    case "W":
                        strError += " the 9 digit zip code matches, but the " +
                                    "street address does not.";
                        break;

                    case "Z":
                        strError += " the zip code matches, but the address does not.";
                        break;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            strError = ex.Message;
        }
        OrderDetail.ObjOrderDetails.ResponseReasonText = strError;
        return(OrderDetail.ObjOrderDetails.ResponseReasonText);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            AspxCommonInfo aspxCommonObj = new AspxCommonInfo();
            aspxCommonObj.StoreID     = GetStoreID;
            aspxCommonObj.PortalID    = GetPortalID;
            aspxCommonObj.UserName    = GetUsername;
            aspxCommonObj.CultureName = GetCurrentCultureName;

            if (!IsPostBack)
            {
                if (Session["OrderID"] != null)
                {
                    orderID = int.Parse(Session["OrderID"].ToString());
                }

                StoreSettingConfig     ssc = new StoreSettingConfig();
                AspxCommerceWebService aws = new AspxCommerceWebService();
                //Store Default Currency
                MainCurrency = ssc.GetStoreSettingsByKey(StoreSetting.MainCurrency, GetPortalID, GetPortalID, GetCurrentCultureName);

                if (Session["CurrencyCode"] != null && Session["CurrencyCode"] != "")
                {
                    SelectedCurrency = Session["CurrencyCode"].ToString();
                }
                else
                {
                    SelectedCurrency = MainCurrency;
                }
                if (Session["Region"] != null && Session["Region"] != "")
                {
                    Region = Session["Region"].ToString();
                }
                else
                {
                    Region = StoreSetting.GetRegionFromCurrencyCode(SelectedCurrency, GetStoreID, GetPortalID);
                }

                //Rate to convert Store Default Item Price to Selcted curency Price
                currencyRate = Convert.ToDecimal(aws.GetCurrencyRateOnChange(aspxCommonObj, MainCurrency, SelectedCurrency, Region));



                var sfConfig = new SageFrameConfig();
                _isUseFriendlyUrls = sfConfig.GetSettingBollByKey(SageFrameSettingKeys.UseFriendlyUrls);
                PageExtension      = SageFrameSettingKeys.PageExtension;
                if (_isUseFriendlyUrls)
                {
                    if (GetPortalID > 1)
                    {
                        _sageRedirectPath = ResolveUrl("~/portal/" + GetPortalSEOName + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + PageExtension);
                        _addressPath      = HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/portal/" + GetPortalSEOName + "/";
                    }
                    else
                    {
                        _sageRedirectPath = ResolveUrl("~/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + PageExtension);
                        _addressPath      = HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/";
                    }
                }
                else
                {
                    _sageRedirectPath = ResolveUrl("{~/Default" + PageExtension + "?ptlid=" + GetPortalID + "&ptSEO=" + GetPortalSEOName + "&pgnm=" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage));
                }

                var imgProgress = (Image)UpdateProgress1.FindControl("imgPrgress");
                if (imgProgress != null)
                {
                    imgProgress.ImageUrl = GetTemplateImageUrl("ajax-loader.gif", true);
                }
                hlnkHomePage.NavigateUrl = _sageRedirectPath;
                SendEmailFrom            = ssc.GetStoreSettingsByKey(StoreSetting.SendEcommerceEmailsFrom, GetStoreID, GetPortalID, GetCurrentCultureName);
                SendOrderNotice          = ssc.GetStoreSettingsByKey(StoreSetting.SendOrderNotification, GetStoreID, GetPortalID, GetCurrentCultureName);

                if (Session["mb_IsCheckoutFromMobile"] != null)
                {
                    MobileSuccess(_sageRedirectPath);
                }
                else
                {
                    SendConfrimMessage(_sageRedirectPath);
                }
            }
            IncludeLanguageJS();
        }
        catch (Exception ex)
        {
            ProcessException(ex);
        }
    }
    protected void SendConfrimMessage(string redirectPat)
    {
        try
        {
            if (Session["OrderID"] != null)
            {
                const int    responseCode       = 1; // response code, defaulted to Invalid
                const string responsereasontext = "Transaction occured successfully";
                const int    responsereasonCode = 1;
                string       paymentmethod      = string.Empty;
                var          orderdata2         = new OrderDetailsCollection();
                if (HttpContext.Current.Session["OrderCollection"] != null)
                {
                    orderdata2 = (OrderDetailsCollection)HttpContext.Current.Session["OrderCollection"];
                }
                string invoice         = orderdata2.ObjOrderDetails.InvoiceNumber;
                var    random          = new Random();
                string purchaseorderNo = (random.Next(0, 1000)).ToString();
                string timeStamp       = ((int)(DateTime.UtcNow - new DateTime(2011, 1, 1)).TotalSeconds).ToString();
                string transID         = (random.Next(99999, 111111)).ToString();
                lblTransaction.Text   = transID;
                lblInvoice.Text       = invoice;
                lblPaymentMethod.Text = "Cash On Delivery";
                lblPaymentStatus.Text = "Successfull";
                lblDateTime.Text      = DateTime.Now.ToString("dddd, dd MMMM yyyy ");
                lblOrderNo.Text       = "#" + Session["OrderID"].ToString();
                AspxCommonInfo aspxCommonObj = new AspxCommonInfo();
                aspxCommonObj.StoreID     = GetStoreID;
                aspxCommonObj.PortalID    = GetPortalID;
                aspxCommonObj.UserName    = GetUsername;
                aspxCommonObj.CustomerID  = GetCustomerID;
                aspxCommonObj.SessionCode = HttpContext.Current.Session.SessionID;
                aspxCommonObj.CultureName = GetCurrentCultureName;
                string result = CashOnDelivery.Parse(transID, invoice, purchaseorderNo, responseCode, responsereasonCode, responsereasontext, aspxCommonObj);
                AspxGiftCardController.IssueGiftCard(orderdata2.LstOrderItemsInfo, false, aspxCommonObj);
                if (orderdata2.GiftCardDetail != null && HttpContext.Current.Session["UsedGiftCard"] != null)
                {
                    AspxGiftCardController.UpdateGiftCardUsage(orderdata2.GiftCardDetail, orderdata2.ObjCommonInfo.StoreID,
                                                               orderdata2.ObjCommonInfo.PortalID, orderdata2.ObjOrderDetails.OrderID, orderdata2.ObjCommonInfo.AddedBy,
                                                               orderdata2.ObjCommonInfo.CultureName);
                    HttpContext.Current.Session.Remove("UsedGiftCard");
                }

                lblerror.Text = result;
                lblerror.Text = GetSageMessage("Payment", "PaymentProcessed");
                var tinfo = new TransactionLogInfo();
                var tlog  = new TransactionLog();

                tinfo.TransactionID = transID;
                tinfo.AuthCode      = "";
                // tinfo.TotalAmount = decimal.Parse(orderdata2.ObjOrderDetails.GrandTotal.ToString());
                tinfo.TotalAmount        = decimal.Parse(Session["GrandTotalAll"].ToString()) * currencyRate;
                tinfo.ResponseCode       = responseCode.ToString();
                tinfo.ResponseReasonText = responsereasontext;
                tinfo.OrderID            = orderdata2.ObjOrderDetails.OrderID;
                tinfo.StoreID            = orderdata2.ObjCommonInfo.StoreID;
                tinfo.PortalID           = orderdata2.ObjCommonInfo.PortalID;
                tinfo.AddedBy            = orderdata2.ObjCommonInfo.AddedBy;
                tinfo.CustomerID         = orderdata2.ObjOrderDetails.CustomerID;
                tinfo.SessionCode        = orderdata2.ObjOrderDetails.SessionCode;
                tinfo.PaymentGatewayID   = orderdata2.ObjOrderDetails.PaymentGatewayTypeID;
                tinfo.PaymentStatus      = "Processed";
                tinfo.CreditCard         = "";
                tinfo.CurrencyCode       = SelectedCurrency;
                tlog.SaveTransactionLog(tinfo);

                var clSes = new AspxCommerceWebService();
                if (Session["IsFreeShipping"] != null)
                {
                    HttpContext.Current.Session.Remove("IsFreeShipping");
                }
                if (Session["DiscountAmount"] != null)
                {
                    HttpContext.Current.Session.Remove("DiscountAmount");
                }
                if (Session["CouponDiscountAmount"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponDiscountAmount");
                }
                if (Session["IsCouponInPercent"] != null)
                {
                    HttpContext.Current.Session.Remove("IsCouponInPercent");
                }
                if (Session["CouponPercentValue"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponPercentValue");
                }
                if (Session["CouponSessionPercentAmount"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponSessionPercentAmount");
                }
                if (Session["CouponSessionAmount"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponSessionAmount");
                }
                if (Session["CouponCode"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponCode");
                }
                if (Session["CouponApplied"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponApplied");
                }
                if (Session["DiscountAll"] != null)
                {
                    HttpContext.Current.Session.Remove("DiscountAll");
                }
                if (Session["TaxAll"] != null)
                {
                    HttpContext.Current.Session.Remove("TaxAll");
                }
                if (Session["ShippingCostAll"] != null)
                {
                    HttpContext.Current.Session.Remove("ShippingCostAll");
                }
                if (Session["GrandTotalAll"] != null)
                {
                    HttpContext.Current.Session.Remove("GrandTotalAll");
                }
                if (Session["Gateway"] != null)
                {
                    HttpContext.Current.Session.Remove("Gateway");
                }

                //invoice  transID

                if (Session["OrderCollection"] != null)
                {
                    var orderdata = (OrderDetailsCollection)Session["OrderCollection"];
                    try
                    {
                        orderdata.ObjOrderDetails.OrderStatus = "Processed";
                        EmailTemplate.SendEmailForOrder(GetPortalID, orderdata, _addressPath, TemplateName, transID);
                    }
                    catch (Exception ex)
                    {
                        lblerror.Text = "";
                        lblerror.Text = GetSageMessage("Payment", "EmailSendOrderProblem");
                        ProcessException(ex);
                    }
                    clSes.ClearSessionVariable("OrderCollection");
                }
            }
            else
            {
                Response.Redirect(_sageRedirectPath, false);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
示例#14
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            try
            {
                SageFrameConfig sfConfig = new SageFrameConfig();
                IsUseFriendlyUrls = sfConfig.GetSettingBollByKey(SageFrameSettingKeys.UseFriendlyUrls);
                string sageRedirectPath = string.Empty;
                if (IsUseFriendlyUrls)
                {
                    if (GetPortalID > 1)
                    {
                        sageRedirectPath = ResolveUrl("~/portal/" + GetPortalSEOName + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + ".aspx");
                        addressPath      = HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/portal/" + GetPortalSEOName + "/";
                    }
                    else
                    {
                        sageRedirectPath = ResolveUrl("~/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + ".aspx");
                        addressPath      = HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/";
                    }
                }
                else
                {
                    sageRedirectPath = ResolveUrl("{~/Default.aspx?ptlid=" + GetPortalID + "&ptSEO=" + GetPortalSEOName + "&pgnm=" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage));
                }

                Image imgProgress = (Image)UpdateProgress1.FindControl("imgPrgress");
                if (imgProgress != null)
                {
                    imgProgress.ImageUrl = GetTemplateImageUrl("ajax-loader.gif", true);
                }
                hlnkHomePage.NavigateUrl = sageRedirectPath;

                if (Session["OrderID"] != null)
                {
                    int    storeID    = int.Parse(GetStoreID.ToString());
                    int    portalID   = int.Parse(GetPortalID.ToString());
                    string userName   = GetUsername.ToString();
                    int    customerID = int.Parse(GetCustomerID.ToString());
                    OrderDetailsCollection   orderdata = new OrderDetailsCollection();
                    List <PayPalSettingInfo> setting;
                    if (HttpContext.Current.Session["OrderCollection"] != null)
                    {
                        orderdata = (OrderDetailsCollection)HttpContext.Current.Session["OrderCollection"];
                        invoice   = orderdata.ObjOrderDetails.InvoiceNumber.ToString();
                        PayPalWCFService pw = new PayPalWCFService();
                        int i = int.Parse(orderdata.ObjOrderDetails.PaymentGatewayTypeID.ToString());
                        setting   = pw.GetAllPayPalSetting(i, storeID, portalID);
                        authToken = setting[0].AuthToken.ToString();
                    }

                    // authToken = "QMtOC54_YHYUkoggkMZ81ivNWSxPXduIqS5oMynafeUGRL1Rv5OTtUd4rvq";

                    //read in txn token from querystring
                    txToken = Request.QueryString.Get("tx");
                    query   = string.Format("cmd=_notify-synch&tx={0}&at={1}", txToken, authToken);
                    // Create the request back
                    // string url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
                    string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
                    string strLive    = "https://www.paypal.com/cgi-bin/webscr";
                    string test       = string.Empty;
                    if (Session["IsTestPayPal"] != null)
                    {
                        if (bool.Parse(Session["IsTestPayPal"].ToString()))
                        {
                            test = strSandbox;
                        }
                        else
                        {
                            test = strLive;
                        }
                    }
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(test);

                    // Set values for the request back
                    req.Method        = "POST";
                    req.ContentType   = "application/x-www-form-urlencoded";
                    req.ContentLength = query.Length;

                    // Write the request back IPN strings
                    StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
                    stOut.Write(query);
                    stOut.Close();

                    // Do the request to PayPal and get the response
                    StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
                    strResponse = stIn.ReadToEnd();
                    stIn.Close();

                    // If response was SUCCESS, parse response string and output details
                    if (strResponse.StartsWith("SUCCESS"))
                    {
                        string sessionCode = HttpContext.Current.Session.SessionID.ToString();
                        //for localhost
                        // PayPalHandler pdt = PayPalHandler.Parse(strResponse, storeID, portalID, userName, customerID, sessionCode);
                        //for live site
                        try
                        {
                            PayPalHandler pdtt = PayPalHandler.ParseAfterIPN(strResponse, storeID, portalID, userName, customerID, sessionCode, TemplateName, addressPath);
                        }
                        catch (Exception)
                        {
                            lblerror.Text = GetSageMessage("Payment", "PaymentParsingIPNError");
                        }
                        AspxCommerceWebService clSes = new AspxCommerceWebService();

                        String   sKey, sValue;
                        String[] StringArray = strResponse.Split('\n');
                        int      i;
                        string   status = string.Empty;
                        for (i = 1; i < StringArray.Length - 1; i++)
                        {
                            String[] StringArray1 = StringArray[i].Split('=');

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

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

                            case "payment_status":
                                status = Convert.ToString(sValue);
                                break;
                            }
                        }

                        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");
                        }

                        if (Session["IsFreeShipping"] != null)
                        {
                            clSes.ClearSessionVariable("IsFreeShipping");
                        }
                        if (Session["DiscountAmount"] != null)
                        {
                            clSes.ClearSessionVariable("DiscountAmount");
                        }
                        if (Session["CouponCode"] != null)
                        {
                            clSes.ClearSessionVariable("CouponCode");
                        }
                        if (Session["CouponApplied"] != null)
                        {
                            HttpContext.Current.Session.Remove("CouponApplied");
                        }
                        Session.Remove("IsTestPayPal");
                        if (Session["DiscountAll"] != null)
                        {
                            HttpContext.Current.Session.Remove("DiscountAll");
                        }
                        if (Session["TaxAll"] != null)
                        {
                            HttpContext.Current.Session.Remove("TaxAll");
                        }
                        if (Session["ShippingCostAll"] != null)
                        {
                            HttpContext.Current.Session.Remove("ShippingCostAll");
                        }
                        if (Session["GrandTotalAll"] != null)
                        {
                            HttpContext.Current.Session.Remove("GrandTotalAll");
                        }
                        if (Session["Gateway"] != null)
                        {
                            HttpContext.Current.Session.Remove("Gateway");
                        }
                    }
                    else
                    {
                        lblerror.Text = GetSageMessage("Payment", "PaymentError");
                    }
                }
                else
                {
                    Response.Redirect(sageRedirectPath, false);
                }
            }
            catch (Exception ex)
            {
                ProcessException(ex);
            }
        }
    }
    protected void SendConfrimMessage()
    {
        try
        {
            if (Session["OrderID"] != null)
            {
                if (Session["TransDetailsAIM"] != null)
                {
                    string   transID = GetTransactionDetailById(int.Parse(Session["OrderID"].ToString()));
                    string[] details = Session["TransDetailsAIM"].ToString().Split('#');
                    lblTransaction.Text   = transID;
                    lblInvoice.Text       = details[0];
                    lblOrderNo.Text       = "#" + Session["OrderID"].ToString();
                    lblPaymentMethod.Text = details[2];
                    lblDateTime.Text      = DateTime.Now.ToString("dddd, dd MMMM yyyy ");
                    lblerror.Text         = GetSageMessage("Payment", "PaymentProcessed");

                    var clSes = new AspxCommerceWebService();
                    clSes.ClearSessionVariable("OrderCollection");
                    HttpContext.Current.Session.Remove("TransDetailsAIM");
                }
                HttpContext.Current.Session.Remove("OrderID");
                if (Session["IsFreeShipping"] != null)
                {
                    HttpContext.Current.Session.Remove("IsFreeShipping");
                }
                if (Session["DiscountAmount"] != null)
                {
                    HttpContext.Current.Session.Remove("DiscountAmount");
                }
                if (Session["IsCouponInPercent"] != null)
                {
                    HttpContext.Current.Session.Remove("IsCouponInPercent");
                }
                if (Session["CouponPercentValue"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponPercentValue");
                }
                if (Session["CouponSessionPercentAmount"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponSessionPercentAmount");
                }
                if (Session["CouponSessionAmount"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponSessionAmount");
                }
                if (Session["CouponCode"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponCode");
                }
                if (Session["CouponApplied"] != null)
                {
                    HttpContext.Current.Session.Remove("CouponApplied");
                }
                if (Session["DiscountAll"] != null)
                {
                    HttpContext.Current.Session.Remove("DiscountAll");
                }
                if (Session["TaxAll"] != null)
                {
                    HttpContext.Current.Session.Remove("TaxAll");
                }
                if (Session["ShippingCostAll"] != null)
                {
                    HttpContext.Current.Session.Remove("ShippingCostAll");
                }
                if (Session["GrandTotalAll"] != null)
                {
                    HttpContext.Current.Session.Remove("GrandTotalAll");
                }
                if (Session["Gateway"] != null)
                {
                    HttpContext.Current.Session.Remove("Gateway");
                }
            }
            else
            {
                Response.Redirect(_sageRedirectPath, false);
            }
        }
        catch (Exception ex)
        {
            ProcessException(ex);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            try
            {
                SageFrameConfig sfConfig = new SageFrameConfig();
                IsUseFriendlyUrls = sfConfig.GetSettingBollByKey(SageFrameSettingKeys.UseFriendlyUrls);
                string sageRedirectPath = string.Empty;
                if (IsUseFriendlyUrls)
                {
                    if (GetPortalID > 1)
                    {
                        sageRedirectPath = ResolveUrl("~/portal/" + GetPortalSEOName + "/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + ".aspx");
                        addressPath = HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/portal/" + GetPortalSEOName + "/";
                    }
                    else
                    {
                        sageRedirectPath = ResolveUrl("~/" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage) + ".aspx");
                        addressPath = HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/";
                    }
                }
                else
                {
                    sageRedirectPath = ResolveUrl("{~/Default.aspx?ptlid=" + GetPortalID + "&ptSEO=" + GetPortalSEOName + "&pgnm=" + sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage));
                }

                Image imgProgress = (Image)UpdateProgress1.FindControl("imgPrgress");
                if (imgProgress != null)
                {
                    imgProgress.ImageUrl = GetTemplateImageUrl("ajax-loader.gif", true);
                }
                hlnkHomePage.NavigateUrl = sageRedirectPath;

                if (Session["OrderID"] != null)
                {
                    int storeID = int.Parse(GetStoreID.ToString());
                    int portalID = int.Parse(GetPortalID.ToString());
                    string userName = GetUsername.ToString();
                    int customerID = int.Parse(GetCustomerID.ToString());
                    OrderDetailsCollection orderdata = new OrderDetailsCollection();
                    List<PayPalSettingInfo> setting;
                    if (HttpContext.Current.Session["OrderCollection"] != null)
                    {

                        orderdata = (OrderDetailsCollection)HttpContext.Current.Session["OrderCollection"];
                        invoice = orderdata.ObjOrderDetails.InvoiceNumber.ToString();
                        PayPalWCFService pw = new PayPalWCFService();
                        int i = int.Parse(orderdata.ObjOrderDetails.PaymentGatewayTypeID.ToString());
                        setting = pw.GetAllPayPalSetting(i, storeID, portalID);
                        authToken = setting[0].AuthToken.ToString();
                    }

                    // authToken = "QMtOC54_YHYUkoggkMZ81ivNWSxPXduIqS5oMynafeUGRL1Rv5OTtUd4rvq";

                    //read in txn token from querystring
                    txToken = Request.QueryString.Get("tx");
                    query = string.Format("cmd=_notify-synch&tx={0}&at={1}", txToken, authToken);
                    // Create the request back
                    // string url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
                    string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
                    string strLive = "https://www.paypal.com/cgi-bin/webscr";
                    string test = string.Empty;
                    if (Session["IsTestPayPal"] != null)
                    {

                        if (bool.Parse(Session["IsTestPayPal"].ToString()))
                        {
                            test = strSandbox;
                        }
                        else
                        {
                            test = strLive;
                        }
                    }
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(test);

                    // Set values for the request back
                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.ContentLength = query.Length;

                    // Write the request back IPN strings
                    StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
                    stOut.Write(query);
                    stOut.Close();

                    // Do the request to PayPal and get the response
                    StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
                    strResponse = stIn.ReadToEnd();
                    stIn.Close();

                    // If response was SUCCESS, parse response string and output details
                    if (strResponse.StartsWith("SUCCESS"))
                    {
                        string sessionCode = HttpContext.Current.Session.SessionID.ToString();
                        //for localhost
                       // PayPalHandler pdt = PayPalHandler.Parse(strResponse, storeID, portalID, userName, customerID, sessionCode);
                        //for live site
                        try
                        {
                            PayPalHandler pdtt = PayPalHandler.ParseAfterIPN(strResponse, storeID, portalID, userName, customerID, sessionCode, TemplateName, addressPath);

                        }
                        catch (Exception)
                        {
                            lblerror.Text = GetSageMessage("Payment", "PaymentParsingIPNError");                           
                        } 
                        AspxCommerceWebService clSes = new AspxCommerceWebService();

                        String sKey, sValue;
                        String[] StringArray = strResponse.Split('\n');
                        int i;
                        string status = string.Empty;
                        for (i = 1; i < StringArray.Length - 1; i++)
                        {
                            String[] StringArray1 = StringArray[i].Split('=');

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

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

                            }
                        }

                        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");  
                        }

                        if (Session["IsFreeShipping"] != null)
                        {
                            clSes.ClearSessionVariable("IsFreeShipping");

                        }
                        if (Session["DiscountAmount"] != null)
                        {
                            clSes.ClearSessionVariable("DiscountAmount");

                        }
                        if (Session["CouponCode"] != null)
                        {
                            clSes.ClearSessionVariable("CouponCode");

                        }
                        if (Session["CouponApplied"] != null)
                        {
                            HttpContext.Current.Session.Remove("CouponApplied");
                        }
                        Session.Remove("IsTestPayPal");
                        if (Session["DiscountAll"] != null)
                        {
                            HttpContext.Current.Session.Remove("DiscountAll");
                        }
                        if (Session["TaxAll"] != null)
                        {
                            HttpContext.Current.Session.Remove("TaxAll");
                        }
                        if (Session["ShippingCostAll"] != null)
                        {
                            HttpContext.Current.Session.Remove("ShippingCostAll");
                        }
                        if (Session["GrandTotalAll"] != null)
                        {
                            HttpContext.Current.Session.Remove("GrandTotalAll");
                        }
                        if (Session["Gateway"] != null)
                        {
                            HttpContext.Current.Session.Remove("Gateway");
                        }
                    }
                    else
                    {

                        lblerror.Text = GetSageMessage("Payment", "PaymentError");
                    }
                }
                else
                {
                    Response.Redirect(sageRedirectPath, false);
                }
            }
            catch (Exception ex)
            {

                ProcessException(ex);
            }
        }
    }