> For the complete documentation index, see [llms.txt](https://developers.tiqets.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers.tiqets.dev/integration-guides/jwt-signing-for-secure-api-requests.md). Agents can also search and read this documentation through its [MCP server](https://developers.tiqets.dev/~gitbook/mcp).

# JWT Signing for Secure API Requests

Some API operations require additional security by signing the payload using JSON Web Tokens (JWT). JWT is a compact, URL-safe standard for transmitting verified data between parties.

You can find JWT libraries for most programming languages at [jwt.io](https://jwt.io/)

### Getting started: Generating Keys

To set up JWT signing, you'll need to:

1. **Generate an RSA key pair** (private and public keys).
2. **Keep the private key safe** — use it to sign payloads on your end.
3. **Share the public key with Tiqets** — we use it to verify incoming signatures.

See the section "[Generating RSA Key Pair](#generating-rsa-key-pair)" below for instructions.<br>

***

### Signing Process

1. **Create the payload** as a standard JSON object. Example:

```
{
  "payment_confirmation_token": "some_token"
}
```

2. **Generate the JWT** using a JWT library, your private key, and the RS256 algorithm.

```
request_body = jwt.encode(payload_json, private_key, algorithm='RS256')
```

3. **Send the resulting JWT** as the body of the HTTP request.

Tip: You can use [jwt.io’s debugger](https://jwt.io/#debugger-io) to validate and debug your JWTs.

***

### Understanding JWT Structure

A signed JWT consists of three Base64-encoded parts, separated by dots:

* **Header**: Specifies the algorithm (RS256) and type (JWT).
* **Payload**: The actual data to be transmitted.
* **Signature**: Ensures data integrity and authenticity.

**Example format**:

```
Header.Payload.Signature
```

This structure allows the receiver to verify that the data was not modified and came from a trusted source.

***

### Generating RSA Key Pair

During onboarding, you’ll be asked to send us your **public key**. To generate a key pair, run the following command:

```
ssh-keygen -t rsa -b 4096 -C "your+email@example.com" -m PEM -f <file-name.pem>
```

* Send the `.pub` file to Tiqets (see contact in onboarding email).
* **Keep your private key secret** — never share or embed it in apps or codebases.

**Example public key format**:

`ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDOesTyaUgcybyNWzeXXXXXXXXXXPzxLH9SSNVjqlyOEPXUhC68lDeLIUVwnPbecKFdQofSOY6cCAmCgXAhovGxoqoXbO9b2CyOsYjRd7Z+XBjfH2x3Hw== contact@example.com`

By following these steps, you ensure a secure integration between your system and Tiqets, with tamper-proof request validation.

### Code Samples

Here are several examples to help you get started with the JWT signing process.

Make sure to update the code before running it by:

* Inserting your API Key
* Inserting your Private Key

{% hint style="warning" %}
**Warning: The code samples below are meant for illustrative purposes only!**

Please apply best practices in your final product, such as keeping secrets outside of the source code or version control systems.
{% endhint %}

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

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

/**
 * Encodes Buffer or string into Base64URL (RFC 7515)
 * @param {string | Buffer} input
 * @returns {string}
 */
function base64UrlEncode(input) {
  const base64 = Buffer.from(input).toString('base64');
  return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

/**
 * Creates a JWT string signed using RS256
 * @param {object} payload - The payload as a plain JavaScript object
 * @param {string} privateKey - RSA private key in PEM format
 * @returns {string} Signed JWT token
 */
function generateJwt(payload, privateKey) {
  const header = {
    alg: 'RS256',
    typ: 'JWT',
  };

  const encodedHeader = base64UrlEncode(JSON.stringify(header));
  const encodedPayload = base64UrlEncode(JSON.stringify(payload));
  const dataToSign = `${encodedHeader}.${encodedPayload}`;

  const signer = crypto.createSign('RSA-SHA256');
  signer.update(dataToSign);
  signer.end();

  const signature = signer.sign(privateKey);
  const encodedSignature = base64UrlEncode(signature);

  return `${dataToSign}.${encodedSignature}`;
}

/**
 * Sends a JWT payload as raw POST body using HTTPS
 * @param {object} options
 * @param {string} options.url - Full URL of the endpoint
 * @param {string} options.jwt - Signed JWT payload string
 * @param {string} options.bearerToken - Bearer token as string
 * @param {boolean} [options.insecure=false] - Disable SSL checks (not for prod)
 * @returns {Promise<string>} - Server response as string
 */
async function postJwt({ url, jwt, bearerToken, insecure = false }) {
  const endpoint = new URL(url);
  const body = Buffer.from(jwt, 'utf8');

  const requestOptions = {
    hostname: endpoint.hostname,
    port: 443,
    path: endpoint.pathname + endpoint.search,
    method: 'POST',
    rejectUnauthorized: !insecure,
    headers: {
      'Authorization': `Bearer ${bearerToken}`,
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'User-Agent': 'NodeJS/JWT-Client',
      'Content-Length': body.length
    }
  };

  return new Promise((resolve, reject) => {
    const req = https.request(requestOptions, res => {
      let data = '';

      res.on('data', chunk => { data += chunk; });
      res.on('end', () => resolve(data));
    });

    req.on('error', err => {
      reject(new Error(`Request failed: ${err.message}`));
    });

    req.write(body);
    req.end();
  });
}

// --- 🧪 Example Usage ---

(async () => {
  const privateKey = `
-----BEGIN RSA PRIVATE KEY-----
<INSERT YOUR PRIVATE KEY HERE>
-----END RSA PRIVATE KEY-----
`.trim();

  /**
   * Returns a date string offset by a number of days (default: 7)
   * Format: YYYY-MM-DD
   * @param {number} offsetDays
   * @returns {string}
   */
  function getDatePlusDays(offsetDays = 7) {
    const date = new Date();
    date.setDate(date.getDate() + offsetDays);
    const year = date.getFullYear();
    const month = `${date.getMonth() + 1}`.padStart(2, '0');
    const day = `${date.getDate()}`.padStart(2, '0');
    return `${year}-${month}-${day}`;
  }

  const payload = {
    product_id: 1006356,
    day: getDatePlusDays(7), // today + 7 days
    variants: [
      { variant_id: 38100, count: 1 }
    ],
    customer_details: {
      firstname: "Johnny",
      lastname: "Bravo",
      phone: "5551234",
      email: "youremail@test.com"
    }
  };

  try {
    const jwtToken = generateJwt(payload, privateKey);
    const response = await postJwt({
      url: 'https://api-tiqt-test.steq.it/v2/orders?lang=en',
      jwt: jwtToken,
      bearerToken: '<INSERT YOUR API KEY HERE>',
      insecure: false
    });

    console.log('✅ Server response:\n', response);
  } catch (error) {
    console.error('❌ Error:', error.message);
  }
})();
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
function generateJwt($payload, $privateKey)
{
    // Define JWT header as an array
    $header = [
        'alg' => 'RS256',
        'typ' => 'JWT'
    ];

    // Encode header and payload to JSON and then to Base64URL
    $base64UrlHeader = rtrim(strtr(base64_encode(json_encode($header)), '+/', '-_'), '=');
    $base64UrlPayload = rtrim(strtr(base64_encode($payload), '+/', '-_'), '=');

    // Concatenate the two with a dot
    $dataToSign = $base64UrlHeader . "." . $base64UrlPayload;

    // Sign the data using RS256
    $signature = '';
    $success = openssl_sign($dataToSign, $signature, $privateKey, OPENSSL_ALGO_SHA256);

    if (!$success) {
        throw new Exception("Failed to sign the JWT. Check your private key.");
    }

    $base64UrlSignature = rtrim(strtr(base64_encode($signature), '+/', '-_'), '=');

    // Return the complete JWT
    return $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
}


/** Thsi is old */
function callApiWithJwt($endpoint, $privateKey, $bearerToken, $payload)
{
    $jwtPayload = generateJwt($payload, $privateKey);
    

    // Prepare the HTTP request headers
    $headers = [
        'Authorization: Bearer ' . $bearerToken,
        'Content-Type: application/json',
        'Accept: application/json',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36'
    ];


    // Initialize cURL
    $ch = curl_init($endpoint);

    // Configure cURL options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jwtPayload);

    // Execute the HTTP request
    $response = curl_exec($ch);

    // Check for errors
    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        curl_close($ch);
        throw new Exception("cURL error: " . $error_msg);
    }

    // Close cURL and return the response
    curl_close($ch);

    return $response;
}

// Example Usage
try {
    $endpoint = 'https://api-tiqt-test.steq.it/v2/orders?lang=en';
    $privateKey = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
<INSERT YOUR KEY HERE>
-----END RSA PRIVATE KEY-----
EOD;
    $bearerToken = '<INSERT YOUR API KEY HERE>';
    $payload = '{
  "product_id": 1006356,
  "day": "2025-07-17",
  "variants": [
    {
      "variant_id": 38100,
      "count": 1
    }
  ],
  "customer_details": {
    "firstname": "Johnny",
    "lastname": "Bravo",
    "phone": "5551234",
    "email": "you@email.com"
  }
}';

    $response = callApiWithJwt($endpoint, $privateKey, $bearerToken, $payload);
    echo "Response: " . $response;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
```

{% endtab %}

{% tab title="Python" %}

```python
import json
import requests
import jwt  # PyJWT
import datetime

# Adjust your private key here (PEM format)
PRIVATE_KEY = """-----BEGIN RSA PRIVATE KEY-----
<INSERT YOUR PRIVATE KEY HERE>
-----END RSA PRIVATE KEY-----"""

# Your bearer token
BEARER_TOKEN = "<INSERT YOUR API KEY HERE>"
# Your API endpoint
ENDPOINT = "https://api-tiqt-test.steq.it/v2/orders?lang=en"

def get_date_plus_days(days=7):
    """Returns a date string offset by X days (default: 7), format YYYY-MM-DD"""
    target_date = datetime.date.today() + datetime.timedelta(days=days)
    return target_date.isoformat()

def generate_jwt(payload, private_key):
    """
    Generates a RS256-signed JWT using PyJWT.
    Payload must be a dict; header is set manually.
    """
    headers = {
        "alg": "RS256",
        "typ": "JWT"
    }

    # PyJWT handles json encoding and base64url encoding correctly
    token = jwt.encode(
        payload=payload,
        key=private_key,
        algorithm="RS256",
        headers=headers
    )

    # ⚠ PyJWT returns bytes in older versions; decode if necessary
    if isinstance(token, bytes):
        token = token.decode('utf-8')

    return token

def send_jwt(endpoint, jwt_token, bearer_token):
    """
    Sends the JWT as the POST body with appropriate headers.
    """
    headers = {
        "Authorization": f"Bearer {bearer_token}",
        "Content-Type": "application/json",
        "Accept": "application/json",
        "User-Agent": "Python/JWT-Client"
    }

    response = requests.post(
        endpoint,
        data=jwt_token,  # Raw string body
        headers=headers,
        verify=False  # Optional: turn off SSL verification (like your PHP test)
    )

    return response

# Example payload creation
payload = {
    "product_id": 1006356,
    "day": get_date_plus_days(7),
    "variants": [
        {
            "variant_id": 38100,
            "count": 1
        }
    ],
    "customer_details": {
        "firstname": "Johnny",
        "lastname": "Bravo",
        "phone": "5551234",
        "email": "youremail@test.com"
    }
}

# Run it
if __name__ == "__main__":
    token = generate_jwt(payload, PRIVATE_KEY)
    print("🔐 JWT Token:\n", token)

    response = send_jwt(ENDPOINT, token, BEARER_TOKEN)
    print(f"\n✅ Status Code: {response.status_code}")
    print("🧾 Response:\n", response.text)
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://developers.tiqets.dev/integration-guides/jwt-signing-for-secure-api-requests.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
