# E-shop verification using OAuth

URL: https://shoptet.dev/addons/documentation/eshop-verification-using-oauth

If you need to authenticate Shoptet administrators using their existing Shoptet credentials—for example, to save specific settings for an individual addon installation—you can utilize the OAuth server functionality.

This authentication mechanism ensures that the user is indeed the legitimate e-shop administrator, eliminating the need to handle their passwords or manage authorization directly.

OAuth serves strictly as an identity verification method and does not support storing data (such as addon settings). You must handle and store such data separately within your own data structure.

The procedure assumes that you have the e-shop ID ( `shopId` ) stored in your database of `API access tokens` . You must ensure you use the correct `API access token` corresponding to the given `shopId` .

The initial step in verifying a user and their associated e-shop involves obtaining the OAuth server URL against which the user's identity will be authenticated.

## 1. Obtaining the OAuth server URL

Enter your settings URL in the addon settings » "Description" tab » "Addon settings URL" field.

If you use the `#SHOP_ID#` placeholder in your URL, it will be replaced with the actual e-shop ID. For example, the URL `https://www.my-server.com/shoptet/addons/my-addon/settings?eshopId=#SHOP_ID#` becomes `https://www.my-server.com/shoptet/addons/my-addon/settings?eshopId=12345` .

If you include the `#LANGUAGE#` placeholder in your URL, it will be replaced with the current language of the e-shop administration. For example, `https://www.my-server.com/shoptet/addons/my-addon/settings?language=#LANGUAGE#` becomes `https://www.my-server.com/shoptet/addons/my-addon/settings?language=cs` .

