# Webhook for Tylt CrossRamp (Pay-in)

#### Overview

Tylt provides a webhook mechanism for merchants to receive real-time updates on the status of their payment instance, whether for pay-ins or for pay-outs. Merchants can specify a `callBackUrl` in their API requests, and Tylt will send notifications to this URL whenever there is a status change in the transaction.

#### Setting Up the Webhook

1. **Implement a Callback Endpoint:** Merchants must set up an HTTP POST endpoint that can receive JSON payloads. This endpoint should be capable of processing the incoming webhook data and verifying its authenticity using HMAC-SHA256 signature validation.
2. **Insert the Callback URL:** While calling the Create Pay-in or Create Pay-out instance API's  , insert your endpoint URL in the `callBackUrl` field. Tylt will send updates to this URL whenever the transaction status changes.
3. **Status Updates:**  The life cycle of a payment instance is tracked via `eventId`. Below is the list of possible `eventId` values and their meanings:<br>

   <table data-header-hidden><thead><tr><th width="100"></th><th></th></tr></thead><tbody><tr><td><strong><code>eventId</code></strong></td><td><strong>Description</strong></td></tr><tr><td><strong><code>1</code></strong></td><td>The instance and trade is created. Waiting for the user to accept the quote.</td></tr><tr><td><strong><code>2</code></strong></td><td>Quote accepted. Waiting for user to enter CPF number.</td></tr><tr><td><strong><code>3</code></strong></td><td>PIX QR generated. Waiting for the user to make the payment.</td></tr><tr><td><strong><code>4</code></strong></td><td>Payment acknowledged and trade settled.</td></tr><tr><td><strong><code>9</code></strong></td><td>Trade expired as action or payment was not completed prior to the deadline or disputed payment was expired due to non payment. </td></tr></tbody></table>

{% hint style="info" %}

### Instance Information

The response related to an instance information contains two primary objects:

#### 1. Trade Object

This object contains all the information about the customer buying or selling USDT from the counterparty. It includes fields like:

* Trade lifecycle details (`eventId`, deadlines, description).
* Fiat and cryptocurrency details (currency name, symbol, amount, etc.).
* Payment method information (e.g., PIX).

#### 2. Transaction Object

This object contains all the information about the financial debit or credit carried out on the merchant's account. It is relevant to merchants for crediting or debiting a consumer for the transaction. The `transaction` object is updated **only when the `eventId` is 4**, representing the completion of the trade
{% endhint %}

4. **Callback Validation:** To ensure the integrity and authenticity of the callback, Tylt signs each callback payload using HMAC-SHA256 with the merchant’s API secret key. This signature is sent in the HTTP header `X-TLP-SIGNATURE`.
5. **Acknowledge the Callback:** Upon receiving the callback, merchants must respond with an HTTP 200 status code and the text `"ok"` in the response body. This acknowledges the successful receipt of the callback. If the acknowledgment is not received, the webhook will not be retried automatically. Merchants can manually resend webhooks from their Tylt dashboard.

#### Validating Callbacks

Merchants should validate the HMAC signature included in the `X-TLP-SIGNATURE` header to ensure the callback is from Tylt and has not been tampered with. The HMAC signature is generated using the raw POST data and the `MERCHANT_API_SECRET` as the shared key.

#### Example Web-hook Handling Code

{% tabs %}
{% tab title="JavaScript" %}

```javascript
const express = require('express');
const crypto = require('crypto');

const app = express();
const PORT = 3000;
const apiSecretKey = 'YOUR_TLP_API_SECRET_KEY'; // Replace with your actual API secret key

// Middleware to parse incoming JSON requests
app.use(express.json());

// Callback endpoint
app.post('/callback', (req, res) => {
    const data = req.body;

    // Calculate HMAC signature
    const tlpSignature = req.headers['x-tlp-signature'];
    const calculatedHmac = crypto
        .createHmac('sha256', apiSecretKey)
        .update(JSON.stringify(data)) // Use raw body string for HMAC calculation
        .digest('hex');

    if (calculatedHmac === tlpSignature) {
        // Signature is valid
        if (data.accounts.transactionType === 'pay-in') {
            console.log('Received pay-in callback:', data);
            // Process pay-in data here
        } 
        // Return HTTP Response 200 with content "ok"
        res.status(200).send('ok');
    } else {
        // Invalid HMAC signature
        res.status(400).send('Invalid HMAC signature');
    }
});

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

```

