# Keys and signing

> Which key goes where, and how every request is signed in both directions.

## Keys

| Key | Who makes it | Use |
|---|---|---|
| API key | PerfectRide (portal for sandbox) | You send it to us: `Authorization: Bearer prk_test_...`. Live keys start `prk_live_` |
| Webhook secret | PerfectRide, with the API key | Both sides sign with it, one per environment |
| Your API key for us | You | We send it to your API: `Authorization: Bearer <your key>` |

- Sandbox keys come from the portal. Live keys come from PerfectRide when your pilot starts.
- Issuing new sandbox keys stops the old pair at once. Only an owner can do it.
- Keep keys and the secret on your servers, never in an app or browser.

## Headers

**Every request, both directions**

```text
Authorization: Bearer <key>
X-PR-Timestamp: 1764756072
X-PR-Signature: sha256=<hex>

hex = HMAC-SHA256(webhook_secret, "<timestamp>.<METHOD>.<path>.<body>")
```

## What you sign

| Part | Value |
|---|---|
| timestamp | The `X-PR-Timestamp` value: unix seconds |
| METHOD | Upper case: `POST`, `GET` |
| path | The path after the base URL, with the query string: `/quotes`, `/trips/t_9931/cancel`, `/settlements?date=2026-12-03` |
| path, events and supply | `/events` for events you send us, `/supply` for supply reports |
| path, our webhooks | `/` for events we send to your webhook URL, whatever its path |
| body | The raw body bytes, UTF-8. Empty for GET |

> **Warning:** Sign the exact bytes you send. Parsing and re-serialising JSON before you sign or verify changes the bytes and breaks the signature.

## Sign and verify

**cURL**

```bash
# hex = HMAC-SHA256(secret, "<ts>.<METHOD>.<path>.<body>")
TS=$(date +%s)
BODY='{"event":"trip.driver_arrived","event_id":"ev_0003","partner_trip_id":"t_9931","pr_trip_id":"pr_55a9","occurred_at":"2026-12-03T10:05:00Z"}'
SIG=$(printf '%s' "$TS.POST./events.$BODY" | openssl dgst -sha256 -hmac "$PR_SECRET" | sed 's/^.*= //')

curl https://www.perfectride.io/api/partner/v1/events \
  -H "Authorization: Bearer $PR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "X-PR-Timestamp: $TS" \
  -H "X-PR-Signature: sha256=$SIG" \
  --data-raw "$BODY"
```

**Node**

```javascript
const crypto = require("node:crypto");

// hex = HMAC-SHA256(secret, "<ts>.<METHOD>.<path>.<body>")
function prSign(secret, method, path, body, ts = String(Math.floor(Date.now() / 1000))) {
  const hex = crypto
    .createHmac("sha256", secret)
    .update(`${ts}.${method.toUpperCase()}.${path}.${body}`, "utf8")
    .digest("hex");
  return { "X-PR-Timestamp": ts, "X-PR-Signature": `sha256=${hex}` };
}

// Check a request PerfectRide sent you. rawBody is the exact body string.
function prVerify(secret, method, path, rawBody, headers) {
  const ts = String(headers["x-pr-timestamp"] || "");
  const got = String(headers["x-pr-signature"] || "").replace(/^sha256=/i, "").toLowerCase();
  if (!/^\d+$/.test(ts) || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
  const want = prSign(secret, method, path, rawBody, ts)["X-PR-Signature"].slice(7);
  return got.length === want.length && crypto.timingSafeEqual(Buffer.from(got), Buffer.from(want));
}
```

**Python**

