> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dollarpe.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

<Highlight>
  \#Introduction
</Highlight>

All API endpoints require authentication through three custom headers.
These headers ensure secure communication between your application and our API.

<Note>
  Ensure you have your API credentials (API Key and API Secret) before proceeding.\
  Contact our [support team](mailto:support@dollarpe.xyz) if you need assistance obtaining these credentials.
</Note>

<Warning>
  Use distinct API credentials for **Sandbox** and **Production** environments.\
  **Production** API keys are not valid in the **Sandbox** environment and vice versa.
</Warning>

## Required Headers

<ResponseField name="X-API-KEY" type="string" required>
  Your unique API key provided by DollarPe. This key identifies your application.
</ResponseField>

<ResponseField name="X-TIMESTAMP" type="integer" required>
  The current Unix timestamp in seconds. This helps prevent replay attacks.
</ResponseField>

<ResponseField name="X-SIGNATURE" type="string" required>
  An HMAC SHA256 signature of the request, encoded in Base64. This signature verifies the integrity and authenticity of the request.
</ResponseField>

## Generating the Signature

The signature is a critical component of the authentication process. Follow these steps to generate it:

<Steps>
  <Step title="Create Message String">
    Concatenate the API key, timestamp, and a sorted JSON string of the request body using a pipe (`|`) separator.

    ```python theme={null}
    import time
    import json

    api_key = "your-api-key"
    timestamp = int(time.time())
    request_body = { # your request body }
    sorted_body = json.dumps(request_body, sort_keys=True)
    message = f"{api_key}|{timestamp}|{sorted_body}"
    ```
  </Step>

  <Step title="Generate Hash">
    Use your API secret to create an HMAC SHA256 hash of the message string.

    ```python theme={null}
    import hmac
    import hashlib

    api_secret = "your-api-secret"
    hash = hmac.new(api_secret.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).digest()
    ```
  </Step>

  <Step title="Encode">
    Convert the resulting hash to Base64 format. This encoded string is your signature.

    ```python theme={null}
    import base64

    signature = base64.b64encode(hash).decode('utf-8')
    ```
  </Step>
</Steps>

## Code Examples

Below are examples in various programming languages to generate the required headers:

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    const crypto = require('crypto');

    /**
     * Generates authentication headers for API requests.
     * @param {string} apiKey - Your API key.
     * @param {string} apiSecret - Your API secret.
     * @param {Object} [body={}] - The request body.
     * @returns {Object} - The headers object containing authentication details.
     */
    const generateHeaders = (apiKey, apiSecret, body = {}) => {
      // Get current timestamp
      const timestamp = Math.floor(Date.now() / 1000);

      // Sort and stringify the body
      const sortedBody = JSON.stringify(body, Object.keys(body).sort());

      // Create message string
      const message = `${apiKey}|${timestamp}|${sortedBody}`;

      // Generate signature
      const signature = crypto
        .createHmac('sha256', apiSecret)
        .update(message)
        .digest('base64');

      return {
        'X-API-KEY': apiKey,
        'X-TIMESTAMP': timestamp.toString(),
        'X-SIGNATURE': signature
      };
    };
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import time
    import json
    import hmac
    import base64
    import hashlib

    def generate_headers(api_key, api_secret, body={}):
        """
        Generates authentication headers for API requests.

        :param api_key: Your API key.
        :param api_secret: Your API secret.
        :param body: The request body (default is {}).
        :return: A dictionary containing the authentication headers.
        """
        # Get current timestamp
        timestamp = int(time.time())

        # Sort and stringify the body
        sorted_body = json.dumps(body, sort_keys=True)

        # Create message string
        message = f"{api_key}|{timestamp}|{sorted_body}"

        # Generate signature
        signature = base64.b64encode(
            hmac.new(
                api_secret.encode('utf-8'),
                message.encode('utf-8'),
                hashlib.sha256
            ).digest()
        ).decode('utf-8')

        return {
            'X-API-KEY': api_key,
            'X-TIMESTAMP': str(timestamp),
            'X-SIGNATURE': signature
        }
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.TreeMap;
    import com.fasterxml.jackson.databind.ObjectMapper;

    public class HeaderGenerator {
        private static final ObjectMapper objectMapper = new ObjectMapper();

        /**
         * Generates authentication headers for API requests.
         *
         * @param apiKey Your API key.
         * @param apiSecret Your API secret.
         * @param body The request body.
         * @return A map containing the authentication headers.
         * @throws Exception If an error occurs during header generation.
         */
        public static Map<String, String> generateHeaders(String apiKey, String apiSecret, Map<String, Object> body) throws Exception {
            // Get current timestamp
            long timestamp = System.currentTimeMillis() / 1000;

            // Sort and stringify the body
            String sortedBody = "{}";
            if (body != null) {
                TreeMap<String, Object> sortedMap = new TreeMap<>(body);
                sortedBody = objectMapper.writeValueAsString(sortedMap);
            }

            // Create message string
            String message = String.format("%s|%d|%s", apiKey, timestamp, sortedBody);

            // Generate signature
            Mac sha256Hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(
                apiSecret.getBytes(StandardCharsets.UTF_8), 
                "HmacSHA256"
            );
            sha256Hmac.init(secretKey);
            String signature = Base64.getEncoder().encodeToString(
                sha256Hmac.doFinal(message.getBytes(StandardCharsets.UTF_8))
            );

            // Create headers map
            Map<String, String> headers = new HashMap<>();
            headers.put("X-API-KEY", apiKey);
            headers.put("X-TIMESTAMP", String.valueOf(timestamp));
            headers.put("X-SIGNATURE", signature);

            return headers;
        }
    }
    ```
  </Tab>
</Tabs>

## Example Usage

Here's how to use the generated headers in an API request:

```javascript theme={null}
const apiKey = "your-api-key";
const apiSecret = "your-api-secret";

const requestBody = {
  asset: "USDT",
  network: "BSC",
  amount: 100.5,
};

const headers = generateHeaders(apiKey, apiSecret, requestBody);

// Make API request
fetch("https://sandbox.dollarpe.xyz/pos/api/v1/payout/fetch-rate", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    ...headers,
  },
  body: JSON.stringify(requestBody),
});
```