{% endtab %}

{% tab title="Python" %}

```python
from flask import Flask, request, jsonify
import hmac
import hashlib

app = Flask(__name__)

# Your TL Pay API Secret Key
TLP_API_SECRET_KEY = 'YOUR_TLP_API_SECRET_KEY'  # Replace with your actual API secret key

@app.route('/callback', methods=['POST'])
def callback():
    # Get the raw request data for HMAC calculation
    raw_data = request.data

    # Parse JSON data from the request
    data = request.get_json()

    # Retrieve the signature from the request headers
    tlp_signature = request.headers.get('X-TLP-SIGNATURE')

    # Calculate the HMAC SHA-256 signature
    calculated_hmac = hmac.new(
        key=TLP_API_SECRET_KEY.encode(),
        msg=raw_data,
        digestmod=hashlib.sha256
    ).hexdigest()

    # Compare the calculated HMAC signature with the one in the request header
    if hmac.compare_digest(calculated_hmac, tlp_signature):
        # Signature is valid
        if data['accounts']['transactionType'] == 'pay-in':
            print('Received pay-in callback:', data)
            # Process pay-in data here
            
        # Return HTTP Response 200 with content "ok"
        return jsonify({"message": "ok"}), 200
    else:
        # Invalid HMAC signature
        return jsonify({"error": "Invalid HMAC signature"}), 400

if __name__ == '__main__':
    app.run(port=3000, debug=True)

```

{% endtab %}
{% endtabs %}

Again, please note that these code snippets serve as examples and may require modifications based on your specific implementation and framework.

**Example of Web-hook Responses**

{% tabs %}
{% tab title="eventId: 1" %}

```json
{
    "data": {
        "trade": {
            "event": {
                "id": 1,
                "deadline": "2025-02-12T05:27:37Z",
                "description": "Trade Initiated. Payment Link Generated. Quote displayed."
            },
            "createdAt": "2025-02-12T05:24:37Z",
            "updatedAt": "2025-02-12T05:24:37Z",
            "fiatCurrency": {
                "name": "Brazilian Real",
                "symbol": "BRL"
            },
            "priceDetails": {
                "price": null,
                "amount": null,
                "paymentAmount": 500
            },
            "paymentMethod": {
                "details": null
            },
            "cryptoCurrency": {
                "name": "Tether",
                "symbol": "USDT"
            }
        },
        "transaction": {
            "amount": null,
            "status": null,
            "isFinal": null,
            "orderId": null,
            "createdAt": null,
            "isCredited": null,
            "updatedAt": null,
            "merchantOrderId": "b73b73b-87wtbc-q36gbc-331n3"
        },
        "accounts": {
                    "transactionType": "pay-in",
                    "amountPaidInLocalCurrency": 500,
                    "localCurrency": "BRL",
                    "conversionRate": null,
                    "amountPaidInCryptoCurrency": null,
                    "cryptoCurrencySymbol": "USDT",
                    "MDR_Rate": 1.1,
                    "merchantAccountCredited": null,
                    "merchantAccountDebited": null,
                     //  fields below are applicable to PIX instant pay-in.
                    "transactionHash": "0x7f696e3389c7f72f933a2ef5607a9b5a2ec5cb00317aa4df19de44cb82d5ca52",
                    "network": "ETH"
                },
        "user": {}
    }
}
```

{% endtab %}

{% tab title="eventId: 2" %}

```json
{
    "data": {
        "trade": {
            "event": {
                "id": 2,
                "deadline": "2025-02-12T05:30:03Z",
                "description": "Quote Accepted. Waiting for CPF input."
            },
            "createdAt": "2025-02-12T05:24:37Z",
            "updatedAt": "2025-02-12T05:25:03Z",
            "fiatCurrency": {
                "name": "Brazilian Real",
                "symbol": "BRL"
                },
            "priceDetails": {
                "price": 5.00,
                "amount": 100,  // Amount of USDT
                "paymentAmount": 500  // Amount to be paid by user in BRL
            }, 
            "paymentMethod": {
                "details": null
            },
            "cryptoCurrency": {
                "name": "Tether",
                "symbol": "USDT"
            }
        },
        "transaction": {
            "amount": null,
            "status": null,
            "isFinal": null,
            "orderId": null,
            "createdAt": null,
            "isCredited": null,
            "updatedAt": null,
            "merchantOrderId": "b73b73b-87wtbc-q36gbc-331n3"
        },
        "accounts": {
            "transactionType": "pay-in",
            "amountPaidInLocalCurrency": 500.00, // Amount to be paid by user in BRL
            "localCurrency": "BRL",
            "conversionRate": 5.00,
            "amountPaidInCryptoCurrency": 100,  // Amount of USDT
            "cryptoCurrencySymbol": "USDT",
            "MDR_Rate": 1.1,
            "merchantAccountCredited": null,
            "merchantAccountDebited": null
        },
        "user": {}
    }
}
```

