# Partner Self-Encoding Guide

URL: https://departcart.com/docs/self-encoding
Updated: 2026-11-17

How to build encrypted DepartCart deeplinks in your own backend with your brand key.

# Partner Self-Encoding Guide

**Audience:** partner engineering teams that build DepartCart deeplinks inside
their own systems.

**Status:** this is the **recommended** way to generate DepartCart deeplinks.
You encode the booking reference yourself with the brand key issued to you at
onboarding, so building a link needs no network call to DepartCart, no bearer
token, and no runtime dependency on our API. It works the same for one link at
checkout and for a batch of thousands.

If you cannot hold a key in a backend service, the
[API-based deeplink guide](/docs/partner-encryption-guide) is a supported
alternative: you send the PNR and last name to DepartCart and receive the link
back. Both produce interchangeable links.

---

## 1. Summary

A DepartCart deeplink carries one opaque parameter, `id`:

```
https://departcart.com/seatmap?id=<ENCODED_ID>&source=cart
https://departcart.com/cart?id=<ENCODED_ID>
https://departcart.com/checkout?id=<ENCODED_ID>
```

`id` is produced in four steps:

| Step | Operation |
|---|---|
| 1 | Build a small JSON payload holding the PNR, a passenger last name, and your brand id |
| 2 | Derive a 32 byte key with PBKDF2-HMAC-SHA256 from your brand password and salt |
| 3 | Encrypt the payload with **Fernet** (AES-128-CBC plus HMAC-SHA256) |
| 4 | Base64url encode the Fernet token **a second time** |

`source` is an optional free-text identifier for where the customer came from. It
is used for return navigation and reporting, and defaults to `cart`.

---

## 2. The payload and its element names

```json
{"pnr": "ABC123", "last_name": "SMITH", "brand": "yourbrand"}
```

The field names are **case sensitive and snake_case**. DepartCart parses the
payload as JSON, so key order and whitespace do not matter, but the names do.

| Element | Type | Required | Rules |
|---------|------|----------|-------|
| `pnr` | string | Yes | Booking reference. Trim whitespace, uppercase. |
| `last_name` | string | Yes | Any passenger's last name on the booking. Trim whitespace, uppercase. |
| `brand` | string | Yes | Your lowercase brand identifier, issued at onboarding. See section 4. |

> **The single most common .NET mistake is here.** `System.Text.Json` and
> `Newtonsoft.Json` both serialize a C# property called `LastName` as `"LastName"`,
> and a camelCase naming policy turns it into `"lastName"`. DepartCart will not find
> either, and the link fails with "Invalid or expired link". Emit exactly
> `last_name`. The sample in section 6 uses an anonymous object with the literal
> field name `last_name`, which sidesteps the whole problem. If you use a class,
> annotate it with `[JsonPropertyName("last_name")]`.

Serialize as UTF-8. No BOM.

> **Last name validation:** DepartCart checks the supplied last name against
> **every** passenger on the PNR, not just the lead traveller. Any passenger's
> surname on the booking works.

---

## 3. Key derivation and key format

```
key_bytes  = PBKDF2-HMAC-SHA256(password   = <your brand password>,
                                salt       = <your brand salt>,
                                iterations = 100000,
                                length     = 32 bytes)
```

| Parameter | Value |
|---|---|
| Algorithm | PBKDF2 with HMAC-SHA256 |
| Iterations | 100000 |
| Output length | 32 bytes |
| Password encoding | Raw ASCII bytes of the issued string, used verbatim |
| Salt encoding | Raw ASCII bytes of the issued string, used verbatim |

Do not hash, trim, normalise, or base64 decode the password or salt before they go
into PBKDF2. They are passed as the literal bytes of the string you were issued.

Fernet splits those 32 bytes into two halves:

```
signing_key    = key_bytes[0..15]     first 16 bytes, used for HMAC-SHA256
encryption_key = key_bytes[16..31]    last 16 bytes, used as the AES-128 key
```

