---
agentTools:
  projectIndex: https://etegram.readme.io/llms.txt
---

# Webhook

Webhooks are an important part of your payment integration. They allow Etegram notify you about events that happen on your account, such as a successful payment or a failed transaction.

EtegramPay supports webhooks to notify your server of payment events in real-time. This allows you to handle post-payment actions such as updating payment status.

With webhooks, our server sends updates to your server when the status of your request changes. The change in status of a request is known as an event. You’ll typically listen to these events on a POST endpoint called your webhook URL

**Setting Up Your Webhook URL**

A webhook URL is simply a POST endpoint that our server sends payment status updates to. The URL needs to parse a JSON request and return a 200 OK.

You can add your webhook URL on your Etegram business dashboard. Go to settings on the sidebar, click on the API & Webhooks, ensure you add your webhook url to both live and test mode.

```node node
// Using Express
app.post("/my/webhook/url", function(req, res) {
    // Retrieve the request's body
    const event = req.body;
    // Do something with event
    res.send(200);
});
```
```php php
<?php
// Assuming this script is saved as webhook.php

// Retrieve the request body
$requestBody = file_get_contents('php://input');

// Decode the JSON payload (if it's JSON)
$event = json_decode($requestBody, true);

// Do something with the $event data
// For example, you could log it:
file_put_contents('webhook_log.txt', print_r($event, true), FILE_APPEND);

// Respond with a 200 status code
http_response_code(200);
?>

```
```asp
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

[ApiController]
[Route("my/webhook/url")]
public class WebhookController : ControllerBase
{
    private readonly ILogger<WebhookController> _logger;

    public WebhookController(ILogger<WebhookController> logger)
    {
        _logger = logger;
    }

    [HttpPost]
    public IActionResult HandleWebhook([FromBody] object eventPayload)
    {
        // Log the received event for debugging purposes
        _logger.LogInformation("Webhook received: {EventPayload}", eventPayload);

        // Process the eventPayload as needed
        // For example, deserialize into a specific model if you know the structure:
        // var myEvent = JsonSerializer.Deserialize<MyEventModel>(eventPayload.ToString());

        // Respond with a 200 OK status
        return Ok();
    }
}

```
```ruby
require 'sinatra'
require 'json'

# Define the webhook endpoint
post '/my/webhook/url' do
  # Parse the incoming request body as JSON
  request_body = request.body.read
  event = JSON.parse(request_body)

  # Log or process the event as needed
  File.open('webhook_log.txt', 'a') do |f|
    f.puts(event)
  end

  # Respond with a 200 OK status
  status 200
end

```

In live mode, we’ll send webhooks every 3 minutes for the first 4 tries, then we switch to sending hourly for the next 72 hours

**Example Webhook Payload**

EtegramPay sends a JSON payload to your webhookURL with the following structure:

**Here is a sample webhook payload for successful payment:**

> <br />
>
> ```json
> {
>   "virtualAccount": {
>     "_id": "678106ee9f731800247859e3",
>     "client": "65fc376405cfe30024d693df",
>     "bankCode": "090286",
>     "bankName": "SAFE HAVEN MICROFINANCE BANK",
>     "accountNumber": "6010804474",
>     "accountName": "EtegramTechLtd Checkout",
>     "currencyCode": "NGN",
>     "validFor": "900",
>     "externalReference": "56cfad9f2f8d4bdbb621e5304a1fd40c",
>     "amountControl": "Fixed",
>     "amount": 100,
>     "expiryDate": "2025-01-10T11:54:26.187Z",
>     "callbackUrl": "https://api-checkout.etegram.com/api/transaction/webhook",
>     "status": "Active"
>   },
>   "projectID": "67475562c8d55ffeea8b0b34",
>   "amount": 98.5,
>   "fees": 1.5,
>   "status": "successful",
>   "type": "credit",
>   "reference": "newReference190",
>   "environment": "live",
>   "phone": "09012121212",
>   "email": "play@mail.com",
>   "fullname": "Ibrahim Remilekun",
>   "accessCode": "56cfad9f2f8d4bdbb621e5304a1fd40c",
>   "isReversed": false,
>   "createdAt": "2025-01-10T11:39:14.827Z",
>   "updatedAt": "2025-01-10T11:41:26.579Z",
>   "channel": "bank",
>   "id": "678106e2f34ed464668b43c5"
> }
> ```

**Event Types**

| Event Type | Description                                      |
| :--------- | :----------------------------------------------- |
| successful | Triggered when payment is successfully completed |
| failed     | Triggered when a payment attempt fails.          |

**Example Webhook Handler**

**Below is an example of how to handle a webhook in an Express.js server:**

```node
const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// Middleware to parse JSON payloads
app.use(bodyParser.json());

// Webhook endpoint
app.post('/payment-webhook', (req, res) => {
  const { event, transactionId, amount, currency, customerId } = req.body;

  switch (event) {
    case 'payment_success':
      console.log(`Payment successful! Transaction ID: ${transactionId}`);
      // Handle success logic here
      break;

    case 'payment_failed':
      console.error(`Payment failed for Customer ID: ${customerId}`);
      // Handle failure logic here
      break;

    case 'payment_refunded':
      console.log(`Payment refunded. Transaction ID: ${transactionId}`);
      // Handle refund logic here
      break;

    default:
      console.warn('Unhandled event type:', event);
  }

  res.status(200).send('Webhook received');
});

// Start the server
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

```