---
updatedAt: 2025-12-15T10:06:58.000Z
agentTools:
  projectIndex: https://developer.onetrust.com/onetrust/llms.txt
---

# Real-Time Consent: Lightweight, Fast, and UI-Ready

```python main.py
import requests
import jwt
import datetime
import time
import logging
from typing import Dict, Any

# Configure Logging and Set Logging Level
logging.basicConfig(
    level=logging.DEBUG, # INFO, DEBUG, ERROR
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# === API Configuration ===
API_HOST = "https://app.onetrust.com"
API_TOKEN = "NjQ0ZDkzY2MzOTM2NDhhZWIeNjbyYjJkG2I2MGY1YzQ6VDBtd2dEd2NZS3dxeWVNcG01Rk9EMGdaMUlPRDdUdUU="
TENANT_ID = "33df590e-3fd5-44bd-a50f-3722988021ed"
COLLECTION_POINT_ID = "f312dd9b-58b4-4f34-b5ff-10b9b464bc4d"
COLLECTION_POINT_VERSION = "3"
IDENTIFIER = "gpburdell@onetrust.com"
PUBLIC_KEY = "b5c2740eae2d1e48796d4dcdf14398688e1e772af9d85dfe83d8e71a4a2b1dfd"
EXPIRY_MINUTES = 5

# === API Endpoints ===
CONSENT_API_BASE = "https://consent-api.onetrust.com/v2"
PRIVACY_PORTAL_BASE = "https://privacyportal.onetrust.com"

# === Request Headers ===
HEADERS = {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Authorization": f"Bearer {API_TOKEN}"
}

def generate_realtime_consent_jwt(identifier: str, key: str, expiry_minutes: int) -> str:
    try:
        current_time = datetime.datetime.now(datetime.UTC)
        payload = {
            "sub": identifier,
            "iat": current_time,
            "exp": current_time + datetime.timedelta(minutes=expiry_minutes)
        }
        token = jwt.encode(payload, key, algorithm="HS256")
        return token
    except Exception as e:
        logger.error(f"Failed to generate JWT: {str(e)}")
        raise

def get_collection_point_token() -> str:
    try:
        url = f"{API_HOST}/api/consentmanager/v1/collectionpoints/{COLLECTION_POINT_ID}/token?version={COLLECTION_POINT_VERSION}"
        response = requests.get(url, headers=HEADERS)
        response.raise_for_status()
        return response.json()['token']
    except requests.RequestException as e:
        logger.error(f"Failed to get collection point token: {str(e)}")
        raise

def submit_consent_receipts(collection_token: str) -> Dict[str, Any]:
    try:
        url = f"{PRIVACY_PORTAL_BASE}/request/v1/consentreceipts"
        payload = {
            "requestInformation": collection_token,
            "identifier": IDENTIFIER,
            "identifierType": "Email",
            "test": True,
            "purposes": [
                {
                "Id": "3576a591-fd7f-4271-b092-e1aff5c41d27",
                "TransactionType": "CONFIRMED"
                },
                {
                "Id": "0a92b865-f477-4fcf-945e-6067bcb4ede3",
                "TransactionType": "CONFIRMED"
                }
            ],
            "PrivacyNotices": [
                {
                    "Id": "2c1e6ef9-36e0-4660-a06b-95c2ee583104",
                    "Version": 1
                }
            ],
            "dsDataElements": {
                "Email": IDENTIFIER,
                "FirstName": "George",
                "LastName": "Burdell"
            }
        }
        response = requests.post(url, json=payload, headers=HEADERS)
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        logger.error(f"Failed to submit consent receipts: {str(e)}")
        raise

def get_data_subject_preferences(jwt_token: str) -> Dict[str, Any]:
    try:
        url = f"{CONSENT_API_BASE}/preferences"
        headers = HEADERS.copy()
        headers["Authorization"] = f"Bearer {jwt_token}"
        headers["identifier"] = IDENTIFIER
        headers["tenantId"] = TENANT_ID
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        logger.error(f"Failed to get data subject preferences: {str(e)}")
        raise

def main():
    """Main execution function."""
    try:
        # Generate JWT token
        logger.info("Generating JWT token...")
        jwt_token = generate_realtime_consent_jwt(IDENTIFIER, PUBLIC_KEY, EXPIRY_MINUTES)
        logger.info("JWT token generated successfully")

        # Get collection point token
        logger.info("Retrieving collection point token...")
        collection_token = get_collection_point_token()
        logger.info("Collection point token retrieved successfully")

        # Submit consent receipts
        logger.info("Submitting consent receipts...")
        consent_response = submit_consent_receipts(collection_token)
        logger.info("Consent receipts submitted successfully")

        # Wait for processing
        logger.info("Waiting for processing...")
        time.sleep(30)

        # Get data subject preferences
        logger.info("Retrieving data subject preferences...")
        preferences = get_data_subject_preferences(jwt_token)
        logger.info("Data subject preferences retrieved successfully")
        
        # Log final results
        logger.info("Script execution completed successfully")
        logger.debug(f"Preferences response: {preferences}")

    except Exception as e:
        logger.error(f"Script execution failed: {str(e)}")
        raise

if __name__ == "__main__":
    main()
```