If your Fernet library wants a single key string rather than raw bytes, it wants
the base64url encoding of all 32 bytes, which is 44 characters and ends in `=`:

```
fernet_key = base64url_encode(key_bytes)
```

The derivation is deterministic. Compute it once at startup and cache it. Running
PBKDF2 at 100000 iterations per link is a needless cost.

---

## 4. Your brand parameters

Each partner brand is issued three values at onboarding:

| Value | What it is |
|-------|------------|
| `brand` | Your lowercase brand identifier, written into every payload |
| Password | Input to PBKDF2 (section 3) |
| Salt | Input to PBKDF2 (section 3) |

The password and salt are issued over a secure channel, along with a decode test
vector. They are not published in this document and are not sent by plain email.
The examples here use the placeholder brand `yourbrand`; substitute your own.

Store both in your secret manager, at the same sensitivity as your API secret.
Anyone holding them can mint a valid deeplink for any PNR under your brand.

Keys are isolated per brand. Your key decodes only your brand's links.

---

## 5. Building the Fernet token

Python has `cryptography`. Node has the `fernet` package. .NET has no widely used
Fernet implementation, so the byte layout is spelled out here. It is specification
version `0x80`, with nothing custom added by DepartCart.

```
version    = 0x80                                1 byte
timestamp  = current Unix seconds, big endian    8 bytes, unsigned
iv         = cryptographically random            16 bytes
ciphertext = AES-128-CBC(encryption_key, iv, PKCS7(payload_utf8))
hmac       = HMAC-SHA256(signing_key, version || timestamp || iv || ciphertext)   32 bytes

fernet_token = base64url( version || timestamp || iv || ciphertext || hmac )
id           = base64url( ASCII bytes of fernet_token )
```

Four details that catch people out:

- **The HMAC covers the version, timestamp, and IV as well as the ciphertext.** It
  is not computed over the ciphertext alone.
- **The timestamp is big endian.** .NET is little endian on every platform you will
  run this on, so `BitConverter.GetBytes` needs an `Array.Reverse`. DepartCart does
  not enforce a maximum token age, but send the real current time.
- **The second base64 pass is required.** It is why every valid `id` begins with
  `Z0FBQUFB`, which is base64 of `gAAAAA`, which is base64 of the `0x80` version
  byte. If your output does not start with `Z0FBQUFB`, you skipped step 4.
- **Keep the `=` padding on both passes.** Fernet and DepartCart both expect padded
  base64. Do not use a padding-stripping base64url helper.

Base64url means standard base64 with `+` replaced by `-` and `/` replaced by `_`.

---

## 6. Reference implementations

### Python

Uses the `cryptography` package (`pip install cryptography`), whose `Fernet`
class implements section 5 exactly, so there is no byte layout to get wrong.

```python
import base64
import json
from urllib.parse import quote

from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

BRAND = "yourbrand"               # your brand id
PASSWORD = "<ISSUED_PASSWORD>"    # from your secret manager
SALT = "<ISSUED_SALT>"            # from your secret manager


def derive_fernet_key(password: str, salt: str) -> bytes:
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt.encode("ascii"),
        iterations=100000,
    )
    return base64.urlsafe_b64encode(kdf.derive(password.encode("ascii")))


# Deterministic, so derive once and reuse for the life of the process.
FERNET = Fernet(derive_fernet_key(PASSWORD, SALT))


def encode_id(pnr: str, last_name: str) -> str:
    payload = json.dumps({
        "pnr": pnr.strip().upper(),
        "last_name": last_name.strip().upper(),
        "brand": BRAND,
    }).encode("utf-8")
    fernet_token = FERNET.encrypt(payload)                  # pass 1, padded
    return base64.urlsafe_b64encode(fernet_token).decode()  # pass 2, padded


def decode_id(encoded_id: str) -> dict:
    """For your tests: the inverse of encode_id."""
    return json.loads(FERNET.decrypt(base64.urlsafe_b64decode(encoded_id)))


def seatmap_url(pnr: str, last_name: str, source: str = "cart") -> str:
    return (
        "https://departcart.com/seatmap?id="
        + quote(encode_id(pnr, last_name), safe="")
        + "&source=" + quote(source, safe="")
    )


def cart_url(pnr: str, last_name: str) -> str:
    return "https://departcart.com/cart?id=" + quote(encode_id(pnr, last_name), safe="")


def checkout_url(pnr: str, last_name: str) -> str:
    return "https://departcart.com/checkout?id=" + quote(encode_id(pnr, last_name), safe="")
```

