Crear archivo para recibir webhook

Para poder recibir las notificaciones en el webhook de forma correcta creamos un código ejemplo de webhook global para recibir cualquier evento de nuestras APIs el cual puedes utilizar para recibir de forma correcta los eventos que se disparan para notificar las respuestas de nuestras transacciones.

Pasos

1.- Copia y pega el código en un archivo de tu proyecto.
2.- Sube este archivo en tu servidor.
3.- Da de alta la dirección URL del archivo desde nuestro endpoint de Add Webhook .
4.- Realiza pruebas de pago, nuestro código genera un archivo de logs para que puedan ver los eventos que se ejecutaron mediante el webhook.

<?php
date_default_timezone_set('America/Mexico_City');

define('ROOT', dirname(__FILE__));
define('DS', DIRECTORY_SEPARATOR);
$log = true;
$json = file_get_contents('php://input');
$data = json_decode($json, true);

# Starting logs
if ($log) {
  $directorio_tmp = ROOT.DS.'logs'.DS;
  if (!file_exists($directorio_tmp)) {
    mkdir($directorio_tmp, 0777, true);
  }
  # log file
  $nombre_archivo_log = date('Y-m-d-H-i-s-').$data['event'];
  $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "w");
  fwrite($fp, date('H:i:s')." #################### Inicia LOG Transacción #################### \n");
}

# Defining the connection data

# Storing data
if ($log) {
  $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
  fwrite($fp, date('H:i:s')." 2- Se Guarda el objeto JSON recibido en un Archivo.  \n");

  $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
  fwrite($fp, date('H:i:s')."- ". json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)." \n");
}

# Getting transaction event
if ($log) {
  $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
  fwrite($fp, date('H:i:s')." 3- Evaluando el tipo de evento...  \n");
}

switch ($data['event']) {
  case 'cep.paid': 
    if ($log) {
      $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
      fwrite($fp, date('H:i:s')." 3.1 - Respuesta de NetPay Checkout Housted con Referencia Pagada  \n");
    }
    /* 
        Respuesta de NetPay Checkout Housted con Referencia Pagada
        {
            "data": {
                "sessionId": "xgwyPx3XoB7cUHBAgBJrTqQEy5fo=7",
                "transactionId": "3d8c8677-7e07-4040-b27b-9b2473ede3ab",
                "reference": "1258630012130904229",
                "merchantReferenceCode": "1616620941",
                "transactionType": "BANORTEPAY",
                "transactionStatus": "IN_PROCESS",
                "durationInDays": 0,
                "amount": 150.75
            },
            "event": "cep.paid”,
            "type": null,
            "createdAt": 1618267045988
        }
    
    */
    if ($log) {
      $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
      fwrite($fp, date('H:i:s')." 3.2- Ejecutamos el Endpoint Get Transaction.  \n");
    }
    $respuesta_get_transaction = consultaEstatus($data['data']['transactionId']);

    if ($log) {
      $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
      fwrite($fp, date('H:i:s')." 3.2 - Respuesta del Endpoint Get Transaction.  \n");
    }

    if ($log) {
      $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
      fwrite($fp, date('H:i:s')." 3.2.1 - ".$respuesta_get_transaction."\n");
    }

  break;
  case 'cep.created':
    if ($log) {
      $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
      fwrite($fp, date('H:i:s')." 3.1 - Respuesta de NetPay Checkout Housted con Referencia Creada  \n");
    }
    /* 
        Respuesta de NetPay Checkout Housted con Referencia Creada 

        {
            "data": {
                "transactionId": "3d8c8677-7e07-4040-b27b-9b2473ede3ab",
                "reference": "1258630012130904229",
                "merchantReferenceCode": "1616620941",
                "transactionType": "BANORTEPAY",
                "transactionStatus": "IN_PROCESS",
                "durationInDays": 0,
                "amount": 150.75
            },
            "event": "cep.created",
            "type": null,
            "createdAt": 1618267045988
        }
    */
    if ($log) {
      $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
      fwrite($fp, date('H:i:s')." 3.1- Ejecutamos el Endpoint Get Transaction.  \n");
    }
    $respuesta_get_transaction = consultaEstatus($data['data']['transactionId']);

    if ($log) {
      $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
      fwrite($fp, date('H:i:s')." 3.2 - Respuesta del Endpoint Get Transaction.  \n");
    }

    if ($log) {
      $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
      fwrite($fp, date('H:i:s')." 3.2.1 - ".$respuesta_get_transaction."\n");
    }
  break;
  default:
    $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
    fwrite($fp, date('H:i:s')." 3.2.1 - Caso default - No atrapado: ".$data['event']."\n");
  break;
}

