> For the complete documentation index, see [llms.txt](https://docs.agego.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.agego.com/integration/integration/s2s-integration.md).

# S2S Integration

The Server-to-Server (S2S) integration allows your backend to fully control when and how users are sent to AgeGO for age verification.

This integration does not require any frontend code and is ideal if you want to manage age verification entirely from your server-side logic, including routing, session handling, and access control.

## <mark style="color:$primary;">When to Use S2S Integration</mark>

S2S is recommended if you:

* Want full backend control over the verification flow.
* Prefer redirects over frontend modals.
* Already manage user sessions and access logic server-side.
* Need a clear separation between your frontend and verification logic.

## <mark style="color:$primary;">High-Level Flow</mark>

At a high level, the S2S integration works as follows:

1. Your backend determines that a visitor requires age verification.
2. Your server redirects the user to AgeGO for verification.
3. The user completes the configured verification checks on AgeGO.
4. AgeGO redirects the user back to your site.
5. Your backend validates the response and grants or denies access accordingly.

## <mark style="color:$primary;">Prerequisites</mark>

Before implementing S2S integration, ensure you have:

* An active AgeGO site configured in the dashboard (Name, Website URL, Callback URL, Site Status).
* Your `asi`.
* An HTTPS endpoint on your side to receive the user after verification.

## <mark style="color:$primary;">Get Your S2S Start URL</mark>

Each AgeGO site has a unique S2S start URL available in the dashboard.

![](https://content.gitbook.com/content/1v2DbmntPqhCff92tEVb/blobs/q12Fn2Bp8J9gqLe681Nv/image)

## <mark style="color:$primary;">Redirecting the User to AgeGO</mark>

When your website determines that a user must be age verified (for example, on first visit or before accessing restricted content), your backend redirects the user to the AgeGO S2S start URL.

This redirect URL is unique per site and supports several query parameters to control security, routing, and user experience.

### <mark style="color:$info;">Redirect Parameters</mark>

* `asi` (mandatory): The unique identifier of your site in AgeGO. This value links the verification request to the correct site configuration.
* `returnto` (optional, recommended): Defines the HTTPS URL where the user is redirected after the age-verification flow completes.
  * When provided, AgeGO redirects the user to this URL after verification.
  * When omitted, AgeGO redirects the user to the root of your Site’s Website URL.
  * When used, this must be a full HTTPS URL pointing to a specific page on your domain.

Using `returnto` is strongly recommended to maintain control over post-verification routing.

**Example with `returnto` :**

{% code overflow="wrap" expandable="true" %}

```
https://myapi.agego.com/s2s/start/?asi=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&returnto=https%3A%2F%2Fwww.example.com%2Fmembers%2Fwelcome
```

{% endcode %}

**Without `returnto` (falls back to Site’s Website URL root):**

{% code overflow="wrap" expandable="true" %}

```
https://myapi.agego.com/s2s/start/?asi=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```

{% endcode %}

* `nonce`: Optional, a random hexadecimal value that will be sent in return request to prevent session tampering and sharing. This value can be saved with user session and used later to verify the returning visitor has the same session. nonce MUST be 64 characters or less.
* `callbacktoken`: Optional, value that will be replaced in the site callback url {`callbacktoken`}. callbacktoken MUST be 64 characters or less.
* `redirect`: The redirect parameter controls which page the user is sent to when the flow starts. The following values are supported:
  * `myaccount`: When set to myaccount, the user is redirected to the My Account page after logging in.
    * If the user is already logged in, they are taken directly to My Account.
    * If the user is not logged in, they are first sent to the login page. After logging in, the flow proceeds to My Account.
    * Verification logic remains unchanged:
      * If the user is not verified, they are redirected to the Verification Methods page.
      * If the user is verified, they proceed normally.
  * `login`: When set to `login`, the user is redirected directly to the login page instead of the usual starting page of the flow. After logging in:
    * If the user is not verified, they are sent to the Verification Methods page.
    * If the user is verified, they continue through the standard flow.
  * Default value: If no value is provided, the user lands on the default starting page of the flow.

### <mark style="color:$info;">Important Notes</mark>

* Redirect parameters apply only to the Server-to-Server (S2S) integration.
* The hostname used in `returnto` must be whitelisted in your site settings.
* Redirect behavior in S2S differs from the Modal integration.
* If Modal Close (X) is enabled for your site in the Dashboard, it will not show a close button in your S2S integration. This setting only applies to the overlay (modal) integration. In S2S, the verification flow is a redirect, and allowing users to "close" partway through could cause redirect loops, so the close option is intentionally not available in this mode. The toggle can still be saved for a site using S2S, but it has no effect on the flow.

**Example redirect URL:**

**Base redirect URL from My Sites:**

{% code overflow="wrap" %}

```
https://myapi.agego.com/s2s/start/?asi=YOUR_ASI&returnto=YOUR_RETURN_URL&nonce=OPTIONAL_NONCE&callbacktoken={callbacktoken}
```

{% endcode %}

**Redirect URL with the optional `redirect` parameter:**

{% code overflow="wrap" %}

```
https://myapi.agego.com/s2s/start/?asi=YOUR_ASI&returnto=YOUR_RETURN_URL&nonce=OPTIONAL_NONCE&callbacktoken={callbacktoken}&redirect=myaccount
```

{% endcode %}

After verification, the user is redirected back to:

* the URL specified in `returnto` (if provided), or
* the root of your site’s Website URL.

Your backend should:

* Parse the returned query or fragment parameters.
* Verify the integrity of the response (`ag_signature`).
* Validate the `nonce` (if used).
* Map the result to the correct user or session.
* Grant or deny access accordingly.

#### <mark style="color:$primary;">Return Parameters</mark>

The redirect back to your site includes the following GET parameters describing the verification result:

* `ag_error`: Error code, if any (see below for possible error codes).
* `ag_expires`: UNIX timestamp in milliseconds after which this request must be considered as expired.
* `ag_nonce`: Value initially sent with nonce parameter in redirect url, none if no value was sent.
* `ag_verified`: Yes if the visitor was successfully age-verified, no otherwise.
* `ag_verified_site`: unique id of the website the visitor was verified for, must match the id of the site for the asi parameter in the initial request.
* `ag_user_token`: a JWT identifying the verified user. If you sent a `nonce` in the redirect URL, the token contains a `nonce` claim equal to `ag_nonce`. If no nonce was sent, the claim is not included.

In addition to above, the following two parameters are sent to verify the information sent with the redirect has not been tampered with and is in fact sent by AgeGO platform.

* `ag_signature`: HMAC checksum of `ag_error`, `ag_expires`, `ag_nonce`, `ag_verified` and `ag_verified_site`, in this order, separated by a vertical bar.
* `ag_signature_algo`: Hash algorithm used for the signature. Currently, the only possible value for this parameter is sha256, however, in future, a different algorithm might be used - all users will be notified about any signing algorithm changes in advance.

`ag_user_token` is not part of the `ag_signature` HMAC. To confirm that the token belongs to this signed response, validate it with the AgeGO API and send the `nonce` and `site_id` of the same response (see Validating `ag_user_token` with the AgeGO API below).

Other optional parameters that might or might not be present in return request:

* `ag_remember_me`: Optional, values yes, or no. Indicates strong user preference to persist the verification result beyond normal session lifetime. Value yes indicates user prefers to persist verification status beyond session lifetime, ex. for 1 year.

### <mark style="color:$info;">Overlay S2S Mode</mark>

Enables server-to-server (S2S) verification mode. When set to true, the AgeGO prompt expects age verification results to be provided via URL query parameters (such as `ag_user_token` and `ag_verified`, or `ag_token`).

It is intended for use cases where verification is handled externally and the result is returned to the frontend, typically through cross-site verification flows or post verification redirects.

If valid parameters are present, the user is considered verified, the `agego_aver` cookie is set with the values from the query parameters, and no overlay or modal is ever shown.

Both `ag_user_token` (with `ag_verified`=yes) and `ag_token` are supported for verification in this mode.

{% hint style="warning" %}
It is not required for standard S2S integrations and should only be used when verification results are returned to the frontend.
{% endhint %}

{% code overflow="wrap" expandable="true" %}

```html
<!-- AgeGO Age verification -->
<script src="https://verifycdn.agego.com/v2/verify.js"></script>
<script>
  window.AGEGO = window.AGEGO || function () {
    (AGEGO.e = AGEGO.e || []).push(arguments);
  };

  AGEGO('init', {
    s2sMode: true,
    // ... other options
  });
  AGEGO('launch');
</script>
```

{% endcode %}

{% hint style="info" %}
If you also need to share the `agego_aver` cookie across subdomains while using s2sMode, the same `domain` configuration described in [Modal Integration → Cookie Options](https://docs.agego.com/integration/integration/modal-integration-overlay.md#cookie-options) applies.
{% endhint %}

## <mark style="color:$primary;">Verifying the Signature</mark>

All return requests will always be accompanied with `ag_signature` parameter that contains a keyed hash value using HMAC hashing method.

The hash is computed on all values in return request listed below, separated by vertical bar, and in the exact order as specified below:

```csharp
ag_error | ag_expires | ag_nonce | ag_verified | ag_verified_site
```

The secret used to calculate the HMAC can be found in "My Sites" section for each individual site.

### <mark style="color:$info;">Important Security Checks</mark>

* Always verify if `ag_signature_algo` contains the permitted value(s) as documented above.
* A string none is used to indicated default/missing values, for example, for `ag_nonce`, `ag_error` and similar.
* Always verify that `ag_expires` timestamp value is in the future.
* Using `nonce` is not mandatory but is recommended to prevent sharing of the verification URL.
* If you use `nonce`, also bind `ag_user_token` to the response: call `validate-token` with `nonce` = `ag_nonce` and `site_id` = `ag_verified_site`. This stops a valid token from another verification from being paired with a genuine signed response.
* Keep your site secret value private and not accessible in frontend code. Leaked site secret will allow for anyone to impersonate age verification responses and bypass the verification process.

## <mark style="color:$primary;">Possible Error Codes</mark>

* `none`: Indicates no error.
* `suspended`: The site is suspended or inactive. [Contact Support](https://docs.agego.com/support/support.md) if you think this is an error.

### <mark style="color:$info;">Code Examples for Signature Calculation</mark>

Minimal code examples to illustrated signature verification process of the return request.

**PHP**

{% code overflow="wrap" expandable="true" %}

```php
$data = sprintf(
    '%s|%s|%s|%s|%s',
    $query['ag_error'],
    $query['ag_expires'],
    $query['ag_nonce'],
    $query['ag_verified'],
    $query['ag_verified_site']
);

$expectedSignature = hash_hmac('sha256', $data, $siteSecret);

$status = $query['ag_signature'] === $expectedSignature;

// TODO: check if $status === true
```

{% endcode %}

**Python**

{% code overflow="wrap" expandable="true" %}

```python
import hmac
import hashlib

if query.ag_signature_algo == 'sha256':
    algo = hashlib.sha256
else:
    raise Exception('Invalid hash algorithm')

data = '%s|%s|%s|%s|%s' % (
    query.ag_error,
    query.ag_expires,
    query.ag_nonce,
    query.ag_verified,
    query.ag_verified_site
)

status = hmac.new(site_secret, data, algo).hexdigest() == query.ag_signature

# TODO: check if status == True
```

{% endcode %}

**NodeJs**

{% code overflow="wrap" expandable="true" %}

```js
const crypto = require('crypto');

const data =
  query['ag_error'] + '|' +
  query['ag_expires'] + '|' +
  query['ag_nonce'] + '|' +
  query['ag_verified'] + '|' +
  query['ag_verified_site']
;

const hmac = crypto.createHmac(signatureAlgo, siteSecret);
hmac.update(data);
const status = hmac.digest('hex') === query['ag_signature'];

// TODO: check if status === true
```

{% endcode %}

**Ruby**

{% code overflow="wrap" expandable="true" %}

```ruby
require 'openssl'

data = "#{query['ag_error']}|" \
       "#{query['ag_expires']}|" \
       "#{query['ag_nonce']}|" \
       "#{query['ag_verified']}|" \
       "#{query['ag_verified_site']}"

digest = OpenSSL::Digest.new(signature_algo)

status = OpenSSL::HMAC.hexdigest(digest, site_secret, data) == signature

# TODO: check if status === true
```

{% endcode %}

## <mark style="color:$primary;">Validating</mark> <mark style="color:$primary;">`ag_user_token`</mark> <mark style="color:$primary;">with the AgeGO API</mark>

```
POST https://myapi.agego.com/authorization/user/validate-token
```

Use the `ag_user_token` returned by the S2S callback as the value of `token`.

**Request body (JSON)**

<table data-header-hidden><thead><tr><th width="186.06158447265625" align="center"></th><th width="130.00439453125" align="center"></th><th align="center"></th></tr></thead><tbody><tr><td align="center"><mark style="color:$primary;">Parameter</mark></td><td align="center"><mark style="color:$primary;">Required</mark></td><td align="center"><mark style="color:$primary;">Description</mark></td></tr><tr><td align="center">token</td><td align="center">Yes</td><td align="center">JWT returned after successful verification.</td></tr><tr><td align="center">country</td><td align="center">Optional</td><td align="center">ISO 3166-1 alpha-2 country code (e.g. "DE").</td></tr><tr><td align="center">region</td><td align="center">Optional</td><td align="center">ISO 3166-2 subdivision code without the country prefix (e.g. "FL" for Florida/US) — Requires country</td></tr><tr><td align="center">nonce</td><td align="center">Optional</td><td align="center">The <code>ag_nonce</code> of the same response. When sent, the token must contain a matching <code>nonce</code> claim. <code>none</code> or an empty value counts as not sent. Max 256 characters.</td></tr><tr><td align="center">site_id</td><td align="center">Required if nonce is sent</td><td align="center">The <code>ag_verified_site</code> of the same response. Must match the site the token was issued for.</td></tr></tbody></table>

Without `nonce` and `site_id`, the endpoint works as before, so tokens issued before this change stay valid.

Some tokens have no `nonce` claim, because they are not returned with a signed response: tokens from Overlay Remember Me and tokens obtained through a cross-site `ag_token`. Do not send `nonce` for these tokens, or the response will be `Token has no nonce`. When a token is renewed, it keeps its original claim.

When `country` is provided (optionally with `region`), the token is also validated against the user's verification methods for that location.

Call this endpoint when a returning verified user accesses your site and you need to confirm the token is still valid for their current location.

{% hint style="warning" %}
Publishers must not replicate AgeGO's location-validity logic on their side. All location-eligibility checks must go through this endpoint.
{% endhint %}

**Responses**

<table data-header-hidden><thead><tr><th width="89.64068603515625" align="center"></th><th width="159.58331298828125" align="center"></th><th width="500.161376953125" align="center"></th></tr></thead><tbody><tr><td align="center"><mark style="color:$primary;">Status</mark></td><td align="center"><mark style="color:$primary;">Response Body</mark></td><td align="center"><mark style="color:$primary;">Description</mark></td></tr><tr><td align="center">200</td><td align="center">{ "status": true, "message": "Valid token" }</td><td align="center">Token is valid. When country is provided, the verification methods are also accepted for that location</td></tr><tr><td align="center">200</td><td align="center">{ "status": false, "error": "..." }</td><td align="center"><p>Where "..." is one of:</p><p><code>Invalid token</code> — signature invalid or token expired</p><p><code>Invalid token structure</code> — token is missing required claims</p><p><code>User invalid</code> — the user was not found, has logged out or been deleted</p><p><code>No valid verification method for country/region</code> — verification method isn't accepted in the supplied location</p><p><code>Nonce mismatch</code> — the <code>nonce</code> sent does not match the token's claim</p><p><code>Site mismatch</code> — the <code>site_id</code> sent does not match the token's site</p><p><code>Token has no nonce</code> — a <code>nonce</code> was sent but the token has no <code>nonce</code> claim</p></td></tr><tr><td align="center">400</td><td align="center">{ "status": false, "error": "..." }</td><td align="center">Where "..." is one of:<br><code>No token provided</code> — The request is malformed (missing token)<br><code>Token must be a string</code> — <code>token</code> is not a string<br><code>Country is required when region is provided</code> — region supplied without country.<br><code>Site id is required when nonce is provided</code> — <code>nonce</code> supplied without <code>site_id</code>.</td></tr><tr><td align="center">500</td><td align="center">{ "status": false, "error": "Validation failed" }</td><td align="center">Server error during validation</td></tr></tbody></table>

### <mark style="color:$info;">Code Examples for Validating</mark> <mark style="color:$info;">`ag_user_token`</mark> <mark style="color:$info;">with the AgeGO API</mark>

Minimal code examples to illustrate user token validation process using AgeGO API.

**PHP**

{% code overflow="wrap" expandable="true" %}

```php
$url = 'https://myapi.agego.com/authorization/user/validate-token';

$data = json_encode([
'token' => $query['ag_user_token'],
'nonce' => $query['ag_nonce'],          // optional, binds the token to this response
'site_id' => $query['ag_verified_site'], // required when nonce is sent
'country' => 'DE', // optional
'region' => 'BY'   // optional
]);

$ch = curl_init();

curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => [
  'Content-Type: application/json',
  'Content-Length: ' . strlen($data)
],
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

echo "HTTP Code: $httpCode\n";
echo "Response: $response\n";

$decodedResponse = json_decode($response, true);
if ($decodedResponse['status']) {
  echo "Token is valid\n";
} else {
  echo "Token validation failed: " . $decodedResponse['error'] . "\n";
}

curl_close($ch);
```

{% endcode %}

**NodeJs**

{% code overflow="wrap" expandable="true" %}

```js
const https = require('https');

const url = 'https://myapi.agego.com/authorization/user/validate-token';

const data = JSON.stringify({
token: query.ag_user_token,
nonce: query.ag_nonce,            // optional, binds the token to this response
site_id: query.ag_verified_site,  // required when nonce is sent
country: 'DE', // optional
region: 'BY'   // optional
});

const options = {
method: 'POST',
headers: {
  'Content-Type': 'application/json',
  'Content-Length': Buffer.byteLength(data)
}
};

const req = https.request(url, options, (res) => {
let responseData = '';

res.on('data', (chunk) => {
  responseData += chunk;
});

res.on('end', () => {
console.log(`HTTP Code: ${res.statusCode}`);
console.log(`Response: ${responseData}`);

try {
  const decodedResponse = JSON.parse(responseData);
  if (decodedResponse.status) {
    console.log('Token is valid');
  } else {
    console.log('Token validation failed');
  }
} catch (error) {
  console.log('Error parsing response:', error.message);
}
});
});

req.write(data);
req.end();
```

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.agego.com/integration/integration/s2s-integration.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