### C#

Verified against the DepartCart decoder. Uses only `System.Security.Cryptography`
and `System.Text.Json`, and compiles on .NET 5 and later as written. It avoids
`Rfc2898DeriveBytes.Pbkdf2` and `RandomNumberGenerator.GetBytes(int)` deliberately,
since both are .NET 6 and later only.

```csharp
using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

public static class DepartCartLink
{
    const string Brand    = "yourbrand";                 // your brand id
    const string Password = "<ISSUED_PASSWORD>";         // from your secret manager
    const string Salt     = "<ISSUED_SALT>";             // from your secret manager

    // PBKDF2-HMAC-SHA256, 100,000 iterations, 32 bytes out.
    // Deterministic, so derive once and reuse for the life of the process.
    static readonly byte[] KeyBytes = DeriveKey();

    static byte[] DeriveKey()
    {
        using (var kdf = new Rfc2898DeriveBytes(
                   Encoding.ASCII.GetBytes(Password),
                   Encoding.ASCII.GetBytes(Salt),
                   100000,
                   HashAlgorithmName.SHA256))
        {
            return kdf.GetBytes(32);
        }
    }

    public static string EncodeId(string pnr, string lastName)
    {
        // Anonymous object, so the JSON field names are literally what is written
        // here. A class with a camelCase naming policy would emit "lastName".
        var payload = JsonSerializer.SerializeToUtf8Bytes(new
        {
            pnr = pnr.Trim().ToUpperInvariant(),
            last_name = lastName.Trim().ToUpperInvariant(),
            brand = Brand,
        });

        var signingKey    = Slice(KeyBytes, 0, 16);   // HMAC-SHA256
        var encryptionKey = Slice(KeyBytes, 16, 16);  // AES-128

        var iv = new byte[16];
        using (var rng = RandomNumberGenerator.Create()) rng.GetBytes(iv);

        byte[] ciphertext;
        using (var aes = Aes.Create())
        {
            aes.Key = encryptionKey;
            aes.IV = iv;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            using (var enc = aes.CreateEncryptor())
                ciphertext = enc.TransformFinalBlock(payload, 0, payload.Length);
        }

        var timestamp = BitConverter.GetBytes(
            (ulong)DateTimeOffset.UtcNow.ToUnixTimeSeconds());
        if (BitConverter.IsLittleEndian) Array.Reverse(timestamp);   // Fernet is big endian

        var body = new byte[1 + 8 + 16 + ciphertext.Length];
        body[0] = 0x80;
        Buffer.BlockCopy(timestamp,  0, body, 1,  8);
        Buffer.BlockCopy(iv,         0, body, 9,  16);
        Buffer.BlockCopy(ciphertext, 0, body, 25, ciphertext.Length);

        byte[] signature;
        using (var hmac = new HMACSHA256(signingKey))
            signature = hmac.ComputeHash(body);      // covers version, timestamp, IV, ciphertext

        var token = new byte[body.Length + 32];
        Buffer.BlockCopy(body,      0, token, 0,           body.Length);
        Buffer.BlockCopy(signature, 0, token, body.Length, 32);

        var fernetToken = Base64Url(token);                          // pass 1
        return Base64Url(Encoding.ASCII.GetBytes(fernetToken));      // pass 2
    }

    public static string SeatmapUrl(string pnr, string lastName) =>
        "https://departcart.com/seatmap?id="
        + Uri.EscapeDataString(EncodeId(pnr, lastName)) + "&source=cart";

    public static string CartUrl(string pnr, string lastName) =>
        "https://departcart.com/cart?id=" + Uri.EscapeDataString(EncodeId(pnr, lastName));

    public static string CheckoutUrl(string pnr, string lastName) =>
        "https://departcart.com/checkout?id=" + Uri.EscapeDataString(EncodeId(pnr, lastName));

    static byte[] Slice(byte[] source, int offset, int length)
    {
        var result = new byte[length];
        Buffer.BlockCopy(source, offset, result, 0, length);
        return result;
    }

    // Base64url, padding retained. Do not switch to a stripping variant.
    static string Base64Url(byte[] data) =>
        Convert.ToBase64String(data).Replace('+', '-').Replace('/', '_');
}
```

