/**
         * Permite inicializar una transacción en Webpay. Como respuesta a la invocación se genera un token que representa en forma única una transacción.
         *
         * */
        public wsInitTransactionOutput initTransaction(decimal amount, string buyOrder, string sessionId, string urlReturn, string urlFinal)
        {
            wsInitTransactionInput initTransaction = new wsInitTransactionInput();

            /** Indica el tipo de transacción, su valor debe ser siempre TR_NORMAL_WS */
            initTransaction.wSTransactionType = wsTransactionType.TR_NORMAL_WS;

            initTransaction.buyOrder  = buyOrder;
            initTransaction.sessionId = sessionId;
            initTransaction.returnURL = urlReturn;
            initTransaction.finalURL  = urlFinal;

            wsTransactionDetail details = new wsTransactionDetail();

            details.commerceCode = this.config.CommerceCode;;
            details.buyOrder     = buyOrder;
            details.amount       = amount;

            wsTransactionDetail[] wsTransactionDetail = new wsTransactionDetail[] { details };

            initTransaction.transactionDetails = wsTransactionDetail;

            using (WSWebpayServiceImplService proxy = new WSWebpayServiceImplService())
            {
                PrepareProxy(proxy);
                wsInitTransactionOutput wsInitTransactionOutput = proxy.initTransaction(initTransaction);
                return(wsInitTransactionOutput);
            }
        }
        /**
         * Permite inicializar una transacción en Webpay.
         * Como respuesta a la invocación se genera un token que representa en forma única una transacción.
         * */
        public wsInitTransactionOutput initTransaction(string buyOrder, string sessionId, string urlReturn, string urlFinal, Dictionary <string, string[]> stores)
        {
            wsInitTransactionInput initTransaction = new wsInitTransactionInput();

            /** Indica el tipo de transacción, su valor debe ser siempre TR_MALL_WS */
            initTransaction.wSTransactionType = wsTransactionType.TR_MALL_WS;

            initTransaction.buyOrder  = buyOrder;
            initTransaction.sessionId = sessionId;

            initTransaction.returnURL  = urlReturn;
            initTransaction.finalURL   = urlFinal;
            initTransaction.commerceId = this.config.CommerceCode;

            wsTransactionDetail[] details = new wsTransactionDetail[100]; //Como ejemplo se agregan dos detalles de comercios

            int counter = 0;

            foreach (KeyValuePair <string, string[]> entry in stores)
            {
                details[counter] = new wsTransactionDetail
                {
                    commerceCode = entry.Value[0],
                    amount       = System.Convert.ToDecimal(entry.Value[1]),
                    buyOrder     = entry.Value[2],
                };

                counter++;
            }

            wsTransactionDetail[] wsTransactionDetail = new wsTransactionDetail[1];
            wsTransactionDetail = details;

            initTransaction.transactionDetails = wsTransactionDetail;

            using (WSWebpayServiceImplService proxy = new WSWebpayServiceImplService())
            {
                /*Define el ENDPOINT del Web Service Webpay*/
                proxy.Url = WSDL;

                Policy myPolicy = new Policy();
                myPolicy.Assertions.Add(new CustomPolicyAssertion(this.config));

                proxy.SetPolicy(myPolicy);
                proxy.Timeout = 60000;
                proxy.UseDefaultCredentials = false;

                wsInitTransactionOutput wsInitTransactionOutput = proxy.initTransaction(initTransaction);
                return(wsInitTransactionOutput);
            }
        }
        /// <summary>
        /// Método principal
        /// </summary>
        /// <returns></returns>
        public wsInitTransactionOutput Pagar()
        {
            wsInitTransactionOutput resultado = null;

            try
            {
                var transaccion = new Transaccion
                {
                    Amount    = 10,
                    BuyOrder  = new Random().Next(100000, 999999999).ToString(),
                    SessionId = "19090000",
                    UrlReturn = @"http://*****:*****@"http://localhost:63065/WebForm1.aspx",
                };

                string baseurl   = string.Empty;
                string seguridad = "http://";
                baseurl = string.Format("{0}{1}", seguridad, HttpContext.Current.Request.ServerVariables["HTTP_HOST"].ToString());
                string pathBase = HttpContext.Current.Server.MapPath(".");

                Configuration ConfiguracionWebPay = new Configuration
                {
                    Environment  = "PRODUCCION",
                    CommerceCode = "597033290136",
                    PublicCert   = string.Format("{0}{1}", pathBase, @"\Models\certificados\597033290136\serverTBK.pem"),
                    WebpayCert   = string.Format("{0}{1}", pathBase, @"\Models\certificados\597033290136\597033290136.pfx"),
                    Password     = "******",
                    StoreCodes   = null
                };

                WebPay = new Webpay.Transbank.Library.Webpay(ConfiguracionWebPay);

                resultado = WebPay.getNormalTransaction().initTransaction(transaccion.Amount, transaccion.BuyOrder, transaccion.SessionId, transaccion.UrlReturn, transaccion.UrlFinal);

                return(resultado);
            }
            catch (Exception ex)
            {
                Logger.Write(System.Diagnostics.TraceLevel.Error, "ERROR", ex.StackTrace);

                string error = ex.Message;

                return(resultado);
            }
        }