```python requirements.txt
requests>=2.31.0
PyJWT>=2.8.0
python-dateutil>=2.8.2
```

```json Response Example
2025-05-13 17:21:54,999 - INFO - Generating JWT token...
2025-05-13 17:21:55,000 - INFO - JWT token generated successfully
2025-05-13 17:21:55,000 - INFO - Retrieving collection point token...
2025-05-13 17:21:55,006 - DEBUG - Starting new HTTPS connection (1): app.onetrust.com:443
2025-05-13 17:21:56,848 - DEBUG - https://app.onetrust.com:443 "GET /api/consentmanager/v1/collectionpoints/f312dd9b-58b4-4f34-b5ff-10b9b464bc4d/token?version=3 HTTP/11" 200 None
2025-05-13 17:21:56,854 - INFO - Collection point token retrieved successfully
2025-05-13 17:21:56,854 - INFO - Submitting consent receipts...
2025-05-13 17:21:56,856 - DEBUG - Starting new HTTPS connection (1): privacyportaltrial.onetrust.com:443
2025-05-13 17:21:57,449 - DEBUG - https://privacyportal.onetrust.com:443 "POST /request/v1/consentreceipts HTTP/11" 200 None
2025-05-13 17:21:57,456 - INFO - Consent receipts submitted successfully
2025-05-13 17:21:57,456 - INFO - Waiting for processing...
2025-05-13 17:22:01,462 - INFO - Retrieving data subject preferences...
2025-05-13 17:22:01,464 - DEBUG - Starting new HTTPS connection (1): consent-api.onetrust.com:443
2025-05-13 17:22:02,060 - DEBUG - https://consent-api.onetrust.com:443 "GET /v2/preferences HTTP/11" 200 None
2025-05-13 17:22:02,066 - INFO - Data subject preferences retrieved successfully
2025-05-13 17:22:02,066 - INFO - Script execution completed successfully
2025-05-13 17:22:02,066 - DEBUG - Preferences response: [{'identifier': 'gpburdell@onetrust.com', 'identifierType': 'Email', 'dataElements': {'Email': 'gpburdell@onetrust.com', 'FirstName': 'George', 'LastName': 'Burdell'}, 'additionalIdentifiers': {}, 'purposes': [{'id': '0a92b865-f477-4fcf-945e-6067bcb4ede3', 'version': 1, 'status': 'ACTIVE', 'consentDate': '2025-05-13T21:21:57.421910774Z', 'customPreferences': [], 'lastInteractionDate': '2025-05-13T21:21:57.421910774Z'}, {'id': '83a5d348-86f3-401d-a744-f3ecb923706a', 'version': 1, 'status': 'ACTIVE', 'consentDate': '2023-11-28T16:29:42.643Z', 'customPreferences': [], 'lastInteractionDate': '2023-11-28T16:29:42.643Z'}, {'id': '3576a591-fd7f-4271-b092-e1aff5c41d27', 'version': 1, 'status': 'ACTIVE', 'consentDate': '2025-05-13T21:21:57.421910774Z', 'customPreferences': [], 'lastInteractionDate': '2025-05-13T21:21:57.421910774Z'}, {'id': 'c50d0577-bcc3-42b6-94d5-c2207468fecd', 'version': 10, 'status': 'EXPIRED', 'consentDate': '2023-06-20T15:00:26.343Z', 'customPreferences': [], 'lastInteractionDate': '2023-09-20T00:02:45.027Z'}], 'consentStrings': [], 'metadata': {'lastReceiptDate': '2025-05-13T21:21:57.421910774Z', 'isFullyProcessed': True}}]
```

