Crear archivo para recibir webhook

Para poder recibir 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
/*
$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 'subscription.paid':
    if ($log) {
      $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
      fwrite($fp, date('H:i:s')." 3.1 - Respuesta de NetPay Loop de pago exitoso  \n");
    }
    /* 
        Respuesta de NetPay Loop de pago exitoso 
    
        {
          "data": {
            "status": "PaymentDue",
            "description": "Harry R. M. Pitts",
            "currency": "MXN",
            "amount": "83.51",
            "client_id": "A=b1542ONefJlGO_P!mO=Nar03m9w7",
            "id": "sbEiw1b=FNLrIVvFuJuxlc_mMaUR6F",
            "object": "Paid",
            "transactionTokenId": "1ca9f71f-769d-4cfe-9e0f-9315652bfaa3",
            "billingStart": 1609480800000,
            "nextPaymentDate": null,
            "subscriptionId": "sbEiw1b=FNLrIVvFuJuxlc_mMaUR6F",
            "billingEnd": "01/01/22 06:00:00",
            "planName": "Harry R. M. Pitts",
            "processing_intent_subscription_number": 1
          },
          "event": "subscription.paid",
          "type": "Subscription",
          "createdAt": 1609282533152
        }
    */
    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']['transactionTokenId']);

    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 'subscription.payment_failed':
    if ($log) {
      $fp = fopen($directorio_tmp . $nombre_archivo_log.'.log', "a");
      fwrite($fp, date('H:i:s')." 3.1 - Respuesta de NetPay Loop de pago fallido  \n");
    }
    /* 
        Respuesta de NetPay Loop de pago fallido 

        {
          "data": {
            "status": "PaymentDue",
            "description": "Harry R. M. Pitts",
            "currency": "MXN",
            "amount": "83.51",
            "client_id": "A=b1542ONefJlGO_P!mO=Nar03m9w7",
            "id": "sbEiw1b=FNLrIVvFuJuxlc_mMaUR6F",
            "object": "PaymentFailed",
            "transactionTokenId": "1ca9f71f-769d-4cfe-9e0f-9315652bfaa3",
            "billingStart": 1609480800000,
            "nextPaymentDate": null,
            "subscriptionId": "sbEiw1b=FNLrIVvFuJuxlc_mMaUR6F",
            "billingEnd": "01/01/22 06:00:00",
            "planName": "Harry R. M. Pitts",
            "processing_intent_subscription_number": 1
          },
          "event": "subscription.payment_failed",
          "type": "Subscription",
          "createdAt": 1609282533152
        }
    */
    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']['transactionTokenId']);

    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;
}

/*
$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 $response;
  }

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