# Quickstart

This walks a browser app from a registered `client_id` and a test account
(see [Getting access](/documentation/developers/getting-access/)) to a real
trajectory result in about ten minutes. It runs the [authorization
flow](/documentation/developers/authorization-flow/) in one browser page
and keeps the tokens in memory. A production web app runs the code
exchange and refreshes on its backend ([Tokens](/documentation/developers/tokens/#browser-apps)).

You need:

- A `client_id` from the [developer portal](/app/developers/)
- A `redirect_uri` you registered, such as `http://127.0.0.1:5500/callback`,
  which a registered `http://127.0.0.1/callback` covers ([Testing
  locally](/documentation/developers/getting-access/#testing-locally))
- The page's origin (`http://127.0.0.1:5500` here) registered as a web
  origin. From an unregistered origin the browser can't read our
  responses.
- The page opened at `http://127.0.0.1:<port>`, the host your redirect URI
  names, not at `localhost`. Step 3 keeps the attempt in `sessionStorage`,
  which belongs to one origin, so a page opened at `localhost` can't read
  it back on the callback, and step 4 fails with "state mismatch".
- A Precision Cut Archery account on your app's test accounts list in the
  portal, with an active or trialing subscription

## 1. Discover the endpoints

Don't hardcode our OAuth URLs. Read them from the authorization server's
metadata document once, at startup:

```js
const ISSUER = 'https://api.precisioncutarchery.com';

let metadata; // fetched once per page load
function discover() {
  metadata ??= fetch(ISSUER + '/.well-known/oauth-authorization-server')
    .then((res) => res.json()); // { authorization_endpoint, token_endpoint, ... }
  return metadata;
}
```

`ISSUER` is the one URL known ahead of time: step 4 checks the callback
against it.

## 2. Generate a PKCE pair

A fresh, random `code_verifier` for this attempt, and its S256
`code_challenge`, with the browser's WebCrypto API:

```js
function base64url(bytes) {
  let s = '';
  bytes.forEach((b) => { s += String.fromCharCode(b); });
  return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

function randomVerifier(nBytes = 32) {
  const bytes = new Uint8Array(nBytes);
  crypto.getRandomValues(bytes);
  return base64url(bytes); // 43 characters
}

async function challengeFor(verifier) {
  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
  return base64url(new Uint8Array(digest));
}
```

## 3. Send the user to us to authorize

This redirects the user's browser, keeping this attempt's `state` and
verifier in `sessionStorage`:

```js
const CLIENT_ID = 'your-client-id';
const REDIRECT_URI = 'http://127.0.0.1:5500/callback';
const SCOPE = 'compute:analyze';

async function startConnect() {
  const verifier = randomVerifier();
  const challenge = await challengeFor(verifier);
  const state = randomVerifier(16);

  // Keep these for this attempt only.
  sessionStorage.setItem('pca_verifier', verifier);
  sessionStorage.setItem('pca_state', state);

  const { authorization_endpoint } = await discover();
  const url = new URL(authorization_endpoint);
  url.search = new URLSearchParams({
    response_type: 'code',
    client_id: CLIENT_ID,
    redirect_uri: REDIRECT_URI,
    scope: SCOPE,
    state,
    code_challenge: challenge,
    code_challenge_method: 'S256',
    resource: ISSUER, // optional (RFC 8707); if sent, the issuer
  }).toString();
  location.assign(url.toString());
}
```

Call `startConnect()` from a button click. The user lands on our login and
consent screen, signs in with their test account, and approves your app for
the `compute:analyze` scope.

## 4. Handle the callback

On `REDIRECT_URI`, check `state` and `iss` before trusting the code or
the error:

```js
async function handleCallback() {
  const params = new URLSearchParams(location.search);
  const expectedState = sessionStorage.getItem('pca_state');
  const verifier = sessionStorage.getItem('pca_verifier');
  sessionStorage.removeItem('pca_state');
  sessionStorage.removeItem('pca_verifier');

  if (params.get('state') !== expectedState) {
    throw new Error('state mismatch: refusing this redirect');
  }
  if (params.get('iss') !== ISSUER) {
    throw new Error('unexpected issuer: refusing this redirect');
  }
  if (params.get('error') === 'access_denied') {
    return null; // not connected: offer startConnect() again
  }
  if (params.has('error')) {
    throw new Error(`${params.get('error')}: ${params.get('error_description') || ''}`);
  }

  return exchangeCode(params.get('code'), verifier);
}
```

`access_denied` isn't a failure, and neither is a user who comes back
without any redirect. In both cases, show the button that calls
`startConnect()` again.

## 5. Exchange the code for tokens

```js
async function exchangeCode(code, verifier) {
  const { token_endpoint } = await discover();
  const res = await fetch(token_endpoint, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      redirect_uri: REDIRECT_URI,
      code_verifier: verifier,
      client_id: CLIENT_ID,
      resource: ISSUER, // optional, as in step 3
    }),
  });
  if (!res.ok) {
    const err = await res.json();
    throw new Error(`${err.error}: ${err.error_description || ''}`);
  }
  return res.json(); // { access_token, refresh_token, expires_in, scope, pca_subject, ... }
}
```

You now have an `access_token` good for one hour. See [Tokens](/documentation/developers/tokens/)
for refreshing, storage and revoking on logout.

## 6. Call a ballistics route

One call to `analyze/trajectory`, for a 450 grain arrow (0.0291595095 kg)
launched at 85.5 m/s with a PCA Drag Index of 95. The peep-to-arrow
height is 4 in (0.1016 m), the air is 1.1593323111192901 kg/m³, and the
shot is zeroed at 30 yd (27.432 m) and read at 20, 30, 40 and 50 yd. Every
number goes in as SI units, so the grains, inches and yards are converted:

```js
async function getTrajectory(accessToken) {
  const res = await fetch(ISSUER + '/api/v1/compute/analyze/trajectory', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${accessToken}`,
    },
    body: JSON.stringify({
      model: {
        launchSpeedMetersPerSecond: 85.5,
        dragIndex: 95,
        massKilograms: 0.0291595095,
      },
      sightHeightMeters: 0.1016,
      airDensityKilogramsPerCubicMeter: 1.1593323111192901,
      ranges: { type: 'list', values: [18.288, 27.432, 36.576, 45.72] },
      zeroRangeMeters: 27.432,
    }),
  });
  if (!res.ok) {
    const problem = await res.json();
    throw new Error(`${problem.code}: ${problem.detail || ''}`);
  }
  return res.json();
}
```

The same call with curl:

```bash
curl https://api.precisioncutarchery.com/api/v1/compute/analyze/trajectory \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": { "launchSpeedMetersPerSecond": 85.5, "dragIndex": 95, "massKilograms": 0.0291595095 },
    "sightHeightMeters": 0.1016,
    "airDensityKilogramsPerCubicMeter": 1.1593323111192901,
    "ranges": { "type": "list", "values": [18.288, 27.432, 36.576, 45.72] },
    "zeroRangeMeters": 27.432
  }'
