/// <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); } }
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íto"); description.Add("VN", "Venta Normal"); description.Add("VC", "Venta en cuotas"); description.Add("SI", "cuotas sin interés"); description.Add("S2", "2 cuotas sin interés"); description.Add("NC", "N cuotas sin interés"); /** 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"); HttpContext.Current.Response.Write("<p style='font-weight: bold; font-size: 200%;'>Ejemplos Webpay - Transacció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 »'></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ó un error en la transacción (Validar correcta configuració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 »'></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ó un error en la transacción (Validar correcta configuració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ó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ón »'></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ó un error en la transacción (Validar correcta configuració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ó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ó un error en la transacción (Validar correcta configuración de parametros). " + ex.Message + "</p>"); } break; } HttpContext.Current.Response.Write("</br><a href='default.aspx'>« volver a index</a>"); }
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íto"); description.Add("VN", "Venta Normal"); description.Add("VC", "Venta en cuotas"); description.Add("SI", "cuotas sin interés"); description.Add("S2", "2 cuotas sin interés"); description.Add("NC", "N cuotas sin interé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")); } }
// 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íto"); description.Add("VN", "Venta Normal"); description.Add("VC", "Venta en cuotas"); description.Add("SI", "cuotas sin interés"); description.Add("S2", "2 cuotas sin interés"); description.Add("NC", "N cuotas sin interé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)); }
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íto"); description.Add("VN", "Venta Normal"); description.Add("VC", "Venta en cuotas"); description.Add("SI", "cuotas sin interés"); description.Add("S2", "2 cuotas sin interés"); description.Add("NC", "N cuotas sin interés"); 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"); 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ón »'></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)); }