# Installation and Authorization

The same flow runs when a merchant installs your app from the App Store, clicks **Go to app** in the App Store, or opens it from the **Apps** list in the store admin panel:

<Steps>
  <Step from="merchant" to="appstore" title="Installs or buys the app">
    For paid apps, payment is taken first.
  </Step>
  <Step from="appstore" to="panel" title="Redirects to the store's authorization page">
    `https://<store>/panel/auth` with `client_id`, `redirect_uri` and a `state` signed by Ideasoft.
  </Step>
  <Step from="panel" to="merchant" title="Shows the consent screen">
    On first install only. If the app was approved before, this step is skipped.
  </Step>
  <Step from="merchant" to="panel" title="Approves the permissions" />
  <Step from="panel" to="app" title="Redirects to your Redirect URL">
    With `state`, `code`, `domain`, `user_id` and, when present, `renew_date`.
  </Step>
  <Step from="app" title="Verifies the state signature">
    If verification fails, stop the flow and do not request tokens.
  </Step>
  <Step from="app" to="api" title="Exchanges the code for tokens">
    `POST /oauth/v2/token`, within 30 seconds of receiving the `code`.
  </Step>
  <Step from="api" to="app" title="Returns the tokens">
    `access_token` is valid for 24 hours; renew it with `refresh_token` before it expires.
  </Step>
  <Step from="app" to="api" title="Calls the Admin API">
    With the `Authorization: Bearer <access_token>` header.
  </Step>
</Steps>

Later openings run the same flow: the consent screen is skipped and a new `code` arrives every time.

## Parameters sent to your Redirect URL

```http
GET https://your-app.example.com/ideasoft/callback
    ?state=ecde6d7136bde13cf3630938b69f40cb556b7f6f9dfefd22ac703902ca5f2a9d
    &code=NTJlMDRkZWI5ZGFkMDBiOTZjODU1YzY4YjAyNWNmNTJj
    &domain=https%3A%2F%2Fyour-store.myideasoft.com
    &user_id=1
    &renew_date=20270401
```