```python
import hashlib, hmac, time

# hex = HMAC-SHA256(secret, "<ts>.<METHOD>.<path>.<body>")
def pr_sign(secret: str, method: str, path: str, body: str, ts: str | None = None) -> dict:
    ts = ts or str(int(time.time()))
    msg = f"{ts}.{method.upper()}.{path}.{body}".encode("utf-8")
    hexsig = hmac.new(secret.encode("utf-8"), msg, hashlib.sha256).hexdigest()
    return {"X-PR-Timestamp": ts, "X-PR-Signature": "sha256=" + hexsig}

# Check a request PerfectRide sent you. raw_body is the exact body, decoded as UTF-8.
def pr_verify(secret: str, method: str, path: str, raw_body: str, headers) -> bool:
    ts = headers.get("X-PR-Timestamp", "")
    got = headers.get("X-PR-Signature", "").lower().removeprefix("sha256=")
    if not ts.isdigit() or abs(time.time() - int(ts)) > 300:
        return False
    want = pr_sign(secret, method, path, raw_body, ts)["X-PR-Signature"][7:]
    return hmac.compare_digest(got, want)
```

**PHP**

```php
<?php
// hex = HMAC-SHA256(secret, "<ts>.<METHOD>.<path>.<body>")
function pr_sign(string $secret, string $method, string $path, string $body, ?string $ts = null): array {
    $ts = $ts ?? (string) time();
    $hex = hash_hmac('sha256', $ts . '.' . strtoupper($method) . '.' . $path . '.' . $body, $secret);
    return ['X-PR-Timestamp' => $ts, 'X-PR-Signature' => 'sha256=' . $hex];
}

// Check a request PerfectRide sent you. $rawBody = file_get_contents('php://input').
function pr_verify(string $secret, string $method, string $path, string $rawBody): bool {
    $ts = $_SERVER['HTTP_X_PR_TIMESTAMP'] ?? '';
    $got = strtolower(preg_replace('/^sha256=/i', '', $_SERVER['HTTP_X_PR_SIGNATURE'] ?? ''));
    if (!ctype_digit($ts) || abs(time() - (int) $ts) > 300) return false;
    $want = substr(pr_sign($secret, $method, $path, $rawBody, $ts)['X-PR-Signature'], 7);
    return hash_equals($want, $got);
}
```

## Check our requests

- Check the Bearer key is the one you gave us.
- Refuse a timestamp more than 300 seconds from your clock.
- Compare signatures in constant time.
- Answer 401 with the error body when any check fails. Certification sends one wrong signature: you must answer 401.

**401 body**

```json
{ "error": { "code": "bad_signature", "message": "X-PR-Signature does not match" } }
```

## Test vector

Check your code against this before you call us.

| Input | Value |
|---|---|
| secret | `whsec_test_123` |
| timestamp | `1764756072` |
| method and path | `POST` `/events` |
| body | `{"event":"trip.driver_arrived","event_id":"ev_0003","partner_trip_id":"t_9931","pr_trip_id":"pr_55a9","occurred_at":"2026-12-03T10:05:00Z"}` |
| X-PR-Signature | `sha256=3eddcf9d07a8ef75f99b16e15e7fe500799eb4dfa028032939f6d93108d1b44b` |

## Conventions

|   | Rule |
|---|---|
| Direction | You host the endpoints, PerfectRide calls them. You send events to our events URL |
| Idempotency | Book and cancel carry `Idempotency-Key`. Every event carries a unique `event_id` |
| Money | Integers in kobo. `650000` = ₦6,500. NGN only |
| Time | ISO 8601, UTC |
| Events URL | `https://www.perfectride.io/api/partner/v1/events` |
| Supply URL | `https://www.perfectride.io/api/partner/v1/supply` |
| Body | JSON, at most 64 KB, with a `Content-Length` header (no chunked bodies) |

## Next

- [Quickstart: your first trip](https://docs.perfectride.io/docs/quickstart.md): Get sandbox keys, answer a quote and a booking, send your first signed event and see it in the portal.
- [Trip events](https://docs.perfectride.io/docs/trip-events.md): Tell PerfectRide what happens on each trip, in order, and handle our answers.
- [Errors](https://docs.perfectride.io/docs/errors.md): Every error code we return, why, and how to fix it.

Source: https://docs.perfectride.io/docs/keys-and-signing