示例#4
0
        /**
         * Permite inicializar una transacción en Webpay. Como respuesta a la invocación se genera un token que representa en forma única una transacción.
         *
         * */
        public wsInitTransactionOutput initTransaction(decimal amount, string buyOrder, string sessionId, string urlReturn, string urlFinal)
        {
            wsInitTransactionInput initTransaction = new wsInitTransactionInput();

            /** Indica el tipo de transacción, su valor debe ser siempre TR_NORMAL_WS */
            initTransaction.wSTransactionType = wsTransactionType.TR_NORMAL_WS;

            initTransaction.buyOrder  = buyOrder;
            initTransaction.sessionId = sessionId;
            initTransaction.returnURL = urlReturn;
            initTransaction.finalURL  = urlFinal;

            wsTransactionDetail details = new wsTransactionDetail();

            details.commerceCode = this.config.CommerceCode;;
            details.buyOrder     = buyOrder;
            details.amount       = amount;

            wsTransactionDetail[] wsTransactionDetail = new wsTransactionDetail[] { details };

            initTransaction.transactionDetails = wsTransactionDetail;

            using (WSWebpayServiceImplService proxy = new WSWebpayServiceImplService())
            {
                /*Define el ENDPOINT del Web Service Webpay*/
                proxy.Url = WSDL;

                Policy myPolicy = new Policy();
                myPolicy.Assertions.Add(new CustomPolicyAssertion(this.config));

                proxy.SetPolicy(myPolicy);
                proxy.Timeout = 60000;
                proxy.UseDefaultCredentials = false;

                wsInitTransactionOutput wsInitTransactionOutput = proxy.initTransaction(initTransaction);
                return(wsInitTransactionOutput);
            }
        }