| Parameter | Description |
|---|---|
| `state` | A 64-character hexadecimal HMAC-SHA256 signature used to verify that the request comes from Ideasoft ([below](#verifying-state)). |
| `code` | Single-use authorization code for obtaining tokens. Valid for **30 seconds**. |
| `domain` | The address of the store that installed or opened the app, including the scheme, e.g. `https://your-store.myideasoft.com`. URL-encoded. |
| `user_id` | ID of the admin panel user who performed the action. **Not** covered by the signature. |
| `renew_date` | Annually renewed products only: renewal date, `YYYYMMDD` ([Renewal date](#renewal-date-renew_date)). |

If the merchant denies access, the redirect carries error parameters instead of a `code`:

```http
GET https://your-app.example.com/ideasoft/callback?error=access_denied&error_description=The+user+denied+access+to+your+application&state=…
```

## Verifying state

`state` is the HMAC-SHA256 signature, keyed with your Client Secret, of a JSON text built from the store address and the date:

```
state = hex( HMAC-SHA256( JSON, client_secret ) )

JSON (without renew_date):
{"domain":"<domain>","date":"<YYYYMMDD>"}

JSON (with renew_date):
{"domain":"<domain>","date":"<YYYYMMDD>","renew_date":"<YYYYMMDD>"}
```

The signed text is PHP `json_encode` output. When reproducing it in your language:

- Key order is fixed: `domain`, `date`, `renew_date`.
- The text contains no whitespace.
- `/` is written as `\/`: `"https:\/\/your-store.myideasoft.com"`. JavaScript's `JSON.stringify` and Python's `json.dumps` do not do this; use the helper in the examples below.
- `date` is the day the signature was produced (Turkey time). It is not sent in the URL; try **today and yesterday** to cover midnight.
- Add `renew_date` only when it is present in the URL.
- Compare in constant time (`hash_equals`, `timingSafeEqual`, `compare_digest`).

Do not request tokens before `state` is verified.

<CodeTabs>

```php title="PHP"
<?php
function ideasoftHmac(array $data, string $clientSecret): string
{
    // With default flags json_encode writes "/" as "\/"
    return hash_hmac('sha256', json_encode($data), $clientSecret);
}

function verifyState(array $query, string $clientSecret): bool
{
    $today = new DateTimeImmutable('now', new DateTimeZone('Europe/Istanbul'));
    foreach ([$today, $today->modify('-1 day')] as $day) {
        $data = ['domain' => $query['domain'] ?? '', 'date' => $day->format('Ymd')];
        if (!empty($query['renew_date'])) {
            $data['renew_date'] = $query['renew_date'];
        }
        if (hash_equals(ideasoftHmac($data, $clientSecret), (string)($query['state'] ?? ''))) {
            return true;
        }
    }
    return false;
}

if (!verifyState($_GET, getenv('IDEASOFT_CLIENT_SECRET'))) {
    http_response_code(403);
    exit('invalid state');
}
```

```js title="Node.js"
import crypto from "node:crypto";

// Same output as PHP json_encode: no whitespace, "/" → "\/", non-ASCII → \uXXXX
const phpJson = (obj) =>
  JSON.stringify(obj)
    .replace(/\//g, "\\/")
    .replace(/[\u007f-\uffff]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));

const ideasoftHmac = (data, clientSecret) =>
  crypto.createHmac("sha256", clientSecret).update(phpJson(data)).digest("hex");

const safeEqual = (a, b) => {
  const x = Buffer.from(a);
  const y = Buffer.from(String(b));
  return x.length === y.length && crypto.timingSafeEqual(x, y);
};

// YYYYMMDD in Turkey time
const ymd = (date) =>
  new Intl.DateTimeFormat("en-CA", { timeZone: "Europe/Istanbul" }).format(date).replaceAll("-", "");

export function verifyState(query, clientSecret) {
  const now = Date.now();
  return [now, now - 86_400_000].some((t) => {
    const data = { domain: query.domain ?? "", date: ymd(new Date(t)) };
    if (query.renew_date) data.renew_date = query.renew_date;
    return safeEqual(ideasoftHmac(data, clientSecret), query.state ?? "");
  });
}
```

```python title="Python"
import hashlib
import hmac
import json
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo


def php_json(obj):
    # Same output as PHP json_encode: no whitespace, "/" → "\/", non-ASCII → \uXXXX
    return json.dumps(obj, separators=(",", ":"), ensure_ascii=True).replace("/", "\\/")


def ideasoft_hmac(data, client_secret):
    return hmac.new(client_secret.encode(), php_json(data).encode(), hashlib.sha256).hexdigest()


def verify_state(query, client_secret):
    now = datetime.now(ZoneInfo("Europe/Istanbul"))
    for day in (now, now - timedelta(days=1)):
        data = {"domain": query.get("domain", ""), "date": day.strftime("%Y%m%d")}
        if query.get("renew_date"):
            data["renew_date"] = query["renew_date"]
        if hmac.compare_digest(ideasoft_hmac(data, client_secret), query.get("state", "")):
            return True
    return False
```

</CodeTabs>

### Test vector

Use these values to check your implementation:

| Input | Value |
|---|---|
| `client_secret` | `example-client-secret` |
| `domain` | `https://your-store.myideasoft.com` |
| `date` | `20260518` |
| Signed text | `{"domain":"https:\/\/your-store.myideasoft.com","date":"20260518"}` |
| `state` | `ecde6d7136bde13cf3630938b69f40cb556b7f6f9dfefd22ac703902ca5f2a9d` |
| `state` with `renew_date=20270401` | `2f2ee2d51b778a3b7060f01227efd140630c2ad56927f665671c5350b1bf258b` |

## Obtaining tokens

After `state` is verified, exchange the `code` for tokens **within 30 seconds**. Send the request to the store given in the `domain` parameter:

```http
POST https://your-store.myideasoft.com/oauth/v2/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&client_id=<client_id>
&client_secret=<client_secret>
&code=<code>
&redirect_uri=<redirect_uri>
```

The returned `access_token` is valid for **24 hours**. Renew it with the `refresh_token` before it expires; the refresh token changes on every renewal. For the full request and response, error codes and the refresh request, see [Authentication](/getting-started/authentication).

Send `client_secret` in the request body, never in the URL.

## Identifying the store and the user

- Identify the store by the `domain` parameter. Because `domain` is part of the `state` signature, it can be trusted after verification. Store your tokens per store.
- `user_id` is not signed; do not use it on its own as proof of identity or authorization.
- Every opening delivers a new `code`. If you already hold valid tokens for the store you do not have to request new ones, but verify `state` on every opening.

## Renewal date (`renew_date`)

For products sold with annual renewal on the App Store, the renewal date is added to the Redirect URL as `renew_date` in `YYYYMMDD` format (e.g. `renew_date=20270401`). When present, `renew_date` is also part of the `state` signature.

:::note{title="May be missing on first install"}
When an app is first installed from the App Store, the renewal date may not exist yet; in that case `renew_date` is not sent. It is sent on the user's later openings of the app.
:::
