Exemplo n.º 1
0
        /* *
         * Permite solicitar a  Webpay la anulación de una transacción realizada previamente y que se encuentra vigente.
         * */
        public nullificationOutput nullify(string authorizationCode, decimal authorizedAmount, string buyOrder, decimal nullifyAmount, string commercecode)
        {
            nullificationInput nullificationInput = new nullificationInput();

            nullificationInput.authorizationCode = authorizationCode;
            nullificationInput.authorizedAmount  = authorizedAmount;
            nullificationInput.buyOrder          = buyOrder;

            if (commercecode == null)
            {
                nullificationInput.commerceId = Int64.Parse(this.config.CommerceCode);
            }
            else
            {
                nullificationInput.commerceId = Int64.Parse(commercecode);
            }

            nullificationInput.nullifyAmount = nullifyAmount;

            using (WSCommerceIntegrationServiceImplService proxy = new WSCommerceIntegrationServiceImplService())
            {
                /*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;

                nullificationOutput nullificationOutput = proxy.nullify(nullificationInput);
                return(nullificationOutput);
            }
        }
Exemplo n.º 2
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>");
        }
Exemplo n.º 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            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;

            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
                {
                    string next_page = sample_baseurl + "?action=nullify";

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

                    HttpContext.Current.Response.Write("<form id='formulario' action=" + next_page + " method='post'>");
                    HttpContext.Current.Response.Write("<fieldset>");
                    HttpContext.Current.Response.Write("<legend>Formulario de Anulaci&oacute;n</legend><br/><br/>");
                    HttpContext.Current.Response.Write("<label>commercecode:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                    HttpContext.Current.Response.Write("<input id='commercecode' name='commercecode' type='text' /><br/><br/><br/>");
                    HttpContext.Current.Response.Write("<label>authorizationCode:</label>");
                    HttpContext.Current.Response.Write("<input id='authorizationCode' name='authorizationCode' type='text' />&nbsp;&nbsp;&nbsp;");
                    HttpContext.Current.Response.Write("<label>authorizedAmount:</label>");
                    HttpContext.Current.Response.Write("<input id='authorizedAmount' name='authorizedAmount' type='text' />&nbsp;&nbsp;&nbsp;");
                    HttpContext.Current.Response.Write("<label>buyOrder:</label>");
                    HttpContext.Current.Response.Write("<input id='buyOrder' name='buyOrder' type='text' />&nbsp;&nbsp;&nbsp;");
                    HttpContext.Current.Response.Write("<label>nullifyAmount:</label>");
                    HttpContext.Current.Response.Write("<input id='nullifyAmount' name='nullifyAmount' type='text' /><br/><br/><br/>");
                    HttpContext.Current.Response.Write("<input id='nullify' name='enviar' type='submit' value='Enviar' />");
                    HttpContext.Current.Response.Write("</fieldset>");
                    HttpContext.Current.Response.Write("</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 "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["authorizedAmount"]);

                    /** 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 = Int64.Parse(Request.Form["nullifyAmount"]);

                    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 result = webpay.getNullifyTransaction().nullify(authorizationCode, authorizedAmount, buyOrder, nullifyAmount, commercecode);

                    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(result) + "</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>result</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>");
        }
Exemplo n.º 4
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));
        }
Exemplo n.º 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            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;

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

            string buyOrder;
            string token;
            string next_page;

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

                    next_page = sample_baseurl + "?action=queryshare";

                    Random random = new Random();

                    /** Monto de la transacción */
                    decimal amount = 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();

                    /** Fecha de expiración de tarjeta, formato YY/MM */
                    string cardExpirationDate = "18/04";

                    /** Código de verificación de la tarjeta */
                    int cvv = 123;

                    /** Número de la tarjeta */
                    string cardNumber = "4051885600446623";

                    request.Add("amount", amount.ToString());
                    request.Add("buyOrder", buyOrder.ToString());
                    request.Add("sessionId", sessionId.ToString());
                    request.Add("cardExpirationDate", cardExpirationDate.ToString());
                    request.Add("cvv", cvv.ToString());
                    request.Add("cardNumber", cardNumber.ToString());

                    wsCompleteInitTransactionOutput result = webpay.getCompleteTransaction().initCompleteTransaction(amount, buyOrder, sessionId, cardExpirationDate, cvv, cardNumber);

                    /** 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=" + next_page + " method='post'>");
                    HttpContext.Current.Response.Write("<input type='hidden' name='token_ws' value=" + result.token + ">");
                    HttpContext.Current.Response.Write("<input type='hidden' name='buyOrder' value=" + buyOrder + ">");
                    HttpContext.Current.Response.Write("<input type='submit' value='Continuar &raquo;'>");
                    HttpContext.Current.Response.Write("</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 "queryshare":

                tx_step = "Queryshare";

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

                    next_page = sample_baseurl + "?action=authorize";

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

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

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

                    /** Número de cuotas */
                    string shareNumber = "2";

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

                    wsCompleteQuerySharesOutput result = webpay.getCompleteTransaction().queryShare(token, buyOrder, shareNumber);

                    /** Verificamos respuesta de inicio en webpay */
                    if (result.token != null && result.token != "")
                    {
                        message = "Transacci&oacute;n realizada 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=" + next_page + " method='post'>");

                    HttpContext.Current.Response.Write("<input type='hidden' name='buyOrder' value=" + buyOrder + ">");
                    HttpContext.Current.Response.Write("<input type='hidden' name='token_ws' value=" + token + ">");
                    HttpContext.Current.Response.Write("<input type='hidden' name='queryId' value=" + result.queryId + ">");
                    HttpContext.Current.Response.Write("<input type='submit' value='Continuar &raquo;'>");
                    HttpContext.Current.Response.Write("</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 "authorize":

                tx_step = "Authorize";

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

                    next_page = sample_baseurl + "?action=end";

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

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

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

                    /** (Opcional) Flag que indica si aplica o no periodo de gracia */
                    bool gracePeriod = false;

                    /** Identificador de la consulta de cuota */
                    long queryShare = Convert.ToInt64(Request.Form["queryId"]);

                    /** (Opcional) Lista de contiene los meses en los cuales se puede diferir el pago, y el monto asociado a cada periodo */
                    int deferredPeriodIndex = 1;

                    request.Add("token", token.ToString());
                    request.Add("buyOrder", buyOrder.ToString());
                    request.Add("gracePeriod", gracePeriod.ToString());
                    request.Add("queryShare", queryShare.ToString());
                    request.Add("deferredPeriodIndex", deferredPeriodIndex.ToString());

                    wsCompleteAuthorizeOutput result = webpay.getCompleteTransaction().authorize(token, buyOrder, gracePeriod, queryShare, deferredPeriodIndex);

                    /** Verificamos respuesta de inicio en webpay */
                    if (result.detailsOutput[0].responseCode == 0)
                    {
                        message = "Transacci&oacute;n realizada 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=" + next_page + " method='post'><input type='hidden' name='buyOrder' value=" + buyOrder + "><input type='hidden' name='token_ws' value=" + token + "><input type='hidden' name='authorizationCode' value=" + result.detailsOutput[0].authorizationCode + "><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>");

                    next_page = sample_baseurl + "?action=nullify";

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

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

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

                    /** Identificador de la consulta de cuota */
                    string idQueryShare = Request.Form["idQueryShare"];

                    /** Codigo de Autorización */
                    int authorizationCode = Int32.Parse(Request.Form["authorizationCode"]);

                    request.Add("", "");
                    message = "Transacci&oacute;n Finalizada";

                    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(token) + "</p>");

                    HttpContext.Current.Response.Write("" + message + "</br></br>");
                    HttpContext.Current.Response.Write("<form action=" + next_page + " method='post'><input type='hidden' name='buyOrder' value=" + buyOrder + "><input type='hidden' name='token_ws' value=" + token + "><input type='hidden' name='idQueryShare' value=" + idQueryShare + "><input type='hidden' name='authorizationCode' value=" + authorizationCode + "><input type='submit' value='Anular Transacci&oacute;n &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 "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 = certificate["commerce_code"];

                    /** 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 = 9990;

                    /** 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 = 9990;

                    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 result = 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(result) + "</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>");
        }