return true;

function consultaEstatus($transactionId){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
          'Authorization: sk_netpay_lyNzonHFhwqoMHXfMFmOILqgZjAAjUVOjisfSkikPkrDA')); //Authorization es la secretkey
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_HEADER, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  curl_setopt($ch, CURLOPT_URL, "https://gateway-154.netpaydev.com/gateway-ecommerce/v3/transactions/".$transactionId);

  $response = curl_exec($ch);
  $err = curl_error($ch);
  curl_close($ch);
  //print_r($response);

  if ($err) {
    return $response = "cURL Error #:" . $err;
  } else {
    return json_encode(json_decode($response, true),  JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  }

  /* 
    Ejemplo de Respuesta del Endpoint Get Transaction.
    {
        "transactionTokenId": "3adeb3e5-0739-4d68-a01a-0b95efc8f7b1",
        "status": "DONE",
        "merchantReferenceCode": "test-11124",
        "currency": null,
        "amount": 200.0,
        "timeIn": "2021-03-02T23:15:48.000+0000",
        "timeOut": "2021-03-02T23:16:31.000+0000",
        "responseCode": "00",
        "responseMsg": "Aprobado",
        "authCode": null,
        "spanRouteNumber": "0002",
        "cardHolderName": "Jon Doe",
        "billToEmail": "[email protected]",
        "bankName": "JPMORGAN CHASE BANK",
        "paymentMethod": "card",
        "externalReference": null,
        "expireDate": null,
        "dayToExpirePayment": null
    }
  */
}
?>
// Establecer la zona horaria predeterminada
const timeZone = 'America/Mexico_City';
Intl.DateTimeFormat().resolvedOptions().timeZone = timeZone;

const ROOT = __dirname;
const DS = require('path').sep;
const log = true;
const json = require('fs').readFileSync('php://input', 'utf8');
const data = JSON.parse(json);

// Inicio de los registros
if (log) {
  const directorio_tmp = ROOT + DS + 'logs' + DS;
  if (!require('fs').existsSync(directorio_tmp)) {
    require('fs').mkdirSync(directorio_tmp, { recursive: true });
  }
  // Archivo de registro
  const nombre_archivo_log = new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').replace('Z', '') + data['event'];
  const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log');
  fp.write(new Date().toISOString().split('T')[1] + " #################### Inicia LOG Transacción #################### \n");
}

// Definición de los datos de conexión
/*
const server = "[TU_SERVIDOR]";
const db_name = "[TU_NOMBRE_DE_BD]";
const usr = "[TU_USUARIO_DE_BD]";
const pswd = "[TU_CONTRASEÑA_DE_BD]";
*/

// Creación de la conexión
/*if (log) {
  const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
  fp.write(new Date().toISOString().split('T')[1] + " 1- Creando conexión a la Base de Datos...  \n");
}*/

/*
const conn = new mysqli(server, usr, pswd, db_name);
if (conn.connect_error) {
  if (log) {
    const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
    fp.write(new Date().toISOString().split('T')[1] + " 1.2- Falló la conexión a la Base de Datos  \n");
  }
  throw new Error("Connection failed: " + conn.connect_error);
}
*/

/*if (log) {
  const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
  fp.write(new Date().toISOString().split('T')[1] + " 1.2- Conexión exitosa a la Base de Datos  \n");
}*/