示例#5
0
        protected void Page_Load()
        {
            Configuration configuration = new Configuration();

            configuration.Environment  = certificate["environment"];
            configuration.CommerceCode = certificate["commerce_code"];
            configuration.PublicCert   = certificate["public_cert"];
            configuration.WebpayCert   = certificate["webpay_cert"];
            configuration.Password     = certificate["password"];

            /** Creacion Objeto Webpay */
            Webpay.Transbank.Library.Webpay webpay = new Webpay.Transbank.Library.Webpay(configuration);

            /** Información de Host para crear URL */
            String httpHost = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"].ToString();
            String selfURL  = System.Web.HttpContext.Current.Request.ServerVariables["URL"].ToString();

            string action = !String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["action"]) ? HttpContext.Current.Request.QueryString["action"] : "init";

            /** Crea URL de Aplicación */
            string sample_baseurl = "http://" + httpHost + selfURL;

            /** Crea Dictionary con descripción */
            Dictionary <string, string> description = new Dictionary <string, string>();

            description.Add("VD", "Venta Deb&iacute;to");
            description.Add("VN", "Venta Normal");
            description.Add("VC", "Venta en cuotas");
            description.Add("SI", "cuotas sin inter&eacute;s");
            description.Add("S2", "2 cuotas sin inter&eacute;s");
            description.Add("NC", "N cuotas sin inter&eacute;s");

            /** Crea Dictionary con codigos de resultado */
            Dictionary <string, string> codes = new Dictionary <string, string>();

            codes.Add("0", "Transacci&oacute;n aprobada");
            codes.Add("-1", "Rechazo de transacci&oacute;n");
            codes.Add("-2", "Transacci&oacute;n debe reintentarse");
            codes.Add("-3", "Error en transacci&oacute;n");
            codes.Add("-4", "Rechazo de transacci&oacute;n");
            codes.Add("-5", "Rechazo por error de tasa");
            codes.Add("-6", "Excede cupo m&aacute;ximo mensual");
            codes.Add("-7", "Excede l&iacute;mite diario por transacci&oacute;n");
            codes.Add("-8", "Rubro no autorizado");

            HttpContext.Current.Response.Write("<p style='font-weight: bold; font-size: 200%;'>Ejemplos Webpay - Transacci&oacute;n Normal</p>");

            string buyOrder;

            string tx_step = "";

            switch (action)
            {
            default:

                tx_step = "Init";

                try
                {
                    HttpContext.Current.Response.Write("<p style='font-weight: bold; font-size: 150%;'>Step: " + tx_step + "</p>");

                    Random random = new Random();

                    /** Monto de la transacción */
                    decimal amount = System.Convert.ToDecimal("9990");

                    /** Orden de compra de la tienda */
                    buyOrder = random.Next(0, 1000).ToString();

                    /** (Opcional) Identificador de sesión, uso interno de comercio */
                    string sessionId = random.Next(0, 1000).ToString();

                    /** URL Final */
                    string urlReturn = sample_baseurl + "?action=result";

                    /** URL Final */
                    string urlFinal = sample_baseurl + "?action=end";

                    request.Add("amount", amount.ToString());
                    request.Add("buyOrder", buyOrder.ToString());
                    request.Add("sessionId", sessionId.ToString());
                    request.Add("urlReturn", urlReturn.ToString());
                    request.Add("urlFinal", urlFinal.ToString());

                    /** Ejecutamos metodo initTransaction desde Libreria */
                    wsInitTransactionOutput result = webpay.getNormalTransaction().initTransaction(amount, buyOrder, sessionId, urlReturn, urlFinal);

                    /** Verificamos respuesta de inicio en webpay */
                    if (result.token != null && result.token != "")
                    {
                        message = "Sesion iniciada con exito en Webpay";
                    }
                    else
                    {
                        message = "webpay no disponible";
                    }

                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightyellow;'><strong>request</strong></br></br>" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(request) + "</p>");
                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightgrey;'><strong>result</strong></br></br>" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(result) + "</p>");

                    HttpContext.Current.Response.Write("" + message + "</br></br>");
                    HttpContext.Current.Response.Write("<form action=" + result.url + " method='post'><input type='hidden' name='token_ws' value=" + result.token + "><input type='submit' value='Continuar &raquo;'></form>");
                }
                catch (Exception ex)
                {
                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightyellow;'><strong>request</strong></br></br>" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(request) + "</p>");
                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightgrey;'><strong>result</strong></br></br> Ocurri&oacute; un error en la transacci&oacute;n (Validar correcta configuraci&oacute;n de parametros). " + ex.Message + "</p>");
                }

                break;

            case "result":

                tx_step = "Get Result";

                try
                {
                    HttpContext.Current.Response.Write("<p style='font-weight: bold; font-size: 150%;'>Step: " + tx_step + "</p>");

                    /** Obtiene Información POST */
                    string[] keysPost = Request.Form.AllKeys;

                    /** Token de la transacción */
                    string token = Request.Form["token_ws"];

                    request.Add("token", token.ToString());

                    transactionResultOutput result = webpay.getNormalTransaction().getTransactionResult(token);

                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightyellow;'><strong>request</strong></br></br> " + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(request) + "</p>");
                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightgrey;'><strong>result</strong></br></br> " + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(result) + "</p>");

                    if (result.detailOutput[0].responseCode == 0)
                    {
                        message = "Pago ACEPTADO por webpay (se deben guardar datos para mostrar voucher)";

                        HttpContext.Current.Response.Write("<script>localStorage.setItem('authorizationCode', " + result.detailOutput[0].authorizationCode + ")</script>");
                        HttpContext.Current.Response.Write("<script>localStorage.setItem('commercecode', " + result.detailOutput[0].commerceCode + ")</script>");
                        HttpContext.Current.Response.Write("<script>localStorage.setItem('amount', " + result.detailOutput[0].amount + ")</script>");
                        HttpContext.Current.Response.Write("<script>localStorage.setItem('buyOrder', " + result.detailOutput[0].buyOrder + ")</script>");
                    }
                    else
                    {
                        message = "Pago RECHAZADO por webpay [Codigo]=> " + result.detailOutput[0].responseCode + " [Descripcion]=> " + codes[result.detailOutput[0].responseCode.ToString()];
                    }

                    HttpContext.Current.Response.Write(message + "</br></br>");
                    HttpContext.Current.Response.Write("<form action=" + result.urlRedirection + " method='post'><input type='hidden' name='token_ws' value=" + token + "><input type='submit' value='Continuar &raquo;'></form>");
                }
                catch (Exception ex)
                {
                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightyellow;'><strong>request</strong></br></br>" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(request) + "</p>");
                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightgrey;'><strong>result</strong></br></br> Ocurri&oacute; un error en la transacci&oacute;n (Validar correcta configuraci&oacute;n de parametros). " + ex.Message + "</p>");
                }

                break;

            case "end":

                tx_step = "End";

                try
                {
                    HttpContext.Current.Response.Write("<p style='font-weight: bold; font-size: 150%;'>Step: " + tx_step + "</p>");

                    request.Add("", "");

                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightyellow;'><strong>request</strong></br></br>" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(request) + "</p>");
                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightgrey;'><strong>result</strong></br></br>" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Request.Form["token_ws"]) + "</p>");

                    message = "Transacci&oacute;n Finalizada";
                    HttpContext.Current.Response.Write(message + "</br></br>");

                    string next_page = sample_baseurl + "?action=nullify";

                    HttpContext.Current.Response.Write("<form action=" + next_page + " method='post'><input type='hidden' name='commercecode' id='commercecode' value=''><input type='hidden' name='authorizationCode' id='authorizationCode' value=''><input type='hidden' name='amount' id='amount' value=''><input type='hidden' name='buyOrder' id='buyOrder' value=''><input type='submit' value='Anular Transacci&oacute;n &raquo;'></form>");
                    HttpContext.Current.Response.Write("<script>var commercecode = localStorage.getItem('commercecode');document.getElementById('commercecode').value = commercecode;</script>");
                    HttpContext.Current.Response.Write("<script>var authorizationCode = localStorage.getItem('authorizationCode');document.getElementById('authorizationCode').value = authorizationCode;</script>");
                    HttpContext.Current.Response.Write("<script>var amount = localStorage.getItem('amount');document.getElementById('amount').value = amount;</script>");
                    HttpContext.Current.Response.Write("<script>var buyOrder = localStorage.getItem('buyOrder');document.getElementById('buyOrder').value = buyOrder;</script>");
                }
                catch (Exception ex)
                {
                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightyellow;'><strong>request</strong></br></br>" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(request) + "</p>");
                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightgrey;'><strong>result</strong></br></br> Ocurri&oacute; un error en la transacci&oacute;n (Validar correcta configuraci&oacute;n de parametros). " + ex.Message + "</p>");
                }

                break;

            case "nullify":

                tx_step = "nullify";

                try
                {
                    HttpContext.Current.Response.Write("<p style='font-weight: bold; font-size: 150%;'>Step: " + tx_step + "</p>");

                    /** Obtiene Información POST */
                    string[] keysNullify = Request.Form.AllKeys;

                    /** Codigo de Comercio */
                    string commercecode = Request.Form["commercecode"];

                    /** Código de autorización de la transacción que se requiere anular */
                    string authorizationCode = Request.Form["authorizationCode"];

                    /** Monto autorizado de la transacción que se requiere anular */
                    decimal authorizedAmount = Int64.Parse(Request.Form["amount"]);

                    /** Orden de compra de la transacción que se requiere anular */
                    buyOrder = Request.Form["buyOrder"];

                    /** Monto que se desea anular de la transacción */
                    decimal nullifyAmount = 3;

                    request.Add("authorizationCode", authorizationCode.ToString());
                    request.Add("authorizedAmount", authorizedAmount.ToString());
                    request.Add("buyOrder", buyOrder.ToString());
                    request.Add("nullifyAmount", nullifyAmount.ToString());
                    request.Add("commercecode", commercecode.ToString());

                    nullificationOutput resultNullify = webpay.getNullifyTransaction().nullify(authorizationCode, authorizedAmount, buyOrder, nullifyAmount, commercecode);

                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightyellow;'><strong>request</strong></br></br>" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(request) + "</p>");
                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightgrey;'><strong>result</strong></br></br>" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(resultNullify) + "</p>");

                    message = "Transacci&oacute;n Finalizada";
                    HttpContext.Current.Response.Write(message + "</br></br>");
                }
                catch (Exception ex)
                {
                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightyellow;'><strong>request</strong></br></br>" + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(request) + "</p>");
                    HttpContext.Current.Response.Write("<p style='font-size: 100%; background-color:lightgrey;'><strong>result</strong></br></br> Ocurri&oacute; un error en la transacci&oacute;n (Validar correcta configuraci&oacute;n de parametros). " + ex.Message + "</p>");
                }

                break;
            }

            HttpContext.Current.Response.Write("</br><a href='default.aspx'>&laquo; volver a index</a>");
        }
