# Trip events

> Tell PerfectRide what happens on each trip, in order, and handle our answers.

POST each event to the events URL, signed with path `/events`. Every event has `event`, `event_id` (unique per event), `partner_trip_id`, `pr_trip_id` and `occurred_at`. The full list is in [Events you send](https://docs.perfectride.io/docs/events-you-send).

## Lifecycle

> Diagram: searching, then driver_assigned, driver_arrived, started, completed. From searching a trip can end as no_driver. From driver_assigned or driver_arrived it can be cancelled.

| Event | Moves the trip to | Accepted when the trip is |
|---|---|---|
| `trip.driver_assigned` | driver_assigned | searching, or driver_assigned (reassign before pickup) |
| `trip.driver_arrived` | driver_arrived | driver_assigned |
| `trip.started` | started | driver_assigned or driver_arrived, with the right `pin` |
| `trip.completed` | completed | started |
| `trip.cancelled` | cancelled | Any time before it ends (cash trips have limits, see [Cash trips](https://docs.perfectride.io/docs/cash-trips)) |
| `trip.no_driver` | no_driver | searching |
| `trip.driver_location` | No change | Any time before it ends |
| `trip.arrived_at_stop`, `trip.departed_stop` | No change | started |
| `trip.rider_rated` | No change | completed |

## Send one

**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);
```

## Ordering

- Send events in the order they happened. Trips only move forward.
- An event that arrives before the one it follows (for example `trip.completed` before `trip.started`) gets 409 `retry_later` and is not recorded. Send the earlier event, then retry.
- An event for a state the trip has already passed gets 200 with `result: "ignored"`.
- Once a trip is completed, cancelled or no_driver, only `trip.rider_rated` is taken (after completed).
- `occurred_at` more than 60 seconds before we booked the trip gets 400 `invalid_event`. It is kept as you sent it; the completion time we record is our own clock.

## Our answers

| Our answer | Meaning | You |
|---|---|---|
| 200 `{ "ok": true, "result": "applied" }` | Done | Stop |
| 200 `result: "duplicate"` | We already have this `event_id` | Stop |
| 200 `result: "ignored"` | The trip is already past this state | Stop |
| 409 `retry_later` | It came before an earlier event, or the trip was busy | Retry with backoff |
| 422 `wrong_pin` | Wrong rider code on `trip.started` | Ask the driver again, send a new event |
| 409 `complete_required`, `cancel_not_allowed`, 422 `fee_not_supported` | Cash cancel rules | See [Cash trips](https://docs.perfectride.io/docs/cash-trips) |
| 400, 401, 403, 404, 411, 413 | Fix the request | Do not retry unchanged. See [Errors](https://docs.perfectride.io/docs/errors) |
| 429, 5xx, timeout | Our side | Retry with backoff |

> **Tip:** Backoff: start at 1 second and double, up to 1 hour between tries, for 24 hours. Keep the same `event_id` on every retry so a repeat is a duplicate, never a second event.

## Limits

- 64 KB per event, with a `Content-Length` header.
- 1,200 events a minute per partner. Over that: 429 with `Retry-After`.

## Next

- [Events you send](https://docs.perfectride.io/docs/events-you-send.md): Every trip event PerfectRide accepts at the events URL, with its fields.
- [Rider code (PIN)](https://docs.perfectride.io/docs/rider-code.md): A trip starts only when your driver enters the rider's 4-digit code.
- [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/trip-events
