Creación de webhook

Para poder recibir la respuesta de nuestra API hacia tu webhook creamos un código ejemplo de webhook global para recibir de forma correcta los eventos de NetPay Loop, NetPay Cash, NetPay Checkout Hosted.

Pasos para implemetar el webhook

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
/*
$server = "[YOUR_SERVER]";
$db_name = "[YOUR_DB_NAME]";
$usr = "[YOUR_DB_USER]";
$pswd = "[YOUR_DB_PASSWORD]";
*/

# Creating connection
/*if ($log) {
  $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
  fwrite($fp, date('H:i:s')." 1- Creando conexión a la Base de Datos...  \n");
}*/

/*
$conn = new mysqli($server, $usr, $pswd, $db_name);
if ($conn->connect_error) {
  if ($log) {
    $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
    fwrite($fp, date('H:i:s')." 1.2- Falló la conexión a la Base de Datos  \n");
  }
  die("Connection failed: " . $conn->connect_error);
}
*/

/*if ($log) {
  $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
  fwrite($fp, date('H:i:s')." 1.2- Conexión exitosa a la Base de Datos  \n");
}*/

# 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;
  case 'sessionLink.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 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) {
      $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;
  case 'sessionLink.failed':
    if ($log) {
      $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
      fwrite($fp, date('H:i:s')." 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) {
      $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;
}

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

if ($conn->query($sqlQuery) === TRUE) {
  if ($log) {
    $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
    fwrite($fp, date('H:i:s')." 4- Registro creado en la base de datos.  \n");
  }
} 
else {
  if ($log) {
    $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
    fwrite($fp, date('H:i:s')." 4- Falló creación de registro en la base de datos. Error: ".$sqlQuery."<br>".$conn->error."\n");
  }
}

$conn->close();
*/

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
    }
  */
}
?>