/// <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);
            }
        }
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
        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"));
            }
        }
Exemplo n.º 4
0
        // GET: Session
        #region Vistas
        public ActionResult Deudas(string rut, string aaction, string token)
        {
            Cliente cliente = BDD.TBL_CLIENTE.Where(o => o.CLI_RUT == rut || o.CLI_CUENTA.ToString() == rut).ToList().Select(o => new Cliente
            {
                CliID     = o.CLI_ID,
                Nombre    = o.CLI_NOMBRE,
                ApellidoP = o.CLI_APELLIDO_PATERNO,
                ApellidoM = o.CLI_APELLIDO_MATERNO,
                Completo  = o.CLI_COMPLETO,
                Cuenta    = o.CLI_CUENTA,
                Rut       = o.CLI_RUT
            }).FirstOrDefault();

            //WebPay
            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"];

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

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

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

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

            if (aaction == "Deudas")
            {
                aaction = "result";
            }

            switch (aaction)
            {
            case "result":
                /** Obtiene Información POST */
                string[] keysPost = Request.Form.AllKeys;

                /** Token de la transacción */

                /** Token de la transacción */
                token = Request.Form["token_ws"];
                request.Add("token", token.ToString());

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

                var carro = BDD.TBL_CARRO_COMPRA.FirstOrDefault(o => o.CAR_TOKEN == token);

                var listo = result.detailOutput[0].responseCode == 0;

                if (listo)
                {
                    listo = carro.CAR_MONTO == result.detailOutput[0].amount;

                    if (!listo)
                    {
                        carro.CEST_ESTADO = 5;
                        carro.CAS_ERROR   = "Pago RECHAZADO los montos difieren";
                        ViewBag.Mensaje   = "Pago RECHAZADO los montos difieren";
                        ViewBag.Error     = true;

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

                        BDD.SaveChanges();

                        return(View(cliente));
                    }

                    listo = carro.CAR_ORDEN_COMPRA == result.detailOutput[0].buyOrder;

                    if (!listo)
                    {
                        carro.CEST_ESTADO = 5;
                        carro.CAS_ERROR   = "Pago RECHAZADO los orden de compra difieren";
                        ViewBag.Mensaje   = "Pago RECHAZADO los orden de compra difieren";
                        ViewBag.Error     = true;

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

                        BDD.SaveChanges();

                        return(View(cliente));
                    }

                    carro.CEST_ESTADO = 2;

                    carro.CAR_CODIGO_AUTORIZACION = result.detailOutput[0].authorizationCode;
                    carro.CAR_CODIGO_COMERCIO     = result.detailOutput[0].commerceCode;


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

                    BDD.SaveChanges();

                    var deudas = carro.TBL_DEUDA.ToList();

                    var pago = new Models.SQL.TBL_PAGOS
                    {
                        CLI_ID       = deudas[0]?.CLI_ID ?? 00,
                        PAG_FECHA    = DateTime.Now,
                        PAG_MONTO    = carro.CAR_MONTO ?? 0,
                        PAG_VIGENCIA = true,
                    };

                    BDD.TBL_PAGOS.Add(pago);
                    BDD.Entry(pago).State = System.Data.Entity.EntityState.Added;

                    BDD.SaveChanges();

                    foreach (var item in deudas)
                    {
                        item.PAG_ID = pago.PAG_ID;

                        BDD.TBL_DEUDA.Attach(item);
                        BDD.Entry(item).State = System.Data.Entity.EntityState.Modified;
                    }
                    try
                    {
                        //var d = webpay.getNormalTransaction().acknowledgeTransaction(token);
                    }
                    catch (Exception ex)
                    {
                        Logger(ex);
                        carro.CEST_ESTADO = 5;
                        carro.CAS_ERROR   = "Error al terminar el pago, itentelo de nuevo.";
                        ViewBag.Mensaje   = "Error al terminar el pago, itentelo de nuevo.";
                        ViewBag.Error     = true;

                        return(View(cliente));
                    }

                    BDD.SaveChanges();

                    ViewBag.Mensaje = "Pago realizado con éxito.";

                    ViewBag.Error = false;

                    return(Redirect(result.urlRedirection + "?token_ws=" + token));
                }
                else
                {
                    carro.CEST_ESTADO = 5;
                    carro.CAS_ERROR   = "Pago RECHAZADO por webpay [Codigo]=> " + result.detailOutput[0].responseCode + " [Descripcion]=> " + codes[result.detailOutput[0].responseCode.ToString()];
                    ViewBag.Mensaje   = "Pago RECHAZADO por webpay [Codigo]=> " + result.detailOutput[0].responseCode + " [Descripcion]=> " + codes[result.detailOutput[0].responseCode.ToString()];
                    ViewBag.Error     = true;

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

                    BDD.SaveChanges();

                    return(View(cliente));
                }
                break;

            case "end":
                break;
            }

            return(View(cliente));
        }
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 OneClick</p>");

            Random random = new Random();

            /** Nombre de usuario o cliente en el sistema del comercio */
            string username = "******";

            /** Dirección de correo electrónico registrada por el comercio */
            string email = "*****@*****.**";

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

                    string urlReturn = sample_baseurl + "?action=OneClickFinishInscription";

                    request.Add("username", username.ToString());
                    request.Add("email", email.ToString());
                    request.Add("urlReturn", urlReturn.ToString());

                    oneClickInscriptionOutput result = webpay.getOneClickTransaction().initInscription(username, email, urlReturn);

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

                    string token = result.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>");

                    HttpContext.Current.Response.Write("" + message + "</br></br>");
                    HttpContext.Current.Response.Write("<form action=" + result.urlWebpay + " method='post'><input type='hidden' name='TBK_TOKEN' 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 "OneClickFinishInscription":

                tx_step = "OneClickFinishInscription";

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

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

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

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

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

                    oneClickFinishInscriptionOutput result = webpay.getOneClickTransaction().finishInscription(token);

                    if (result.responseCode != 0)
                    {
                        message = "Transacci&oacute;n RECHAZADO por webpay";
                    }
                    else
                    {
                        message = "Transacci&oacute;n ACEPTADA por webpay";
                    }

                    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='tbkUser' value=" + result.tbkUser + "><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 "OneClickAuthorize":

                tx_step = "OneClickAuthorize";

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

                    next_page = sample_baseurl + "?action=OneClickReverse";

                    /** Usuario Transbank */
                    string tbkUser = Request.Form["tbkUser"];

                    /** Monto del pago en pesos */
                    string amount = random.Next(0, 1000).ToString();

                    DateTime today = DateTime.Now;

                    /** Identificador único de la compra generado por el comercio */
                    buyOrder = today.ToString("yyyyMMddHHmmss") + random.Next(0, 1000).ToString();

                    request.Add("buyOrder", buyOrder);
                    request.Add("tbkUser", tbkUser);
                    request.Add("username", username);
                    request.Add("amount", amount);

                    oneClickPayOutput result = webpay.getOneClickTransaction().authorize(buyOrder, tbkUser, username, amount);

                    /** Verificamos respuesta de inicio en webpay */
                    if (result.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='tbkUser' value=" + tbkUser + "><input type='hidden' name='buyOrder' value=" + buyOrder + "><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 "OneClickReverse":

                tx_step = "OneClickReverse";

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

                    next_page = sample_baseurl + "?action=OneClickFinal";

                    /** Usuario Transbank */
                    buyOrder = Request.Form["buyOrder"];

                    request.Add("buyOrder", buyOrder);

                    oneClickReverseOutput result = webpay.getOneClickTransaction().reverseTransaction(buyOrder);

                    /** Verificamos respuesta de inicio en webpay */
                    if (result.reversed == true)
                    {
                        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='tbkUser' value=" + Request.Form["tbkUser"] + "><input type='submit' value='Continuar &raquo;'></form>");
                }
                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;

            case "OneClickFinal":

                tx_step = "Get removeUser";

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

                    /** Usuario Transbank */
                    string tbkUser = Request.Form["tbkUser"];

                    request.Add("tbkUser", tbkUser);
                    request.Add("username", username);

                    bool result = webpay.getOneClickTransaction().oneClickremoveUserOutput(tbkUser, username);

                    /** Verificamos respuesta de inicio en webpay */
                    if (result == true)
                    {
                        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>");
                }
                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.º 6
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.º 7
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 Captura Diferida</p>");

            string buyOrder;

            string tx_step = "";

            switch (action)
            {
            default:

                tx_step = "Init";

                try
                {
                    string next_page = sample_baseurl + "?action=capture";

                    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 Captura</legend><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>captureAmount:</label>");
                    HttpContext.Current.Response.Write("<input id='captureAmount' name='captureAmount' 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;<br/><br/><br/>");
                    HttpContext.Current.Response.Write("<input 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 "capture":

                tx_step = "capture";

                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;

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

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

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

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

                    captureOutput result = webpay.getCaptureTransaction().capture(authorizationCode, authorizedAmount, buyOrder);

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