// Almacenamiento de datos
if (log) {
  const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
  fp.write(new Date().toISOString().split('T')[1] + " 2- Se Guarda el objeto JSON recibido en un Archivo.  \n");

  const fp2 = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
  fp2.write(new Date().toISOString().split('T')[1] + "- " + JSON.stringify(data, null, 2) + " \n");
}

// Obtención del evento de transacción
if (log) {
  const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
  fp.write(new Date().toISOString().split('T')[1] + " 3- Evaluando el tipo de evento...  \n");
}

switch (data['event']) {
  case 'cep.paid':
    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.1 - Respuesta de NetPay Checkout Housted con Referencia Pagada  \n");
    }
    /* 
        Respuesta de NetPay Checkout Housted con Referencia Pagada
        {
            "data": {
                "sessionId": "xgwyPx3XoB7cUHBAgBJrTqQEy5fo=7",
                "transactionId": "3d8c8677-7e07-4040-b27b-9b2473ede3ab",
                "reference": "1258630012130904229",
                "merchantReferenceCode": "1616620941",
                "transactionType": "BANORTEPAY",
                "transactionStatus": "IN_PROCESS",
                "durationInDays": 0,
                "amount": 150.75
            },
            "event": "cep.paid”,
            "type": null,
            "createdAt": 1618267045988
        }
    
    */
    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.2- Ejecutamos el Endpoint Get Transaction.  \n");
    }
    const respuesta_get_transaction = consultaEstatus(data['data']['transactionId']);

    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.2 - Respuesta del Endpoint Get Transaction.  \n");
    }

    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.2.1 - " + respuesta_get_transaction + "\n");
    }

    break;
  case 'cep.created':
    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.1 - Respuesta de NetPay Checkout Housted con Referencia Creada  \n");
    }
    /* 
        Respuesta de NetPay Checkout Housted con Referencia Creada 

        {
            "data": {
                "transactionId": "3d8c8677-7e07-4040-b27b-9b2473ede3ab",
                "reference": "1258630012130904229",
                "merchantReferenceCode": "1616620941",
                "transactionType": "BANORTEPAY",
                "transactionStatus": "IN_PROCESS",
                "durationInDays": 0,
                "amount": 150.75
            },
            "event": "cep.created",
            "type": null,
            "createdAt": 1618267045988
        }
    */
    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.1- Ejecutamos el Endpoint Get Transaction.  \n");
    }
    const respuesta_get_transaction = consultaEstatus(data['data']['transactionId']);

    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.2 - Respuesta del Endpoint Get Transaction.  \n");
    }

    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.2.1 - " + respuesta_get_transaction + "\n");
    }
    break;
  case 'sessionLink.paid':
    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.1 - Respuesta de NetPay Checkout Housted de pago exitoso  \n");
    }
    /* 
        Respuesta de NetPay Checkout Housted de pago exitoso 
    
        {
            "data": {
                "sessionId": "xgwyPx3XoB7cUHBAgBJrTqQEy5fo=7",
                "transactionId": "fc5e9f79-d809-40cd-b2ce-2ba4d389d27f",
                "amount": "150.75",
                "status": "DONE",
                "cardHolderName": "John",
                "lastFourDigits": "0002",
                "bankName": "JPMORGAN CHASE BANK",
                "responseCode": "00",
                "procRetMsg": "Aprobada",
                "customerEmail": "[email protected]",
                "cartType": "001",
                "cardNature": "VISA DEBIT",
                "authDate": 1618267390617,
                "authCode": "123456",
                "orderId": "1618267387448630012"
            },
            "event": "sessionLink.paid",
            "type": null,
            "createdAt": 1618267390617
        }
    */
    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.1- Ejecutamos el Endpoint Get Transaction.  \n");
    }
    const respuesta_get_transaction = consultaEstatus(data['data']['transactionId']);

    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.2 - Respuesta del Endpoint Get Transaction.  \n");
    }

    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.2.1 - " + respuesta_get_transaction + "\n");
    }
    break;
  case 'sessionLink.failed':
    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.1 - Respuesta de NetPay Checkout Housted de pago fallido  \n");
    }
    /* 
        Respuesta de NetPay Checkout Housted de pago fallido 
    
        {
            "data": {
                "sessionId": "YpO=mm_!T3QaFpc_G__sv8uiU3gX0w",
                "transactionId": "40a6aa7a-f440-48b5-94c1-3e44d08d228f",
                "amount": "150.75",
                "status": "INSECURE",
                "cardHolderName": "John",
                "lastFourDigits": "0010",
                "bankName": null,
                "responseCode": "87",
                "procRetMsg": null,
                "customerEmail": "[email protected]",
                "cartType": "001",
                "cardNature": null,
                "authDate": 1616698827517,
                "authCode": null,
                "orderId": "1616698826988630012"
            },
            "event": "sessionLink.failed",
            "type": null,
            "createdAt": 1616698827517
        }
    */
    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.1- Ejecutamos el Endpoint Get Transaction.  \n");
    }
    const respuesta_get_transaction = consultaEstatus(data['data']['transactionId']);

    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.2 - Respuesta del Endpoint Get Transaction.  \n");
    }

    if (log) {
      const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
      fp.write(new Date().toISOString().split('T')[1] + " 3.2.1 - " + respuesta_get_transaction + "\n");
    }
    break;
  default:
    const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
    fp.write(new Date().toISOString().split('T')[1] + " 3.2.1 - Caso default - No atrapado: " + data['event'] + "\n");
    break;
}

