# Quickstart: your first trip

> Get sandbox keys, answer a quote and a booking, send your first signed event and see it in the portal.

> **Note:** You need portal access. We send it when your application is approved. About 15 minutes once your server can answer HTTPS.

### Step 1: Sign in and get sandbox keys

Open the [partner portal](https://docs.perfectride.io/portal) and sign in with your email and the 6-digit code we email you. In **Setup**, under **Keys**, issue sandbox keys. You get an API key (`prk_test_...`) and a webhook secret, shown once.

**Shell**

```bash
export PR_API_KEY=prk_test_...   # you send it to us as Bearer
export PR_SECRET=...              # the webhook secret: both sides sign with it
```

### Step 2: Connect your sandbox

In **Connect**, save your **Sandbox API URL**, your **Webhook URL** and **Your API key for us** (we send it to you as Bearer). Only an owner can change these.

> **Tip:** No server yet? The [sample server](https://docs.perfectride.io/partner-api/sample-server.md) runs a full trip in one file.

### Step 3: Answer a quote and a booking

Build `POST /quotes` and `POST /trips` (details in [Quotes and booking](https://docs.perfectride.io/docs/quotes-and-booking)). Then press **Run tests** in **Test your API**: we quote, book twice, get and cancel, and send a wrong signature and an old timestamp you must refuse.

**cURL**

```bash
# Call your own sandbox the way PerfectRide does (signed with your secret).
# The signed path is the path after your base URL: /quotes.
TS=$(date +%s)
BODY='{"pickup":{"lat":4.8156,"lng":7.0345,"address":"Hotel Presidential, Aba Road, Port Harcourt"},"dropoff":{"lat":4.8242,"lng":6.9969,"address":"Genesis Centre, GRA Phase 2, Port Harcourt"},"ride_class":"standard","passengers":1,"payment_method":"perfectride"}'
SIG=$(printf '%s' "$TS.POST./quotes.$BODY" | openssl dgst -sha256 -hmac "$PR_SECRET" | sed 's/^.*= //')

curl "$YOUR_BASE_URL/quotes" \
  -H "Authorization: Bearer $KEY_YOU_GAVE_US" \
  -H "Content-Type: application/json" \
  -H "X-PR-Timestamp: $TS" \
  -H "X-PR-Signature: sha256=$SIG" \
  --data-raw "$BODY"
```

**Node**

```javascript
// Express. prVerify is in Keys and signing.
app.post("/quotes", express.raw({ type: "application/json" }), (req, res) => {
  const raw = req.body.toString("utf8");
  if (req.get("authorization") !== `Bearer ${process.env.OUR_KEY}` ||
      !prVerify(process.env.PR_SECRET, "POST", "/quotes", raw, req.headers)) {
    return res.status(401).json({ error: { code: "bad_signature", message: "Signature does not match" } });
  }
  const q = JSON.parse(raw);
  const offer = priceFor(q.pickup, q.dropoff, q.ride_class, q.stops || []); // your own pricing
  if (!offer) return res.json({ available: false }); // no driver: not an error
  res.json({
    quote_id: offer.id,
    price: offer.kobo, // what your own app charges, in kobo
    eta_seconds: offer.etaSeconds,
    expires_at: new Date(Date.now() + 2 * 60_000).toISOString(),
  });
});
```

**Python**

```python
# Flask. pr_verify is in Keys and signing.
from flask import Flask, request, jsonify
import datetime, json, os

app = Flask(__name__)

@app.post("/quotes")
def quotes():
    raw = request.get_data(as_text=True)
    if request.headers.get("Authorization") != f"Bearer {os.environ['OUR_KEY']}" or \
       not pr_verify(os.environ["PR_SECRET"], "POST", "/quotes", raw, request.headers):
        return jsonify(error={"code": "bad_signature", "message": "Signature does not match"}), 401
    q = json.loads(raw)
    offer = price_for(q["pickup"], q["dropoff"], q["ride_class"], q.get("stops", []))  # your own pricing
    if offer is None:
        return jsonify(available=False)  # no driver: not an error
    expires = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=2)
    return jsonify(quote_id=offer.id, price=offer.kobo, eta_seconds=offer.eta_seconds,
                   expires_at=expires.isoformat())
```

**PHP**

```php
<?php
// quotes.php. pr_verify is in Keys and signing.
$raw = file_get_contents('php://input');
header('Content-Type: application/json');
if (($_SERVER['HTTP_AUTHORIZATION'] ?? '') !== 'Bearer ' . getenv('OUR_KEY')
    || !pr_verify(getenv('PR_SECRET'), 'POST', '/quotes', $raw)) {
    http_response_code(401);
    echo json_encode(['error' => ['code' => 'bad_signature', 'message' => 'Signature does not match']]);
    exit;
}
$q = json_decode($raw, true);
$offer = price_for($q['pickup'], $q['dropoff'], $q['ride_class'], $q['stops'] ?? []); // your own pricing
if (!$offer) { echo json_encode(['available' => false]); exit; } // no driver: not an error
echo json_encode([
    'quote_id' => $offer['id'],
    'price' => $offer['kobo'],
    'eta_seconds' => $offer['eta_seconds'],
    'expires_at' => gmdate('Y-m-d\TH:i:s\Z', time() + 120),
]);
```

### Step 4: Send trip.driver_assigned

In **Certification**, press start. We book test trips in your sandbox and list each one with its `pr_trip_id` and PIN. Copy the id of the first trip and send `trip.driver_assigned` for it.

**cURL**

```bash
TS=$(date +%s)
NOW=$(date -u +%Y-%m-%dT%H:%M:%SZ)
PR_TRIP_ID=pr_xxxx   # the test trip from the portal
BODY='{"event":"trip.driver_assigned","event_id":"ev_0001","partner_trip_id":"t_9931","pr_trip_id":"'"$PR_TRIP_ID"'","occurred_at":"'"$NOW"'","driver":{"id":"d_771","name":"Musa A.","phone":"+2348090001122"},"vehicle":{"make":"Toyota","model":"Corolla","color":"Black","plate":"PHC-123-AB"},"eta_seconds":240}'
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
// Node 18+. prSign is in Keys and signing.
const body = JSON.stringify({
  event: "trip.driver_assigned",
  event_id: "ev_0001",
  partner_trip_id: "t_9931",
  pr_trip_id: process.argv[2], // from the portal's test trip
  occurred_at: new Date().toISOString(),
  driver: { id: "d_771", name: "Musa A.", phone: "+2348090001122" },
  vehicle: { make: "Toyota", model: "Corolla", color: "Black", plate: "PHC-123-AB" },
  eta_seconds: 240,
});

const res = await fetch("https://www.perfectride.io/api/partner/v1/events", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.PR_API_KEY}`,
    "Content-Type": "application/json",
    ...prSign(process.env.PR_SECRET, "POST", "/events", body),
  },
  body,
});
console.log(res.status, await res.json()); // 200 { ok: true, result: "applied" }
```

**Python**

```python
# pip install requests. pr_sign is in Keys and signing.
import json, os, sys, datetime, requests

body = json.dumps({
    "event": "trip.driver_assigned",
    "event_id": "ev_0001",
    "partner_trip_id": "t_9931",
    "pr_trip_id": sys.argv[1],  # from the portal's test trip
    "occurred_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
    "driver": {"id": "d_771", "name": "Musa A.", "phone": "+2348090001122"},
    "vehicle": {"make": "Toyota", "model": "Corolla", "color": "Black", "plate": "PHC-123-AB"},
    "eta_seconds": 240,
}, separators=(",", ":"))

headers = {
    "Authorization": f"Bearer {os.environ['PR_API_KEY']}",
    "Content-Type": "application/json",
    **pr_sign(os.environ["PR_SECRET"], "POST", "/events", body),
}
# Send the exact string you signed.
r = requests.post("https://www.perfectride.io/api/partner/v1/events", data=body.encode("utf-8"), headers=headers)
print(r.status_code, r.json())
```

**PHP**

```php
<?php
// pr_sign is in Keys and signing.
$body = json_encode([
    'event' => 'trip.driver_assigned',
    'event_id' => 'ev_0001',
    'partner_trip_id' => 't_9931',
    'pr_trip_id' => $argv[1], // from the portal's test trip
    'occurred_at' => gmdate('Y-m-d\TH:i:s\Z'),
    'driver' => ['id' => 'd_771', 'name' => 'Musa A.', 'phone' => '+2348090001122'],
    'vehicle' => ['make' => 'Toyota', 'model' => 'Corolla', 'color' => 'Black', 'plate' => 'PHC-123-AB'],
    'eta_seconds' => 240,
], JSON_UNESCAPED_SLASHES);

$headers = ['Authorization: Bearer ' . getenv('PR_API_KEY'), 'Content-Type: application/json'];
foreach (pr_sign(getenv('PR_SECRET'), 'POST', '/events', $body) as $k => $v) $headers[] = "$k: $v";

$ch = curl_init('https://www.perfectride.io/api/partner/v1/events');
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => $body, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true]);
echo curl_exec($ch);
```

**Response 200**

```json
{ "ok": true, "result": "applied", "trip_status": "driver_assigned" }
```

### Step 5: See it in the portal

Open **Event log** and press **Refresh**. Your event shows as accepted, or refused with the error code and why. Then play the rest of the test trips to pass certification.

> **Warning:** A 401 `bad_signature` almost always means the signed body is not the exact body sent. Sign the string you send, byte for byte.

## Next

- [Keys and signing](https://docs.perfectride.io/docs/keys-and-signing.md): Which key goes where, and how every request is signed in both directions.
- [Trip events](https://docs.perfectride.io/docs/trip-events.md): Tell PerfectRide what happens on each trip, in order, and handle our answers.
- [Sandbox and test data](https://docs.perfectride.io/docs/sandbox.md): Test against PerfectRide before any rider is involved: portal tests, certification trips and fixed scenarios.

Source: https://docs.perfectride.io/docs/quickstart