Again, please note that these response snippets serve as examples and may require modifications based on your specific implementation and framework.
{% endtab %}

{% tab title="eventId: 3" %}

```json
{
    "data": {
        "trade": {
            "event": {
                "id": 3,
                "deadline": "2025-02-12T05:30:03Z",
                "description": "Awaiting Payment"
            },
            "createdAt": "2025-02-12T05:24:37Z",
            "updatedAt": "2025-02-12T05:25:03Z",
            "fiatCurrency": {
                "name": "Brazilian Real",
                "symbol": "BRL"
                },
            "priceDetails": {
                "price": 5.00,
                "amount": 100,  // Amount of USDT
                "paymentAmount": 500  // Amount to be paid by user in BRL
            }, 
            "paymentMethod": {
                "details": null
            },
            "cryptoCurrency": {
                "name": "Tether",
                "symbol": "USDT"
            }
        },
        "transaction": {
            "amount": null,
            "status": null,
            "isFinal": null,
            "orderId": null,
            "createdAt": null,
            "isCredited": null,
            "updatedAt": null,
            "merchantOrderId": "b73b73b-87wtbc-q36gbc-331n3"
        },
        "accounts": {
            "transactionType": "pay-in",
            "amountPaidInLocalCurrency": 500.00, // Amount to be paid by user in BRL
            "localCurrency": "BRL",
            "conversionRate": 5.00,
            "amountPaidInCryptoCurrency": 100,  // Amount of USDT
            "cryptoCurrencySymbol": "USDT",
            "MDR_Rate": 1.1,
            "merchantAccountCredited": null,
            "merchantAccountDebited": null
        },
        "user": {}
    }
}
```

{% endtab %}

{% tab title="eventId: 4" %}

```json
{
    "data": {
        "trade": {
            "event": {
                "id": 4,
                "deadline": "2025-02-12T05:30:03Z",
                "description": "Payment acknowledged and trade settled."
            },
            "createdAt": "2025-02-12T05:24:37Z",
            "updatedAt": "2025-02-12T05:25:03Z",
            "fiatCurrency": {
                "name": "Brazilian Real",
                "symbol": "BRL"
                },
            "priceDetails": {
                "price": 5.00,
                "amount": 100,  // Amount of USDT
                "paymentAmount": 500  // Amount to be paid by user in BRL
            }, 
            "paymentMethod": {
                "details": null
            },
            "cryptoCurrency": {
                "name": "Tether",
                "symbol": "USDT"
            }
        },
        "transaction": {
            "amount": 5.00,
            "status": "Completed",
            "isFinal": 1,
            "orderId": "nbdfd-73b73b-8oidtbc-oi8rfh-331n3ull",
            "createdAt": "2025-02-12T05:25:03Z",
            "isCredited": 1,
            "updatedAt": "2025-02-12T05:25:03Z",,
            "merchantOrderId": "b73b73b-87wtbc-q36gbc-331n3"
        },
        "accounts": {
            "transactionType": "pay-in",
            "amountPaidInLocalCurrency": 500.00, // Amount to be paid by user in BRL
            "localCurrency": "BRL",
            "conversionRate": 5.00,
            "amountPaidInCryptoCurrency": 100,  // Amount of USDT
            "cryptoCurrencySymbol": "USDT",
            "MDR_Rate": 1.1,
            "merchantAccountCredited": null,
            "merchantAccountDebited": null
        },
        "user": {}
    }
}

```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Important Considerations**

* **Security:** Always verify the `X-TLP-SIGNATURE` header to ensure the callback originates from Tylt.
* **Response:** Always return an HTTP 200 response with `"ok"` in the body to acknowledge successful receipt of the web-hook.
* **Manual Retry:** In case of missed callbacks, use the tylt.money dashboard to manually resend the webhook.
  {% endhint %}