/*
const sqlQuery = "INSERT INTO [TU_BASE_DE_DATOS] VALUES ([VALORES_QUE_NECESITAS]);";

if (conn.query(sqlQuery) === true) {
  if (log) {
    const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
    fp.write(new Date().toISOString().split('T')[1] + " 4- Registro creado en la base de datos.  \n");
  }
} 
else {
  if (log) {
    const fp = require('fs').createWriteStream(directorio_tmp + nombre_archivo_log + '.log', { flags: 'a' });
    fp.write(new Date().toISOString().split('T')[1] + " 4- Falló creación de registro en la base de datos. Error: " + sqlQuery + "<br>" + conn.error + "\n");
  }
}

conn.close();
*/

return true;

function consultaEstatus(transactionId) {
  const options = {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'sk_netpay_lyNzonHFhwqoMHXfMFmOILqgZjAAjUVOjisfSkikPkrDA' // Authorization es la secretkey
    },
    method: 'GET',
    rejectUnauthorized: false
  };

  const url = "https://gateway-154.netpaydev.com/gateway-ecommerce/v3/transactions/" + transactionId;

  return new Promise((resolve, reject) => {
    require('https').get(url, options, (res) => {
      let body = '';
      res.on('data', (chunk) => {
        body += chunk;
      });
      res.on('end', () => {
        resolve(JSON.stringify(JSON.parse(body), null, 2));
      });
    }).on('error', (err) => {
      reject("Error: " + err.message);
    });
  });
}