From the received `eshopId` , find the corresponding `API access token` in your database and call the [Eshop info endpoint](https://api.docs.shoptet.com/shoptet-api/openapi/eshop/geteshopinfo) . In the response, check the field `data.urls[]` and find the object with the `ident` value equal to `oauth` and use the value from the `url` field as the OAuth server URL for the user who was logged in.

Note that the domain may change over time. We recommend registering the `eshop:projectDomain`[webhook](https://api.docs.shoptet.com/shoptet-api/openapi/section/code-lists/webhook-event-types) so you can update the domain in your system as needed.

```php
<?php
$baseOAuthUrl = current(array_filter($response['data']['urls'], function ($url) {
    return $url['ident'] == 'oauth';
}, ARRAY_FILTER_USE_BOTH))['url'];
```

`$baseOAuthUrl` will be something like [https://example.myshoptet.com/action/OAuthServer/](https://example.myshoptet.com/action/OAuthServer/)

## 2. Obtaining the OAuth code (one-time code)

Shoptet supports two methods for obtaining the OAuth code:

- **Full OAuth with redirect** : Redirecting users to Shoptet (recommended if you need to authenticate the Shoptet administrator directly on your website).
- **Simplified OAuth** : The OAuth code is provided directly, for example, within an iframe URL.

### 2.1 Full OAuth with redirect

Redirect the e-shop user to the OAuth server for authentication.

Save the generated URL for the current user (e.g., in the user's session), as you will need this value in the next step.

```php
$_SESSION['base_oauth_url'] = $baseOAuthUrl;
```

Construct the URL to which the user will be redirected.

```php
// $_SESSION['base_oauth_url'] contains the ending slash
$url = $_SESSION['base_oauth_url'] . 'authorize';
```

Add GET parameters to the URL:

```php
// Your client ID in the OAuth server
// This is an example only, the specific value can be found in
// the e-shop administration → Connections → API Partner → Access to API
$param['client_id'] = 'wae54...slekn';
// authorization group in OAuth server, enter 'basic_eshop'
$param['scope'] = 'basic_eshop';
```

To increase the security, add `state` parameter.

```php
$state = uniqid();
$_SESSION["state"] = $state;
$param['state'] = $state;
```

The `state` parameter is optional but **strongly recommended** , as it provides protection against XSRF attacks. Generate a unique `state` value, store it for the current user, and include it in the request to the `OAuth server` . The OAuth server will return this parameter unchanged in its response, allowing you to verify the authenticity of the request (see the verification step below).

Next, add the `response_type` and `redirect_uri` parameters to your request `URL` .

```php
// response_type is always 'code'
$param['response_type'] = 'code';
// returning url (to your server), to which the OAuth server redirects the user after successful verification
// redirect_uri must be entered in addon settings as "URL for user authorization".
// The OAuth server inspects whether the addresses are matching;
// if the address entered in administration does not match with address sent,
// the OAuth server responds with error
$param['redirect_uri'] = 'https://www.my-server.com/shoptet/addon/my-addon/code';
// Then create the url and redirect the user to OAuth server
$url = $url . "?" . http_build_query($param);
header("Location: " . $url);
```

The OAuth server authenticates the user and redirects them back to your specified `redirect_uri` . In the redirected `GET` request, you'll receive the `code` parameter, and optionally, the `state` parameter you previously provided.

```php
$code = $_GET['code'];
$state = $_GET['state'];
// Check state parameters. When the values are different, someone other than you
// initiated the request and your code should not continue.
if ($state != $_SESSION['state']) {
    die('State parameters do not match');
}
```

### 2.2 Simplified OAuth

In this case, you obtain the OAuth code directly from the URL, typically from GET parameters (depending on where you place the `#OAUTH_CODE#` placeholder). For example:

```php
$code = $_GET['code'];
```

The OAuth code is valid for 30 seconds and can be used only once, so exchange it for the OAuth access token right after you receive it.

## 3. Getting the OAuth access token

The next step is to obtain the `OAuth access token` , which provides the identity of the user or e-shop.

note
This `OAuth access token` is different from the token you receive when installing the addon.

The request is sent in the background, without the user's knowledge.

```php
$data = [
    // $code is the value from the GET parameter
    'code' => $code,
    // grant_type is always 'authorization_code'
    'grant_type' => 'authorization_code',
    // Your client id in OAuth server
    // This is an example only, the specific value can be found in
    // e-shop administration → Connections → API Partner → Access to API
    'client_id' => '<your client id>',
    // Your secret string for communication with OAuth server.
    // The specific value can be found in e-shop administration → Connections → API Partner → Access to API.
    // Contact Shoptet, if client_secret is not available (for older API partners, it was not generated automatically)
    'client_secret' => '<your client secret>',
    // redirect_uri must be entered in addon settings as "URL for user authorization".
    // The OAuth server inspects whether the addresses are matching;
    // if the address entered in administration does not match with address sent, the OAuth server responds with error
    'redirect_uri' => 'https://www.my-server.com/shoptet/addon/my-addon/code',
    // Enter 'basic_eshop'
    'scope' => 'basic_eshop'
];
$url = $_SESSION['base_oauth_url'] . 'token';
```

Send a POST request:

```php
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

if ($err) {
    die("CURL Error: " . $err);
}
```

The response will contain the `access_token` in JSON format:

```json
{
    "access_token": "90r3azmxy6dbxzpjfxj237cjt8rp0f4hq6uygone78i4n4zk47xb649pls1097fc0xs501hjhpv9tlj2k9hc6xhutymtthet8dzx0sm1ih7r6ml6gf6hc4dixqn48l0r5qk1ynqp0fvojief30b2f70rnedfcy2zyqhkin326ynvdv404hn1xw8nqct6rkn9h4xm9za2i53pbb8hqkmz37qdpol5yr3dciftn0vl04jfvpxg4l36lnw9vsqdyke",
    "expires_in": 43200,
    "token_type": "bearer",
    "scope": "basic_eshop"
}
```

```php
$response = json_decode($response, TRUE);
$accessToken = $response['access_token'];
```

## 4. Getting the e-shop's identity

To obtain the e-shop's identity, submit a request to the OAuth server with an authorization header containing the OAuth access token.

Construct the request URL:

```php
$url = $_SESSION['base_oauth_url'] . 'resource?method=getBasicEshop';
```

Send the request:

```php
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $accessToken]);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curl);
curl_close($curl);
```

A successful response contains the key `success` with the value `true` .

```json
{
    "success":true,
    "data": {
        "user": {
            "email": "novak@fenix.myshoptet.com",
            "name": "Jan Novak"
        },
        "project": {
            "id": 159834,
            "url": "https://fenix.myshoptet.com/",
            "name": "Fenix"
        }
    }
}
```

The `data.project` object contains the `id` and `url` that identify the e-shop.

```php
$response = json_decode($response, TRUE);
$_SESSION['project_id'] = $response['data']['project']['id'];
```

With the `project_id` , you can link the current user of your application to the e-shop administrator.

### Error Identification

If an error occurs, the response will contain an `error` and `error_description` field:

```json
{
    "error": "You must use `client_secret`. Please contact us to obtain one.",
    "error_description": null
}
```