# Overview

<!-- python@1-194 -->
<!-- python@1-5 -->

The [Get Data Subject's Preferences V2 API](getrealtimepreferences)—nicknamed the Real-Time Consent (RTC) API—is purpose-built to power UI experiences where timely and synchronized consent is critical. Whether you're building your own Trust Center, registration flow, or cross-device CMP experience, this API ensures user preferences are accessible and respected across tabs, browsers, and devices.

**Benefits**

✅ Syncs preferences almost instantly across devices or browser tabs
✅ Ideal for high-sensitivity flows like registration, gated content, or marketing opt-ins
✅ Designed for embeddable UIs: Trust Centers, CMPs, and custom-built consent interfaces
✅ Uses JWT-based auth tailored for UI contexts (no OAuth tokens exposed in front-end code)

# Things to Know

<!-- python@1-194 -->
<!-- python@1-5 -->

- The JWT is not a traditional OAuth 2.0 access token. It is ephemeral and signed using your domain's secret.
- Ensure JWTs are scoped and expire quickly to prevent misuse.
- This API is not paginated or designed for bulk reads. It’s optimized for real-time access to a single data subject’s preference snapshot.
- This is ideal for registration flows where user consent must be validated before continuing (e.g., enabling the "Next" or "Submit" button).

# Create a Real-Time Consent JWT

<!-- python@35-49,114-118 -->
<!-- python@1-5 -->

The [Get Data Subject's Preferences V2 API](getrealtimepreferences) requires a JWT-based authentication token. Unlike OAuth tokens, this JWT is short-lived, contains only the minimum user-identifying claims, and is safe to use in client-side contexts like web or mobile apps.

> ℹ️ 
> 
> JWTs must be generated by your backend—OneTrust does not create them for you. For more information, refer to [creating JWT auth tokens](https://developer.onetrust.com/onetrust/docs/cross-domain-cross-device#creating-jwt-auth-tokens).

This function creates a secure authentication token for the [Get Data Subject's Preferences V2 API](getrealtimepreferences). It takes three inputs:
- An identifier (like an email or cookie ID)
- A secret key (This value is your Public Key, which you need to add to your OneTrust tenant via **Settings > Consent > Public Keys**)
- How long the token should last (in minutes)

The function creates a JWT (JSON Web Token) that contains:
- The user's identifier
- When the token was created
- When the token will expire

**Security Best Practices**
- This function must run on your backend server only
- The secret key should be stored in environment variables, not in code
- The token is short-lived (5 minutes in the example) for security

**Example Usage**
```python
# On your backend server
token = generate_realtime_consent_jwt(
identifier="user@example.com", 
key=os.getenv('ONETRUST_SECRET_KEY'), 
expiry_minutes=5)
```
This token is used to securely authenticate users when they interact with OneTrust's consent features.

> 🚧
>
> Always generate this JWT server-side to prevent leaking your secret. You’ll pass it to the front end and use it in requests to POST consent or GET preferences.

# Send a Consent Receipt

<!-- python@49-96,118-128 -->
<!-- python@1-5 -->

Use the [Create Consent Receipts API](createconsentreceiptusingpost) to submit a user's preference in real-time (e.g., opt-in or opt-out of categories or purposes).

> ℹ️ 
>
> For more details and explanation on these steps, refer to [Submit Consent Receipts & Retrieve Transactions](https://developer.onetrust.com/onetrust/recipes/submit-consent-receipts-retrieve-transactions).

# Wait ~30 seconds

<!-- python@128-132 -->
<!-- python@1-5 -->

Since the [Get Data Subject's Preferences V2 API](getrealtimepreferences) updates preferences in near real-time, include a 30-second buffer before reading back the preference state.

# Read Real-time Preferences

<!-- python@96-110,132-137 -->
<!-- python@1-5 -->

To verify whether consent was successfully processed, retrieve the most up-to-date preference state using the [Get Data Subject's Preferences V2 API](getrealtimepreferences).