using System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Establecer la zona horaria
            TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("America/Mexico_City");
            TimeZoneInfo.ConvertTime(DateTime.Now, timeZone);

            // Definir la ruta raíz y el directorio temporal
            string root = AppDomain.CurrentDomain.BaseDirectory;
            string directoryTmp = Path.Combine(root, "logs");
            bool log = true;

            // Leer el JSON de la entrada estándar
            string json;
            using (StreamReader reader = new StreamReader(Console.OpenStandardInput()))
            {
                json = reader.ReadToEnd();
            }

            // Deserializar el JSON en un objeto dinámico
            dynamic data = JsonConvert.DeserializeObject(json);

            // Iniciar los registros
            if (log)
            {
                if (!Directory.Exists(directoryTmp))
                {
                    Directory.CreateDirectory(directoryTmp);
                }

                string logFileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-") + data["event"] + ".log";
                string logFilePath = Path.Combine(directoryTmp, logFileName);
                using (StreamWriter writer = new StreamWriter(logFilePath))
                {
                    writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " #################### Inicia LOG Transacción ####################");
                }
            }

            // Definir los datos de conexión
            /*
            string server = "[YOUR_SERVER]";
            string dbName = "[YOUR_DB_NAME]";
            string usr = "[YOUR_DB_USER]";
            string pswd = "[YOUR_DB_PASSWORD]";
            */

            // Crear la conexión
            /*if (log)
            {
                using (StreamWriter writer = new StreamWriter(logFilePath, true))
                {
                    writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 1- Creando conexión a la Base de Datos...");
                }
            }*/

            /*
            MySqlConnection conn = new MySqlConnection($"server={server};database={dbName};user={usr};password={pswd}");
            try
            {
                conn.Open();
                if (log)
                {
                    using (StreamWriter writer = new StreamWriter(logFilePath, true))
                    {
                        writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 1.2- Conexión exitosa a la Base de Datos");
                    }
                }
            }
            catch (Exception ex)
            {
                if (log)
                {
                    using (StreamWriter writer = new StreamWriter(logFilePath, true))
                    {
                        writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 1.2- Falló la conexión a la Base de Datos");
                    }
                }
                Console.WriteLine("Connection failed: " + ex.Message);
                return;
            }
            */

            // Almacenar los datos
            if (log)
            {
                using (StreamWriter writer = new StreamWriter(logFilePath, true))
                {
                    writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 2- Se Guarda el objeto JSON recibido en un Archivo.");
                    writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + "- " + JsonConvert.SerializeObject(data, Formatting.Indented));
                }
            }

            // Obtener el evento de la transacción
            if (log)
            {
                using (StreamWriter writer = new StreamWriter(logFilePath, true))
                {
                    writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3- Evaluando el tipo de evento...");
                }
            }

            switch (data["event"].ToString())
            {
                case "cep.paid":
                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.1 - Respuesta de NetPay Checkout Housted con Referencia Pagada");
                        }
                    }
                    /* 
                        Respuesta de NetPay Checkout Housted con Referencia Pagada
                        {
                            "data": {
                                "sessionId": "xgwyPx3XoB7cUHBAgBJrTqQEy5fo=7",
                                "transactionId": "3d8c8677-7e07-4040-b27b-9b2473ede3ab",
                                "reference": "1258630012130904229",
                                "merchantReferenceCode": "1616620941",
                                "transactionType": "BANORTEPAY",
                                "transactionStatus": "IN_PROCESS",
                                "durationInDays": 0,
                                "amount": 150.75
                            },
                            "event": "cep.paid”,
                            "type": null,
                            "createdAt": 1618267045988
                        }
                    */
                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.2- Ejecutamos el Endpoint Get Transaction.");
                        }
                    }
                    string respuestaGetTransaction = ConsultaEstatus(data["data"]["transactionId"].ToString());

                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.2 - Respuesta del Endpoint Get Transaction.");
                        }
                    }

                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.2.1 - " + respuestaGetTransaction);
                        }
                    }

                    break;
                case "cep.created":
                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.1 - Respuesta de NetPay Checkout Housted con Referencia Creada");
                        }
                    }
                    /* 
                        Respuesta de NetPay Checkout Housted con Referencia Creada 

                        {
                            "data": {
                                "transactionId": "3d8c8677-7e07-4040-b27b-9b2473ede3ab",
                                "reference": "1258630012130904229",
                                "merchantReferenceCode": "1616620941",
                                "transactionType": "BANORTEPAY",
                                "transactionStatus": "IN_PROCESS",
                                "durationInDays": 0,
                                "amount": 150.75
                            },
                            "event": "cep.created",
                            "type": null,
                            "createdAt": 1618267045988
                        }
                    */
                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.1- Ejecutamos el Endpoint Get Transaction.");
                        }
                    }
                    respuestaGetTransaction = ConsultaEstatus(data["data"]["transactionId"].ToString());

                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.2 - Respuesta del Endpoint Get Transaction.");
                        }
                    }

                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.2.1 - " + respuestaGetTransaction);
                        }
                    }
                    break;
                case "sessionLink.paid":
                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.1 - Respuesta de NetPay Checkout Housted de pago exitoso");
                        }
                    }
                    /* 
                        Respuesta de NetPay Checkout Housted de pago exitoso 
    
                        {
                            "data": {
                                "sessionId": "xgwyPx3XoB7cUHBAgBJrTqQEy5fo=7",
                                "transactionId": "fc5e9f79-d809-40cd-b2ce-2ba4d389d27f",
                                "amount": "150.75",
                                "status": "DONE",
                                "cardHolderName": "John",
                                "lastFourDigits": "0002",
                                "bankName": "JPMORGAN CHASE BANK",
                                "responseCode": "00",
                                "procRetMsg": "Aprobada",
                                "customerEmail": "[email protected]",
                                "cartType": "001",
                                "cardNature": "VISA DEBIT",
                                "authDate": 1618267390617,
                                "authCode": "123456",
                                "orderId": "1618267387448630012"
                            },
                            "event": "sessionLink.paid",
                            "type": null,
                            "createdAt": 1618267390617
                        }
                    */
                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.1- Ejecutamos el Endpoint Get Transaction.");
                        }
                    }
                    respuestaGetTransaction = ConsultaEstatus(data["data"]["transactionId"].ToString());

                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.2 - Respuesta del Endpoint Get Transaction.");
                        }
                    }

                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.2.1 - " + respuestaGetTransaction);
                        }
                    }
                    break;
                case "sessionLink.failed":
                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.1 - Respuesta de NetPay Checkout Housted de pago fallido");
                        }
                    }
                    /* 
                        Respuesta de NetPay Checkout Housted de pago fallido 
    
                        {
                            "data": {
                                "sessionId": "YpO=mm_!T3QaFpc_G__sv8uiU3gX0w",
                                "transactionId": "40a6aa7a-f440-48b5-94c1-3e44d08d228f",
                                "amount": "150.75",
                                "status": "INSECURE",
                                "cardHolderName": "John",
                                "lastFourDigits": "0010",
                                "bankName": null,
                                "responseCode": "87",
                                "procRetMsg": null,
                                "customerEmail": "[email protected]",
                                "cartType": "001",
                                "cardNature": null,
                                "authDate": 1616698827517,
                                "authCode": null,
                                "orderId": "1616698826988630012"
                            },
                            "event": "sessionLink.failed",
                            "type": null,
                            "createdAt": 1616698827517
                        }
                    */
                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.1- Ejecutamos el Endpoint Get Transaction.");
                        }
                    }
                    respuestaGetTransaction = ConsultaEstatus(data["data"]["transactionId"].ToString());

                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.2 - Respuesta del Endpoint Get Transaction.");
                        }
                    }

                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.2.1 - " + respuestaGetTransaction);
                        }
                    }
                    break;
                default:
                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 3.2.1 - Caso default - No atrapado: " + data["event"]);
                        }
                    }
                    break;
            }

            /*
            string sqlQuery = "INSERT INTO [YOUR_DATA_BASE] VALUES ([VALUES_YOU_NEED]);";

            using (MySqlCommand cmd = new MySqlCommand(sqlQuery, conn))
            {
                try
                {
                    cmd.ExecuteNonQuery();
                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 4- Registro creado en la base de datos.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (log)
                    {
                        using (StreamWriter writer = new StreamWriter(logFilePath, true))
                        {
                            writer.WriteLine(DateTime.Now.ToString("H:mm:ss") + " 4- Falló creación de registro en la base de datos. Error: " + ex.Message);
                        }
                    }
                }
            }

            conn.Close();
            */

            Console.WriteLine("true");
        }

        static string ConsultaEstatus(string transactionId)
        {
            string url = "https://gateway-154.netpaydev.com/gateway-ecommerce/v3/transactions/" + transactionId;
            string secretKey = "sk_netpay_lyNzonHFhwqoMHXfMFmOILqgZjAAjUVOjisfSkikPkrDA";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Headers.Add("Content-Type", "application/json");
            request.Headers.Add("Authorization", secretKey);

            string responseString;
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        responseString = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                responseString = "cURL Error #:" + ex.Message;
            }

            dynamic responseJson = JsonConvert.DeserializeObject(responseString);
            return JsonConvert.SerializeObject(responseJson, Formatting.Indented);
        }
    }
}