示例#6
0
        public JsonResult GetToken(int[] Deudas, string rut)
        {
            if (Deudas == null)
            {
                return(JsonError("Debe seleccionar al menos un periodo."));
            }
            int deudaTotal = 0;

            var carro = new Models.SQL.TBL_CARRO_COMPRA
            {
                CEST_ESTADO = 1,
            };

            BDD.TBL_CARRO_COMPRA.Add(carro);
            BDD.Entry(carro).State = System.Data.Entity.EntityState.Added;

            BDD.SaveChanges();

            foreach (var item in Deudas)
            {
                var deuda = BDD.TBL_DEUDA.FirstOrDefault(o => o.DEU_ID == item);
                deuda.CAR_ID = carro.CAR_ID;

                BDD.TBL_DEUDA.Attach(deuda);
                BDD.Entry(deuda).State = System.Data.Entity.EntityState.Modified;

                deudaTotal += deuda.DEU_DEUDA;
            }

            carro.CAR_MONTO = deudaTotal;

            BDD.TBL_CARRO_COMPRA.Attach(carro);
            BDD.Entry(carro).State = System.Data.Entity.EntityState.Modified;

            BDD.SaveChanges();

            Configuration configuration = new Configuration();

            configuration.Environment  = certificate["environment"];
            configuration.CommerceCode = certificate["commerce_code"];
            configuration.PublicCert   = certificate["public_cert"];
            configuration.WebpayCert   = certificate["webpay_cert"];
            configuration.Password     = certificate["password"];

            /** Creacion Objeto Webpay */
            Webpay.Transbank.Library.Webpay webpay = new Webpay.Transbank.Library.Webpay(configuration);

            /** Información de Host para crear URL */
            String httpHost = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"].ToString();
            String selfURL  = System.Web.HttpContext.Current.Request.ServerVariables["URL"].ToString();


            string sample_baseurl = "http://" + httpHost + selfURL;
            /** Crea Dictionary con descripción */
            Dictionary <string, string> description = new Dictionary <string, string>();

            description.Add("VD", "Venta Deb&iacute;to");
            description.Add("VN", "Venta Normal");
            description.Add("VC", "Venta en cuotas");
            description.Add("SI", "cuotas sin inter&eacute;s");
            description.Add("S2", "2 cuotas sin inter&eacute;s");
            description.Add("NC", "N cuotas sin inter&eacute;s");


            string buyOrder;

            Random random = new Random();

            /** Monto de la transacción */
            decimal amount = (decimal)deudaTotal;

            /** Orden de compra de la tienda */
            buyOrder = carro.CAR_ID.ToString();

            /** (Opcional) Identificador de sesión, uso interno de comercio */
            string sessionId = Session.SessionID;

            /** URL Final */
            string urlReturn = "http://" + httpHost + "/Session/Deudas" + "?rut=" + rut + "&aaction=result";

            /** URL Final */
            string urlFinal = "http://" + httpHost + "/Session/Deudas" + "?rut=" + rut + "&aaction=end";

            request.Add("amount", amount.ToString());
            request.Add("buyOrder", buyOrder.ToString());
            request.Add("sessionId", sessionId.ToString());
            request.Add("urlReturn", urlReturn.ToString());
            request.Add("urlFinal", urlFinal.ToString());

            /** Ejecutamos metodo initTransaction desde Libreria */
            wsInitTransactionOutput result = webpay.getNormalTransaction().initTransaction(amount, buyOrder, sessionId, urlReturn, urlFinal);

            carro.CAR_TOKEN        = result.token;
            carro.CAR_ORDEN_COMPRA = buyOrder;
            carro.CAR_SESSION_ID   = sessionId;

            BDD.TBL_CARRO_COMPRA.Attach(carro);
            BDD.Entry(carro).State = System.Data.Entity.EntityState.Modified;

            BDD.SaveChanges();

            URLWEBPAY = result.url;

            if (result.token != null && result.token != "")
            {
                return(JsonExito("Sesion iniciada con exito en Webpay", new { request = request, result = result }));
            }
            else
            {
                return(JsonError("webpay no disponible"));
            }
        }
