/// <summary>
        /// Build NVP response into a readable HTML response
        /// </summary>
        /// <param name="response"></param>
        /// <param name="header1"></param>
        /// <param name="header2"></param>
        /// <returns></returns>
        public static string BuildResponse(object response, string header1, string header2)
        {
            if (response != null)
            {
                NVPHelper decoder = new NVPHelper();
                decoder = (NVPHelper)response;

                string res = "<center>";
                if (header1 != null)
                    res = res + "<font size=4 color=black face=Verdana><b>" + header1 + "</b></font>";
                res = res + "<br>";
                res = res + "<br>";

                if (header2 != null)
                    res = res + "<b>" + header2 + "</b><br>";

                res = res + "<br>";

                res = res + "<table width=650 class=api>";

                for (int i = 0; i < decoder.Keys.Count; i++)
                {
                    res = res + "<tr><td align=left> " + decoder.Keys[i].ToString() + ":</td>";
                    res = res + "<td align=left>" + decoder.GetValues(i)[0] + "</td>";
                    res = res + "</tr>";
                    res = res + "<tr>";
                }

                res = res + "</table>";
                res = res + "</center>";
                return res;
            }
            else
            {
                return "Requested action not allowed";
            }
        }
        public string VerifyPaypalEmail(string email, string firstName, string lastName)
        {
            string returnResponse = "false";

            try
            {
                ISettingManager settingManager = IoC.Resolve<ISettingManager>();
                bool useSandbox = settingManager.GetSettingValueBoolean("PaymentMethod.PaypalAdaptive.UseSandbox");
                string sandboxEndpoint = settingManager.GetSettingValue("Paypal.AdaptiveAccounts.Sandbox.Endpoint");
                string productionEndpoint = settingManager.GetSettingValue("Paypal.AdaptiveAccounts.Production.Endpoint");
                string aa_endpoint = useSandbox ? sandboxEndpoint : productionEndpoint;
                string endpoint = aa_endpoint + "GetVerifiedStatus";
                System.Collections.Hashtable headers = new System.Collections.Hashtable();

                headers = settingManager.GetSettingValueBoolean("PaymentMethod.PaypalAdaptive.UseSandbox") ? Constants_Common.sandboxHeaders() : Constants_Common.productionHeaders();

                NVPHelper NVPRequest = new NVPHelper();
                //requestEnvelope.errorLanguage is common for all the request
                NVPRequest[NVPConstant.requestEnvelopeerrorLanguage] = "en_US";
                NVPRequest[NVPConstant.GetVerifiedStatus.emailAddress] = email;
                NVPRequest[NVPConstant.GetVerifiedStatus.matchCriteria] = "NAME";

                NVPRequest[NVPConstant.GetVerifiedStatus.firstName] = firstName;
                NVPRequest[NVPConstant.GetVerifiedStatus.lastName] = lastName;

                string strrequestforNvp = NVPRequest.Encode();

                IoC.Resolve<ILogService>().InsertLog(LogTypeEnum.Unknown, "pre-call", "Adaptive Accounts");
                //calling Call method where actuall API call is made, NVP string, header value adne end point are passed as the input.
                CallerServices_NVP CallerServices = new CallerServices_NVP();
                string stresponsenvp = CallerServices.Call(strrequestforNvp, headers, endpoint);
                IoC.Resolve<ILogService>().InsertLog(LogTypeEnum.Unknown, stresponsenvp, "Adaptive Accounts");

                //Response is send to Decoder method where it is decoded to readable hash table
                NVPHelper decoder = new NVPHelper();
                decoder.Decode(stresponsenvp);

                if (decoder["responseEnvelope.ack"] != "Failure")
                {
                    //account exists, may or may not be verified.
                    //add code later to addres this issue.
                    //if (decoder["accountStatus"] == "VERIFIED") { }
                    //if (decoder["accountStatus"] == "UNVERIFIED") { }
                    IoC.Resolve<ILogService>().InsertLog(LogTypeEnum.Unknown, stresponsenvp, "Adaptive Accounts");
                    returnResponse = "true";
                }
                else
                {
                    IoC.Resolve<ILogService>().InsertLog(LogTypeEnum.Unknown, stresponsenvp, "Adaptive Accounts");
                    returnResponse = "false";
                }

            }
            catch (FATALException fx)
            {
                //NVPHelper decoder = new NVPHelper();
                //decoder.Add("fx.FATALExceptionMessage", fx.FATALExceptionMessage);
                //decoder.Add("fx.FATALExceptionLongMessage", fx.FATALExceptionLongMessage);
                //string printerror = Utils.BuildResponse(decoder, "SDK Error Page", "");
                //Session["AllResponse"] = printerror;
                //Response.Redirect("../Public/allResponse.aspx");
                IoC.Resolve<ILogService>().InsertLog(LogTypeEnum.Unknown, fx.Message, fx);
                returnResponse = "false";
            }
            catch (Exception ex)
            {
                IoC.Resolve<ILogService>().InsertLog(LogTypeEnum.Unknown, ex.Message, ex);
                returnResponse = "false";
            }

            return returnResponse;
        }
        /// <summary>
        /// Post process payment (payment gateways that require redirecting)
        /// </summary>
        /// <param name="order">Order</param>
        /// <returns>The error status, or String.Empty if no errors</returns>
        public string PostProcessPayment(Order order)
        {
            try
            {
                InitSettings();

                string vendorEmail = order.OrderProductVariants[0].NpProductVariant.Vendor.PaypalEmailAddress;

                string endpoint = PaypalEndpoint + "Pay";
                NVPHelper NVPRequest = new NVPHelper();
                //requestEnvelope.errorLanguage is common for all the request
                NVPRequest[NVPConstant.requestEnvelopeerrorLanguage] = "en_US";

                NVPRequest[NVPConstant.Pay.actionType] = "PAY";
                NVPRequest[NVPConstant.Pay.currencyCode] = "USD";
                NVPRequest[NVPConstant.Pay.feesPayer] = "EACHRECEIVER";
                NVPRequest[NVPConstant.Pay.memo] = "Order reference number: " + order.OrderGuid;
                NVPRequest[NVPConstant.Pay.receiverListreceiveramount_0] = order.OrderTotal.ToString();
                NVPRequest[NVPConstant.Pay.receiverListreceiveremail_0] = vendorEmail;
                NVPRequest[NVPConstant.Pay.receiverListreceiverprimary_0] = "false";
                //do not pass this.  It is not necessary to complete payment and
                //may not actually be the customers paypal account.
                //NVPRequest[NVPConstant.Pay.senderEmail] = order.Customer.Email;
                NVPRequest[NVPConstant.Pay.trackingId] = order.OrderGuid.ToString();

                NVPRequest[NVPConstant.Pay.cancelUrl] = cancelURL;
                NVPRequest[NVPConstant.Pay.returnUrl] = returnURL;
                NVPRequest[NVPConstant.Pay.ipnUrl] = ipnURL;

                //
                //Needed for pre approval.  Not doing pre approvals at the moment.
                //
                //if (txtPreapprovalkey.Text.Trim() != "")
                //{
                //    NVPRequest[NVPConstant.Pay.preapprovalKey] = txtPreapprovalkey.Text;
                //}

                string strrequestforNvp = NVPRequest.Encode();
                //calling Call method where actuall API call is made, NVP string, header value and end point are passed as the input.
                CallerServices_NVP CallerServices = new CallerServices_NVP();
                string stresponsenvp = CallerServices.Call(strrequestforNvp, headers(), endpoint);

                //Response is send to Decoder method where it is decoded to readable hash table
                NVPHelper decoder = new NVPHelper();
                decoder.Decode(stresponsenvp);

                //Response obtained after the API call is stored in print string to display all the response
                //string print = Utils.BuildResponse(decoder, "Pay", "");
                ////Storing response string in session
                HttpContext.Current.Session["PaypalAPResponse"] = decoder; //
                ////COMPLETED, CREATED, Success

                string redirectURL = string.Empty;

                //this is a complete success, ready to allow the user to redirect and pay.
                if (decoder != null && decoder["responseEnvelope.ack"].Equals("Success") && NVPRequest[NVPConstant.Pay.actionType] == "PAY" && decoder["paymentExecStatus"].Equals("CREATED"))
                {
                    if (UseLightBox) {
                        //HttpContext.Current.Session["PayRedirect"] = redirectURLStarter + "paykey=" + decoder["payKey"];
                        HttpContext.Current.Session["PayRedirect"] = PaypalLightboxURL + "expType=light&paykey=" + decoder["payKey"];
                        redirectURL = PaypalLightboxURL + "expType=light&paykey=" + decoder["payKey"];
                    }
                    else {
                        HttpContext.Current.Session["PayRedirect"] = PaypalRedirectURL + "cmd=_ap-payment&paykey=" + decoder["payKey"];
                        //redirectURL = PaypalRedirectURL + "cmd=_ap-payment&paykey=" + decoder["payKey"];
                    }
                }
                //this is assuming we did a preapproval. this will execute the payment and charge the user.
                else if (decoder != null && decoder["responseEnvelope.ack"].Equals("Success") && (String.Empty != "") && NVPRequest[NVPConstant.Pay.actionType] == "CREATE" && decoder["paymentExecStatus"].Equals("CREATED"))
                {
                    HttpContext.Current.Session["PayRedirect"] = PaypalRedirectURL + "cmd=_ap-payment&paykey=" + decoder["payKey"];

                    redirectURL = PaypalRedirectURL + "cmd=_ap-payment&paykey=" + decoder["payKey"];

                    HttpContext.Current.Session["setPayKey"] = decoder["payKey"];
                    HttpContext.Current.Session["executePayKey"] = decoder["payKey"];
                }
                //this assumes that if we executed a payment using above preapproval this would be our return message.
                else if (decoder != null && decoder["responseEnvelope.ack"].Equals("Success") && NVPRequest[NVPConstant.Pay.actionType] == "CREATE" && decoder["paymentExecStatus"].Equals("CREATED"))
                {
                    string senderApiEmail = "admin_1320635048_biz_api1.sewbie.com";
                    string senderEmail = NVPRequest[NVPConstant.Pay.senderEmail];
                    string senderTruncatedEmail = senderEmail.Substring(0, senderEmail.IndexOf("@"));
                    string senderApiTruncatedEmail = senderApiEmail.Substring(0, senderApiEmail.IndexOf("_api"));
                    if (senderTruncatedEmail == senderApiTruncatedEmail)
                    {
                        HttpContext.Current.Session["PayRedirect"] = PaypalRedirectURL+ "cmd=_ap-payment&paykey=" + decoder["payKey"];
                        redirectURL = PaypalRedirectURL + "cmd=_ap-payment&paykey=" + decoder["payKey"];
                        HttpContext.Current.Session["setPayKey"] = decoder["payKey"];
                        HttpContext.Current.Session["executePayKey"] = decoder["payKey"];
                    }
                    else
                    {
                        HttpContext.Current.Session["PayRedirect"] = PaypalRedirectURL + "cmd=_ap-payment&paykey=" + decoder["payKey"];
                        redirectURL = PaypalRedirectURL + "cmd=_ap-payment&paykey=" + decoder["payKey"];
                    }
                } //if it's not a success of any type, check if it's a success with warning otherwise process the error.
                else if (decoder != null &&
                            (!decoder["responseEnvolope.ack"].Equals("Success") ||
                                !decoder["responseEnvolope.ack"].Equals("SuccessWithWarning")))
                {
                    //paypal has not approved the request.  Do we need to undo everything to this point and set the customer straight?
                    //order has been processed.  Cannot cancel.
                    HttpContext.Current.Response.Redirect(CommonHelper.GetStoreLocation(false) + "PaypalAPPaymentRequestFailure.aspx");
                    //logService.InsertLog(LogTypeEnum.OrderError, decoder[""].ToString(), "error logging");
                }

                if (UseLightBox)
                {
                    return redirectURL;
                }
                else
                {
                    //According to paypal redirects need to be performed via javascript.
                    //At this point we redirect to our redirector page, redirects from server will fail.
                    HttpContext.Current.Response.Redirect(CommonHelper.GetStoreLocation(false) + "PaypalAPRedirect.aspx");
                    return String.Empty;
                }
            }
            catch (FATALException fx)
            {
                NVPHelper decoder = new NVPHelper();
                decoder.Add("fx.FATALExceptionMessage", fx.FATALExceptionMessage);
                decoder.Add("fx.FATALExceptionLongMessage", fx.FATALExceptionLongMessage);
                string printerror = Utils.BuildResponse(decoder, "SDK Error Page", "");

                //logService.InsertLog(LogTypeEnum.CommonError, "Post Process FATAL Exception" + printerror, "logging");
            }
            return string.Empty;
        }