Note `Uri.EscapeDataString` on the way into the query string. The `id` ends in `=`
padding, which must be percent encoded as `%3D`.

### Decoding, for your tests

```csharp
public static string DecodeId(string id)
{
    var fernetToken = Encoding.ASCII.GetString(Base64UrlDecode(id));
    var token = Base64UrlDecode(fernetToken);

    var signingKey    = Slice(KeyBytes, 0, 16);
    var encryptionKey = Slice(KeyBytes, 16, 16);

    var body = Slice(token, 0, token.Length - 32);
    var signature = Slice(token, token.Length - 32, 32);

    using (var hmac = new HMACSHA256(signingKey))
    {
        var expected = hmac.ComputeHash(body);
        if (!CryptographicOperations.FixedTimeEquals(expected, signature))
            throw new CryptographicException("Fernet signature mismatch");
    }

    var iv = Slice(body, 9, 16);
    var ciphertext = Slice(body, 25, body.Length - 25);

    using (var aes = Aes.Create())
    {
        aes.Key = encryptionKey;
        aes.IV = iv;
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;
        using (var dec = aes.CreateDecryptor())
            return Encoding.UTF8.GetString(
                dec.TransformFinalBlock(ciphertext, 0, ciphertext.Length));
    }
}

static byte[] Base64UrlDecode(string value) =>
    Convert.FromBase64String(value.Replace('-', '+').Replace('_', '/'));
```

---

## 7. Handing the encoded string to the GTM injectable

Everything above produces an `id` for a link the customer clicks. The GTM
injectable is the other half: it renders the seat selection and refund protect
panels **inside your own page**, and it has to find the same `id` in the DOM to
know which booking it is looking at.

### Put it on the body tag

```html
<body data-encrypted-id="Z0FBQUFBQnFqREVCVzFtRUVQczZOM0Z2NmNfTk5UTXFCY0pnNlVwelFO...">
```

That is the whole integration. Render it server-side into the page your GTM
container fires on, and the injectable picks it up.

### Why the body tag specifically

The loader finds the booking by walking these in order, stopping at the first hit:

| Order | Source |
|---|---|
| 1 | `?id=` or `?encrypted_id=` on the page URL |
| 2 | The first element matching `[data-encrypted-id]`, `[data-booking-id]` or `[data-id]` |
| 3 | `window.bookingData.encryptedId` |
| 4 | A scan of elements whose class or id contains `booking` or `confirmation` |

Step 2 is a single `querySelector`, so it takes the **first matching element in
document order** and then reads whichever of the three attributes that element
has. `data-id` is a very common attribute on booking and confirmation pages. If
anything earlier in your DOM carries one, the loader reads that value, returns
it, and never reaches your tag or `window.bookingData`.

`<body>` precedes every element it contains, so it cannot lose that race. That
is the entire reason for the recommendation.

### Three things that will break it

- **Do not percent encode the attribute value.** Put the raw `id` in, `=`
  padding and all. The loader calls `encodeURIComponent` itself when it posts to
  `/api/booked-seats`, so a value you have encoded yourself arrives double
  encoded, `%3D` becomes `%253D`, and the booking lookup fails.
- **Do not rely on `data-id`.** Use `data-encrypted-id`. It is the most specific
  of the three attribute names and the only one unlikely to collide with
  something your own page already sets.
