> ## Documentation Index
> Fetch the complete documentation index at: https://developers-docs.easyorders.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Get an access token for a merchant's store with OAuth 2.0: the authorization code flow with PKCE.

Your app gets access to a store when the merchant approves it. EasyOrders uses the OAuth 2.0 **authorization code** flow with **PKCE** (`S256`), and both are required on every request.

```mermaid theme={"dark"}
sequenceDiagram
  participant M as Merchant
  participant A as Your app
  participant E as EasyOrders
  A->>M: Redirect to the consent page (client_id, scope, state, code_challenge)
  M->>E: Approves the scopes
  E->>A: Redirect to redirect_uri with code and state
  A->>E: POST /oauth/token (code, code_verifier, client credentials)
  E->>A: access_token, refresh_token, scope, store_id
  A->>E: Admin API calls with Authorization: Bearer
```

## Credentials

When you register your app you get:

| Credential | Looks like | Keep it |
| - | - | - |
| `client_id` | `eo_cid_...` | Public. It names your app. |
| `client_secret` | `eo_sec_...` | Secret, on your server only. It is shown once; rotate it if it leaks. After a rotation the old secret keeps working for 24 hours. |

Redirect URLs must be `https` (except `localhost` while you develop), and they are matched exactly.

## 1. Send the merchant to the consent page

Create a random `state` and a PKCE pair, keep both in the merchant's session, then redirect:

```text theme={"dark"}
https://DASHBOARD-HOST/oauth/authorize
  ?response_type=code
  &client_id=eo_cid_9f3a...
  &redirect_uri=https://app.example.com/auth/callback
  &scope=read_orders write_orders
  &state=xyz123
  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &code_challenge_method=S256
```

| Parameter | |
| - | - |
| `response_type` | Always `code`. |
| `client_id` | Your app's client ID. |
| `redirect_uri` | One of your registered redirect URLs, exactly. |
| `scope` | The scopes you need, space-separated. They must be among your app's registered scopes. See [Scopes](https://developers-docs.easyorders.ai/scopes.md). |
| `state` | A random value. Check that the same value comes back. |
| `code_challenge` | `BASE64URL(SHA256(code_verifier))`, without padding. |
| `code_challenge_method` | Always `S256`. |

```typescript TypeScript theme={"dark"}
import { createHash, randomBytes } from 'node:crypto'

const codeVerifier = randomBytes(32).toString('base64url')
const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url')
const state = randomBytes(16).toString('base64url')
// keep codeVerifier and state in the merchant's session
```

```go Go theme={"dark"}
import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
)

func pkce() (verifier, challenge string) {
	b := make([]byte, 32)
	if _, err := rand.Read(b); err != nil {
		panic(err)
	}
	verifier = base64.RawURLEncoding.EncodeToString(b)
	sum := sha256.Sum256([]byte(verifier))
	return verifier, base64.RawURLEncoding.EncodeToString(sum[:])
}
```

```php PHP theme={"dark"}
<?php

$base64url = fn (string $b) => rtrim(strtr(base64_encode($b), '+/', '-_'), '=');

$codeVerifier = $base64url(random_bytes(32));
$codeChallenge = $base64url(hash('sha256', $codeVerifier, true));
$state = $base64url(random_bytes(16));
// keep $codeVerifier and $state in the merchant's session
```

```python Python theme={"dark"}
import base64
import hashlib
import secrets

code_verifier = secrets.token_urlsafe(32)
code_challenge = base64.urlsafe_b64encode(
    hashlib.sha256(code_verifier.encode()).digest()
).rstrip(b"=").decode()
state = secrets.token_urlsafe(16)
# keep code_verifier and state in the merchant's session
```

The merchant signs in if needed, picks a store when they have more than one, and approves or declines.

## 2. Handle the redirect

EasyOrders sends the merchant back to your `redirect_uri`:

```text theme={"dark"}
# approved
https://app.example.com/auth/callback?code=eo_code_a81f...&state=xyz123

# declined
https://app.example.com/auth/callback?error=access_denied&state=xyz123
```

Check that `state` is the one you sent before you use the code. The code lasts **one minute** and works **once**.

| `error` | Meaning |
| - | - |
| `access_denied` | The merchant declined. |
| `invalid_request` | A parameter is missing or wrong. |
| `invalid_scope` | A scope is not registered for your app. |

A wrong `client_id` or `redirect_uri` never redirects: the merchant sees an error page on EasyOrders.

## 3. Exchange the code for tokens

From your server, `POST https://api.easy-orders.net/oauth/token`. The body is JSON or `application/x-www-form-urlencoded`. Send the client credentials in the body, or as HTTP Basic auth, not both.

```bash cURL theme={"dark"}
curl -X POST "https://api.easy-orders.net/oauth/token" \
  -H "Content-Type: application/json" \
  -d '{
  "grant_type": "authorization_code",
  "client_id": "eo_cid_9f3a...",
  "client_secret": "'"$EASYORDERS_CLIENT_SECRET"'",
  "code": "eo_code_a81f...",
  "redirect_uri": "https://app.example.com/auth/callback",
  "code_verifier": "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
}'
```

