# Signing API Payloads

***

#### Overview

To ensure the security and integrity of API requests, all requests to Tylt must be signed using your API Secret Key. Each request includes a signature generated using HMAC-SHA256, allowing Tylt to verify:

* The authenticity of the request
* That the payload has not been tampered with

***

#### How Signing Works

1. Prepare the request payload
2. Convert the payload into a string
3. Generate a signature using HMAC-SHA256 with your API Secret Key
4. Include the signature in the request headers

***

#### Signature Function

```javascript
const createSignature = (secret, data) => {
    return crypto.createHmac('sha256', secret)
                 .update(data)
                 .digest('hex');
};
```

***

#### Signing a POST Request

For POST requests:

* Convert the request body to a JSON string
* Use the exact same string for:
  * request body
  * signature generation

```javascript
const sendPostRequest = async (url, body) => {
    const raw = JSON.stringify(body);
    const signature = createSignature(apiSecret, raw);
    const headers = {
        "X-TLP-APIKEY": apiKey,
        "X-TLP-SIGNATURE": signature
    };
    const response = await axios.post(url, body, { headers });
    return response.data;
};
```

***

#### Signing a GET Request

For GET requests:

* Convert query parameters into a query string
* Use the same query string for signature generation

```javascript
const sendGetRequest = async (url, params) => {
    const raw = new URLSearchParams(params).toString();
    const signature = createSignature(apiSecret, JSON.stringify(params));
    const headers = {
        "X-TLP-APIKEY": apiKey,
        "X-TLP-SIGNATURE": signature
    };
    const response = await axios.get(`${url}?${raw}`, { headers });
    return response.data;
};
```

***

### Headers

All requests must include:

| Header            | Description                          |
| ----------------- | ------------------------------------ |
| `X-TLP-APIKEY`    | Your API Key                         |
| `X-TLP-SIGNATURE` | HMAC-SHA256 signature of the request |

***

### Important Rules

* The string used for signature must exactly match the payload sent
* Any difference in formatting, spacing, or encoding will result in signature mismatch
* Always generate signatures on the server side only
* Never expose your API Secret Key in frontend applications

***

### Security Best Practices

* Store API credentials in a secure environment (e.g., secrets manager)
* Rotate keys immediately if compromised
* Restrict API usage to trusted backend systems

***

### **Example Codes**

Here’s how you can sign requests using different programming languages:

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

```javascript
// Common function to create HMAC SHA-256 signature
const createSignature = (secret, data) => {
    return crypto.createHmac('sha256', secret)
                 .update(data)
                 .digest('hex');
};
```

{% endtab %}

{% tab title="Node JS" %}

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

// Replace with your API Key and Secret
const apiKey = 'your-api-key';
const apiSecret = 'your-api-secret';

// Function to send a POST request
const sendPostRequest = async (url, body) => {
    const raw = JSON.stringify(body);
    const signature = createSignature(apiSecret, raw);
    const headers = {
        "X-TLP-APIKEY": apiKey,
        "X-TLP-SIGNATURE": signature
    };
    const response = await axios.post(url, body, { headers });
    return response.data;
};

// Function to send a GET request
const sendGetRequest = async (url, params) => {
    const raw = new URLSearchParams(params).toString();
    const signature = createSignature(apiSecret, JSON.stringify(params));
    const headers = {
        "X-TLP-APIKEY": apiKey,
        "X-TLP-SIGNATURE": signature
    };
    const response = await axios.get(`${url}?${raw}`, { headers });
    return response.data;
};
```

{% endtab %}

{% tab title="Python" %}

```python
import json
import hashlib
import hmac
import requests

# Replace with your API Key and Secret
api_key = 'your-api-key'
api_secret = 'your-api-secret'

# Function to create HMAC SHA-256 signature
def create_signature(secret, data):
    return hmac.new(secret.encode(), data.encode(), hashlib.sha256).hexdigest()

# Function to send a POST request
def send_post_request(url, body):
    raw = json.dumps(body, separators=(',', ':'), ensure_ascii=False)
    signature = create_signature(api_secret, raw)
    headers = {
        'X-TLP-APIKEY': api_key,
        'X-TLP-SIGNATURE': signature
    }
    response = requests.post(url, headers=headers, data=raw)
    return response.json()
    
send_post_request('https://domain.com/path', body = {"orderId":"UUID-order-id"})

# Function to send a GET request
def send_get_request(url, params):
    raw = '&'.join([f"{key}={value}" for key, value in params.items()])
    body_string = json.dumps(params, separators=(',', ':'), ensure_ascii=False)
    signature = create_signature(api_secret, body_string)
    headers = {
        'X-TLP-APIKEY': api_key,
        'X-TLP-SIGNATURE': signature
    }
    response = requests.get(f"{url}?{raw}", headers=headers)
    return response.json()
send_get_request('https://domain.com/path',  params = {"orderId":"UUID-order-id"})
```

{% endtab %}

{% tab title="JavaScript" %}

<pre class="language-javascript"><code class="lang-javascript">const crypto = require('crypto');

// Function to send a POST request
const sendPostRequest = async (url, body) => {
    const raw = JSON.stringify(body);
    const signature = createSignature(apiSecret, raw);
    const headers = {
        "Content-Type": "application/json",
        "X-TLP-APIKEY": apiKey,
        "X-TLP-SIGNATURE": signature
    };
    const response = await fetch(url, {
        method: 'POST',
        headers: headers,
        body: raw,
    });
    return response.json();
};

// Function to send a GET request
<strong>    const sendGetRequest = async (url, params) => {
</strong>    const raw = new URLSearchParams(params).toString();
    const signature = createSignature(apiSecret, raw);
    const headers = {
        "X-TLP-APIKEY": apiKey,
        "X-TLP-SIGNATURE": signature
    };
    const response = await fetch(`${url}?${raw}`, {
        method: 'GET',
        headers: headers,
    });
    return response.json();
};
</code></pre>

{% endtab %}
{% endtabs %}

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

* **Keep Your Keys Secure**: Always use environment variables or secure storage for sensitive information like your API Secret Key.
* **Regenerate Keys if Compromised**: If your API keys are exposed or compromised, regenerate them immediately and update your secure storage.
  {% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.tylt.money/introduction/signing-api-payloads.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