示例#7
0
        public ActionResult PagoTbk()
        {
            Configuration configuration = new Configuration();

            configuration.Environment  = certificate["environment"];
            configuration.CommerceCode = certificate["commerce_code"];
            configuration.PublicCert   = certificate["public_cert"];
            configuration.WebpayCert   = certificate["webpay_cert"];
            configuration.Password     = certificate["password"];

            ViewModels.TbkViewModel         vm     = new ViewModels.TbkViewModel();
            Webpay.Transbank.Library.Webpay webpay = new Webpay.Transbank.Library.Webpay(configuration);

            String httpHost       = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"].ToString();
            String selfURL        = System.Web.HttpContext.Current.Request.ServerVariables["URL"].ToString();
            string action         = !String.IsNullOrEmpty(System.Web.HttpContext.Current.Request.QueryString["action"]) ? System.Web.HttpContext.Current.Request.QueryString["action"] : "init";
            string sample_baseurl = "http://" + httpHost + selfURL;

            Dictionary <string, string> description = new Dictionary <string, string>();

            description.Add("VD", "Venta Deb&iacute;to");
            description.Add("VN", "Venta Normal");
            description.Add("VC", "Venta en cuotas");
            description.Add("SI", "cuotas sin inter&eacute;s");
            description.Add("S2", "2 cuotas sin inter&eacute;s");
            description.Add("NC", "N cuotas sin inter&eacute;s");

            Dictionary <string, string> codes = new Dictionary <string, string>();

            codes.Add("0", "Transacci&oacute;n aprobada");
            codes.Add("-1", "Rechazo de transacci&oacute;n");
            codes.Add("-2", "Transacci&oacute;n debe reintentarse");
            codes.Add("-3", "Error en transacci&oacute;n");
            codes.Add("-4", "Rechazo de transacci&oacute;n");
            codes.Add("-5", "Rechazo por error de tasa");
            codes.Add("-6", "Excede cupo m&aacute;ximo mensual");
            codes.Add("-7", "Excede l&iacute;mite diario por transacci&oacute;n");
            codes.Add("-8", "Rubro no autorizado");

            string  buyOrder;
            string  tx_step            = "";
            string  authorizationCodeR = "";
            string  idVenta            = "";
            decimal amount             = 0;
            string  horaProceso        = "";
            string  minProceso         = "";
            string  secProceso         = "";
            string  clientName         = "";

            try
            {
                try { clientName = (Request.Cookies["clientName"].Value != null) ? Request.Cookies["clientName"].Value : ""; }
                catch { clientName = ""; }

                switch (action)
                {
                default:

                    tx_step = "Init";
                    Random random = new Random();
                    horaProceso = Request.Cookies["horaProceso"].Value;
                    minProceso  = Request.Cookies["minProceso"].Value;
                    secProceso  = Request.Cookies["secProceso"].Value;
                    idVenta     = Request.Cookies["IdVenta"].Value;
                    amount      = Convert.ToDecimal(Request.Cookies["amount"].Value);
                    buyOrder    = idVenta;  //random.Next(0, 1000).ToString() + idVenta;
                    string sessionId = random.Next(0, 1000).ToString();
                    string urlReturn = sample_baseurl + "?action=result";
                    string urlFinal  = sample_baseurl + "?action=end";

                    request.Add("amount", amount.ToString());
                    request.Add("buyOrder", buyOrder.ToString());
                    request.Add("sessionId", sessionId.ToString());
                    request.Add("urlReturn", urlReturn.ToString());
                    request.Add("urlFinal", urlFinal.ToString());

                    DateTime aDate = DateTime.Now;
                    try
                    {
                        aDate = new DateTime(aDate.Year, aDate.Month, aDate.Day, Convert.ToInt32(horaProceso), Convert.ToInt32(minProceso), Convert.ToInt32(secProceso));
                    }
                    catch { }

                    DAL.MaestroVentas m1   = new DAL.MaestroVentas();
                    DTO.LogTbkDTO     log1 = new DTO.LogTbkDTO
                    {
                        IdVenta     = Convert.ToInt32(idVenta),
                        Fecha       = aDate,
                        Monto       = Convert.ToDouble(Request.Cookies["amount"].Value),
                        Token       = string.Empty,
                        CodigoTbk   = string.Empty,
                        Estado      = "Pendiente",
                        OrdenCompra = buyOrder
                    };
                    m1.SaveLogtBK(log1);

                    wsInitTransactionOutput result = webpay.getNormalTransaction().initTransaction(amount, buyOrder, sessionId, urlReturn, urlFinal);

                    if (result.token != null && result.token != "")
                    {
                        message = "Sesion iniciada con exito en Webpay";
                    }
                    else
                    {
                        message = "WebPay no disponible";
                        tx_step = "Error";
                    }

                    vm.token             = result.token;
                    vm.url               = result.url;
                    vm.step              = tx_step;
                    vm.message           = message;
                    vm.authorizationCode = "";
                    vm.amount            = 0;
                    vm.buyOrder          = "";
                    vm.client            = clientName;

                    break;

                case "result":

                    tx_step = "Get Result";
                    string   idVentaResp = Request.Cookies["IdVenta"].Value;
                    string[] keysPost    = Request.Form.AllKeys;
                    string   token       = Request.Form["token_ws"];
                    request.Add("token", token.ToString());

                    transactionResultOutput result2 = webpay.getNormalTransaction().getTransactionResult(token);

                    if (result2.detailOutput[0].responseCode == 0)
                    {
                        authorizationCodeR = result2.detailOutput[0].authorizationCode;
                        message            = "Pago ACEPTADO por webpay (se deben guardar datos para mostrar voucher)";

                        System.Web.HttpContext.Current.Response.Write("<script>localStorage.setItem('authorizationCode', " + result2.detailOutput[0].authorizationCode + ")</script>");
                        System.Web.HttpContext.Current.Response.Write("<script>localStorage.setItem('commercecode', " + result2.detailOutput[0].commerceCode + ")</script>");
                        System.Web.HttpContext.Current.Response.Write("<script>localStorage.setItem('amount', " + result2.detailOutput[0].amount + ")</script>");
                        System.Web.HttpContext.Current.Response.Write("<script>localStorage.setItem('buyOrder', " + result2.detailOutput[0].buyOrder + ")</script>");
                        System.Web.HttpContext.Current.Response.Write("<script>localStorage.setItem('clientName', " + clientName + ")</script>");

                        vm.token             = token;
                        vm.url               = result2.urlRedirection;
                        vm.step              = tx_step;
                        vm.message           = message;
                        vm.authorizationCode = authorizationCodeR;
                        vm.amount            = (double)result2.detailOutput[0].amount;
                        vm.buyOrder          = result2.detailOutput[0].buyOrder;
                        vm.client            = clientName;

                        DAL.MaestroVentas m = new DAL.MaestroVentas();
                        m.ActualizaEstadoVenta("2", Convert.ToInt32(idVentaResp));

                        DTO.LogTbkDTO log = new DTO.LogTbkDTO {
                            IdVenta     = Convert.ToInt32(idVentaResp),
                            Fecha       = result2.transactionDate,
                            Monto       = vm.amount,
                            Token       = vm.token,
                            CodigoTbk   = vm.authorizationCode,
                            Estado      = "Finalizado",
                            OrdenCompra = vm.buyOrder
                        };
                        m.UpdateStateLogtBK(log);

                        Helpers.CreaNotaVenta cnt = new Helpers.CreaNotaVenta();
                        double r = cnt.CreaNotaVentaSofltand(Convert.ToInt32(idVentaResp));
                    }
                    else
                    {
                        message = "Pago RECHAZADO por WebPay, Codigo: " + result2.detailOutput[0].responseCode;

                        vm.token             = token;
                        vm.url               = result2.urlRedirection;
                        vm.step              = "Error";
                        vm.message           = message;
                        vm.authorizationCode = result2.detailOutput[0].authorizationCode;
                        vm.amount            = (double)result2.detailOutput[0].amount;
                        vm.buyOrder          = result2.detailOutput[0].buyOrder;
                        vm.client            = clientName;

                        DAL.MaestroVentas m   = new DAL.MaestroVentas();
                        DTO.LogTbkDTO     log = new DTO.LogTbkDTO
                        {
                            IdVenta     = Convert.ToInt32(idVentaResp),
                            Fecha       = result2.transactionDate,
                            Monto       = vm.amount,
                            Token       = vm.token,
                            CodigoTbk   = vm.authorizationCode,
                            Estado      = "Rechazado",
                            OrdenCompra = vm.buyOrder
                        };
                        m.UpdateStateLogtBK(log);
                    }

                    Response.Cookies["amount"].Expires      = DateTime.Now.AddDays(-1);
                    Response.Cookies["IdVenta"].Expires     = DateTime.Now.AddDays(-1);
                    Response.Cookies["horaProceso"].Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies["minProceso"].Expires  = DateTime.Now.AddDays(-1);
                    Response.Cookies["secProceso"].Expires  = DateTime.Now.AddDays(-1);
                    Response.Cookies["clientName"].Expires  = DateTime.Now.AddDays(-1);

                    break;

                case "end":

                    tx_step = "End";
                    request.Add("", "");
                    message = "Transacción Finalizada";
                    string next_page = sample_baseurl + "?action=nullify";

                    System.Web.HttpContext.Current.Response.Write("<form action=" + next_page + " method='post'><input type='hidden' name='commercecode' id='commercecode' value=''><input type='hidden' name='authorizationCode' id='authorizationCode' value=''><input type='hidden' name='amount' id='amount' value=''><input type='hidden' name='buyOrder' id='buyOrder' value=''><input type='hidden' name='client' id='client' value=''><input type='hidden' name='product' id='product' value=''><input type='hidden' value='Anular Transacci&oacute;n &raquo;'></form>");
                    System.Web.HttpContext.Current.Response.Write("<script>var commercecode = localStorage.getItem('commercecode');document.getElementById('commercecode').value = commercecode;</script>");
                    System.Web.HttpContext.Current.Response.Write("<script>var authorizationCode = localStorage.getItem('authorizationCode');document.getElementById('authorizationCode').value = authorizationCode;</script>");
                    System.Web.HttpContext.Current.Response.Write("<script>var amount = localStorage.getItem('amount');document.getElementById('amount').value = amount;</script>");
                    System.Web.HttpContext.Current.Response.Write("<script>var buyOrder = localStorage.getItem('buyOrder');document.getElementById('buyOrder').value = buyOrder;</script>");
                    System.Web.HttpContext.Current.Response.Write("<script>var clientName = localStorage.getItem('clientName');document.getElementById('clientName').value = clientName;</script>");

                    vm.token             = "";
                    vm.url               = "";
                    vm.step              = tx_step;
                    vm.message           = message;
                    vm.authorizationCode = authorizationCodeR;
                    vm.amount            = (double)amount;
                    vm.buyOrder          = "";
                    vm.client            = clientName;

                    break;

                case "nullify":

                    tx_step = "nullify";
                    string[] keysNullify       = Request.Form.AllKeys;
                    string   commercecode      = Request.Form["commercecode"];
                    string   authorizationCode = Request.Form["authorizationCode"];
                    decimal  authorizedAmount  = Int64.Parse(Request.Form["amount"]);
                    buyOrder = Request.Form["buyOrder"];
                    decimal nullifyAmount = 3;

                    request.Add("authorizationCode", authorizationCode.ToString());
                    request.Add("authorizedAmount", authorizedAmount.ToString());
                    request.Add("buyOrder", buyOrder.ToString());
                    request.Add("nullifyAmount", nullifyAmount.ToString());
                    request.Add("commercecode", commercecode.ToString());

                    nullificationOutput resultNullify = webpay.getNullifyTransaction().nullify(authorizationCode, authorizedAmount, buyOrder, nullifyAmount, commercecode);
                    message = "Transacción Finalizada";

                    vm.token             = "";
                    vm.url               = "";
                    vm.step              = tx_step;
                    vm.message           = message;
                    vm.authorizationCode = "";
                    vm.amount            = 0;
                    vm.buyOrder          = "";
                    vm.client            = "";

                    break;
                }
            }
            catch (Exception ex)
            {
                vm.token             = "";
                vm.url               = "";
                vm.step              = "Error";
                vm.message           = "Ocurrio un error en la transacción (Validar correcta configuración de parametros). " + ex.Message;
                vm.authorizationCode = "";
                vm.amount            = 0;
                vm.buyOrder          = "";
                vm.client            = "";
            }

            return(PartialView(vm));
        }