```typescript TypeScript theme={"dark"}
const response = await fetch('https://api.easy-orders.net/oauth/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    grant_type: 'authorization_code',
    client_id: process.env.EASYORDERS_CLIENT_ID,
    client_secret: process.env.EASYORDERS_CLIENT_SECRET,
    code,
    redirect_uri: 'https://app.example.com/auth/callback',
    code_verifier: codeVerifier,
  }),
})

const tokens = await response.json()
if (!response.ok) {
  throw new Error(`${tokens.error}: ${tokens.error_description}`)
}
// save tokens.access_token, tokens.refresh_token and tokens.store_id
```

```go Go theme={"dark"}
form := url.Values{}
form.Set("grant_type", "authorization_code")
form.Set("client_id", os.Getenv("EASYORDERS_CLIENT_ID"))
form.Set("client_secret", os.Getenv("EASYORDERS_CLIENT_SECRET"))
form.Set("code", code)
form.Set("redirect_uri", "https://app.example.com/auth/callback")
form.Set("code_verifier", codeVerifier)

res, err := http.PostForm("https://api.easy-orders.net/oauth/token", form)
if err != nil {
	panic(err)
}
defer res.Body.Close()

var tokens struct {
	AccessToken      string `json:"access_token"`
	TokenType        string `json:"token_type"`
	ExpiresIn        int    `json:"expires_in"`
	RefreshToken     string `json:"refresh_token"`
	Scope            string `json:"scope"`
	StoreID          string `json:"store_id"`
	Error            string `json:"error"`
	ErrorDescription string `json:"error_description"`
}
if err := json.NewDecoder(res.Body).Decode(&tokens); err != nil {
	panic(err)
}
if res.StatusCode != http.StatusOK {
	panic(tokens.Error + ": " + tokens.ErrorDescription)
}
```

```php PHP theme={"dark"}
<?php

$ch = curl_init('https://api.easy-orders.net/oauth/token');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS => http_build_query([
        'grant_type' => 'authorization_code',
        'client_id' => getenv('EASYORDERS_CLIENT_ID'),
        'client_secret' => getenv('EASYORDERS_CLIENT_SECRET'),
        'code' => $code,
        'redirect_uri' => 'https://app.example.com/auth/callback',
        'code_verifier' => $codeVerifier,
    ]),
]);

$tokens = json_decode(curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

if ($status !== 200) {
    throw new RuntimeException($tokens['error'] . ': ' . $tokens['error_description']);
}
```

```python Python theme={"dark"}
import os

import requests

response = requests.post(
    "https://api.easy-orders.net/oauth/token",
    data={
        "grant_type": "authorization_code",
        "client_id": os.environ["EASYORDERS_CLIENT_ID"],
        "client_secret": os.environ["EASYORDERS_CLIENT_SECRET"],
        "code": code,
        "redirect_uri": "https://app.example.com/auth/callback",
        "code_verifier": code_verifier,
    },
    timeout=30,
)
tokens = response.json()
if not response.ok:
    raise RuntimeError(f"{tokens['error']}: {tokens['error_description']}")
```

```json Response theme={"dark"}
{
  "access_token": "eo_at_5d0e...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "eo_rt_b73c...",
  "scope": "read_orders write_orders",
  "store_id": "2b7e4f1c-..."
}
```

Save the tokens with the `store_id`: each pair works on that store only.

## 4. Call the Admin API

```bash theme={"dark"}
curl "https://api.easy-orders.net/api/partners-apps/v1/orders" \
  -H "Authorization: Bearer $EASYORDERS_ACCESS_TOKEN"
```

## Refresh the access token

An access token lasts **one hour**. Get a new pair with the refresh token, on the same endpoint:

```json Request theme={"dark"}
{
  "grant_type": "refresh_token",
  "client_id": "eo_cid_9f3a...",
  "client_secret": "eo_sec_7b21c4...",
  "refresh_token": "eo_rt_b73c..."
}
```

The answer has the same shape as the code exchange, with a **new** refresh token. Store it and drop the old one:

* A refresh token lasts **30 days** and works **once**.
* Using an old refresh token again revokes **every** token of the installation, as it means a token leaked. To get tokens again, send the merchant through the consent page again.

> [!WARNING]
>
> If two of your workers can refresh at the same time, let one of them do it (a lock per store), or the second refresh will use a spent token and revoke the installation.

## Revoke

To remove your app from a store, `POST https://api.easy-orders.net/oauth/revoke` with your client credentials and either token. The whole installation ends: every token of it stops working.

```json Request theme={"dark"}
{
  "client_id": "eo_cid_9f3a...",
  "client_secret": "eo_sec_7b21c4...",
  "token": "eo_rt_f204..."
}
```

It answers `200` with no body. A merchant can also remove your app from their dashboard at any time.

## Token endpoint errors

The token and revoke endpoints answer errors the OAuth way:

```json theme={"dark"}
{
  "error": "invalid_grant",
  "error_description": "Authorization code expired"
}
```

| Status | `error` | When |
| - | - | - |
| 400 | `invalid_request` | A parameter is missing, or the client credentials were sent twice. |
| 400 | `invalid_grant` | The code is unknown, used or expired; the `redirect_uri` or `code_verifier` does not match; the refresh token is unknown, expired, revoked or already used. |
| 400 | `unsupported_grant_type` | `grant_type` is not `authorization_code` or `refresh_token`. |
| 401 | `invalid_client` | The client ID or secret is wrong. |

## New scopes

If your app later asks for more scopes, send the merchant through the consent page again. Until they approve, the installation keeps working with the scopes it has.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.