```

Put the three steps together on your callback page:

```js
const tokens = await handleCallback();
if (tokens) {
  const trajectory = await getTrajectory(tokens.access_token);
  console.log(trajectory);
}
```

## 7. Read the result

The response has a `launch` object (the arrow's speed, kinetic energy and
momentum at the launch station) and a `rows` array, one entry per requested
range. For the 20 yd and 30 yd rows of the call above:

```json
{
  "launch": {
    "speedMetersPerSecond": 85.5,
    "kineticEnergyJoules": 106.58165216118749,
    "momentumNewtonSeconds": 2.49313806225
  },
  "rows": [
    { "horizontalPositionMeters": 18.288, "timeSeconds": 0.21702440882378013,
      "speedMetersPerSecond": 82.98925806115452,
      "kineticEnergyJoules": 100.41393409266846,
      "momentumNewtonSeconds": 2.4199260588321865,
      "verticalPositionMeters": 0.08403455933388007, "windDriftMeters": 0 },
    { "horizontalPositionMeters": 27.432, "timeSeconds": 0.32810582878311617,
      "speedMetersPerSecond": 81.71932338867421,
      "kineticEnergyJoules": 97.36429935297095,
      "momentumNewtonSeconds": 2.3828953866856177,
      "verticalPositionMeters": 9.43435007694708e-05, "windDriftMeters": 0 }
  ]
}
```

A row's `verticalPositionMeters` is the arrow's height above the horizontal
through the peep, so it is about zero at the 27.432 m zero. [Ballistics
concepts](/documentation/developers/concepts/) says what the fields mean,
and the [OpenAPI
document](/documentation/developers/calling-the-api/#openapi-document) has
the rest.