- **Render it server-side, before the tag fires.** If a script writes the
  attribute after page load, it is a race against the GTM container. Losing that
  race looks exactly like the failure below.

### Verifying the handoff

A missing `id` does **not** produce an error. The seat selection loader falls
back to a built-in demo booking, so a mis-wired tag renders a perfectly
plausible panel showing somebody else's flights. This is the failure mode to
watch for, because nothing on the page looks wrong.

Open the browser console on a real booking page and look for the loader's own
log line:

```text
[AA Seat Loader] Found encrypted ID in page element      <- correct
[AA Seat Loader] Found encrypted ID in URL parameters    <- correct
[AA Seat Loader] Using demo encrypted ID for testing     <- the handoff failed
```

If you see the third line, the attribute was missing, was placed after the tag
fired, or lost the `querySelector` race described above.

Then confirm the panel shows the customer's real flight numbers and dates, not
the demo booking's.

### One booking per page

The loader resolves a single `id` for the whole page. If you render several
bookings on one page, the injectable will attach to whichever it finds first.
Split them across pages, or talk to the integration team about scoping.

---

## 8. Verifying your implementation

A Fernet token embeds a random IV and the current timestamp, so encrypting the same
booking twice gives two different `id` values. **Do not test by comparing your
output against a fixed expected string.** It will never match, and that is correct
behaviour rather than a bug.

Test in the decode direction instead. DepartCart issues a test vector alongside your
credentials: a fixed `id` that must decode to a known payload.

```csharp
var decoded = DepartCartLink.DecodeId(TestVectorId);
// {"pnr": "ABC123", "last_name": "SMITH", "brand": "yourbrand"}
```

If that passes, your key derivation, both base64 passes, and your byte layout are
all correct, and the encode path is correct by symmetry.

Then confirm end to end:

1. Encode a real PNR from your sandbox.
2. Open the resulting `https://departcart.com/seatmap?id=...&source=cart` in a browser.
3. The seatmap should load with the correct flights and passengers.

An "Invalid or expired link" page means the `id` did not decode. In rough order of
likelihood:

| Symptom | Cause |
|---|---|
| `id` does not start with `Z0FBQUFB` | The second base64 pass was skipped |
| `id` decodes locally but fails in the browser | Not percent encoded, so the trailing `=` was lost |
| Signature mismatch on your own decode | HMAC computed over the ciphertext only, or the timestamp written little endian |
| Payload decrypts but the link still fails | Field named `lastName` or `LastName` instead of `last_name` |
| Nothing works at all | PBKDF2 iteration count, or the password or salt passed as something other than raw ASCII bytes |

---

## 9. What the encoded brand does and does not control

The `brand` field in the payload selects which key DepartCart uses to decode the
link. It does **not** select the merchant account, the currency, or pricing.

Those are read from the booking itself when DepartCart retrieves the PNR. A booking
made under your brand prices and settles under your brand regardless of what the
link says. A wrong `brand` value breaks the link rather than misrouting money.

---

## 10. Operational notes

- **Links do not expire.** The `id` stays valid for as long as the booking exists.
  There is no TTL enforced on the token, and the embedded timestamp is not checked
  against a maximum age.
- **Encode at generation time, not at send time.** Nothing in the token depends on
  when the customer opens it, so batch generation is safe.
- **Plan for key rotation to invalidate links already sent.** Do not rely on an
  overlap period during which old and new keys both work. Plan any rotation with
  the integration team, and expect to regenerate outstanding links.
- **Never put the password or salt in client-side code.** Encoding belongs in a
  backend service. A key shipped in a browser bundle or a mobile app is a published
  key.
- **You can mix both integration options freely.** An `id` built locally and an `id`
  returned by the [deeplink API](/docs/partner-encryption-guide) are
  interchangeable, so the API remains available as a fallback.

---

## 11. Support

- Technical Support: [support@departcart.com](mailto:support@departcart.com)
- Integration Team: [integration@departcart.com](mailto:integration@departcart.com)

Ask the integration team for your brand password, salt, and decode test vector.
