openapi: 3.1.0
info:
  title: ESTO Merchant API
  version: "2.0.0"
  description: |
    ## Introduction

    The ESTO Merchant API lets partner merchants offer hire purchase, Pay
    Later, ESTO X, and ESTO Pay at checkout in Estonia, Latvia, and
    Lithuania. Your backend creates a purchase; ESTO handles identification,
    scoring, contract signing, and payment collection. For integration
    support, contact ESTO through the Partner Portal.

    ## Authentication

    The API uses two independent mechanisms: HTTP Basic auth authenticates
    your request to ESTO, and a MAC signature lets you verify that a
    response or callback actually came from ESTO and wasn't altered in
    transit. You need both.

    ### HTTP Basic auth

    Authenticated endpoints (everything under `/purchase` and `/merchant`)
    require HTTP Basic auth:

    - **Username**: your merchant `shop_id`
    - **Password**: your merchant secret key

    Both are issued in the **Partner Portal**, under Developer Tools. Missing
    or wrong credentials get `401 Unauthorized`; valid credentials for a
    resource owned by a different merchant get `403 Forbidden`. Public
    endpoints — the `/calculate/*` instalment calculators — do not require
    Basic auth.

    ```bash
    curl -u your-shop-id:your-secret-key \
      -X POST \
      -H "Content-Type: application/json" \
      -d '{"amount": 91.89, "reference": "order-1234"}' \
      https://api.esto.ee/v2/purchase
    ```

    ### MAC signature

    ESTO signs the payload in purchase responses and in the status callback
    so you can confirm it's authentic. The algorithm is a straightforward
    salted hash — not HMAC:

    ```
    MAC = UPPERCASE( SHA-512( trim(json_string) + secret_key ) )
    ```

    Take the exact JSON string ESTO sent you (the `data` field on a purchase
    response, or the `json` field on a callback) without re-serializing it,
    trim leading/trailing whitespace, concatenate your secret key directly
    onto the end (no separator), hash with SHA-512, and uppercase the hex
    digest. Compare the result to the `mac` value you received — they must
    match exactly.

    #### PHP

    ```php
    function verifyMac(string $json, string $secretKey, string $mac): bool
    {
        $computed = strtoupper(hash('sha512', trim($json) . $secretKey));

        return hash_equals($computed, $mac);
    }
    ```

    #### Node.js

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

    function verifyMac(json, secretKey, mac) {
      const computed = crypto
        .createHash('sha512')
        .update(json.trim() + secretKey)
        .digest('hex')
        .toUpperCase();

      return computed === mac;
    }
    ```

    Always use a constant-time comparison (`hash_equals` in PHP, or a
    timing-safe compare in Node) rather than `===`/`==` on secrets.

    #### Common mistakes

    - **Re-encoding the JSON before hashing.** Hash the raw string exactly as
      received — never `json_decode` then `json_encode` it again first.
    - **Verifying against the decoded object instead of the string.** The MAC
      is computed over the string, not the object.
    - **Forgetting to trim.** Stray whitespace around the JSON string breaks
      the hash.

    ## IP whitelisting

    If your system requires IP whitelisting, add the following IPs based on
    region:

    - **Estonia** — 3.70.12.52, 18.153.156.231, 3.125.238.167, 63.176.211.49, 18.157.62.6, 3.69.187.42, 18.192.202.237
    - **Latvia** — 3.120.72.230, 63.176.249.208, 3.122.188.177, 3.70.84.234, 18.193.166.74, 52.29.97.78, 3.77.20.36
    - **Lithuania** — 52.57.126.200, 18.157.101.53, 52.29.174.26, 63.176.192.54, 18.158.41.5, 3.79.80.76, 3.121.241.252

    ## Structure of an API request

    All endpoints are relative to `https://api.esto.ee/v2` (the base URL
    updates to match the region selected at the top of the page). Request
    bodies are JSON.

    Set `connection_mode: "test"` to create a test purchase — no real credit
    checks or money take place, the purchase is flagged `is_test: true`, and
    you use the same credentials as for live purchases. Omit the field, or
    set it to `"live"`, for real purchases.

    ## Structure of an API response

    Authenticated purchase endpoints wrap the payload in an envelope:

    ```json
    { "errors": [], "data": "{...}", "mac": "UPPERCASE_SHA512_HEX" }
    ```

    `data` is a **JSON-encoded string** — decode it before reading. On a
    business error, `errors` is populated and `data` is the string `"[]"`
    (the `mac` is then computed over that `"[]"` string). Validation failures
    return HTTP 422; auth failures return 401/403. `GET` metadata endpoints
    and the `/calculate/*` endpoints return plain JSON with no envelope.
externalDocs:
  description: Partner Portal
  url: https://partner.esto.ee
servers:
  - url: https://api.esto.ee/v2
    description: Production
tags:
  - name: Purchase
    description: Create, read, modify, and cancel purchases (hire purchase, Pay Later, ESTO X, ESTO Pay).
  - name: Calculate
    description: Public, unauthenticated instalment calculators. Safe to call from the storefront frontend.
  - name: Merchant
    description: Merchant, cashier, and store metadata.
security:
  - basicAuth: []
paths:
  /purchase:
    post:
      operationId: createPurchase
      tags: [Purchase]
      summary: Create purchase
      description: |
        Creates a hire purchase / Pay Later / ESTO X / ESTO Pay application.
        Send the order details — amount, items, and optionally basic
        customer info — and ESTO returns a `purchase_url`. Redirect the
        customer's browser there to complete identification, scoring, and
        contract signing on ESTO's hosted pages. When the customer finishes,
        ESTO redirects them back to your `return_url`, and separately calls
        your `notification_url` once the final status is known.

        ![Purchase flow](flow.svg)

        Supports all schedule types. ESTO Pay is available **only** on this
        endpoint. If you omit `schedule_type`, the customer sees a chooser
        on the redirect page with whichever types are enabled for your
        merchant account — narrow this down with `display_schedule_types`.

        Optionally pass `payment_method_key` (from
        `GET /purchase/payment-methods`) or `bank_id` to pre-select a
        payment method and skip a step on ESTO's side. Optionally set
        `send_url_message_to_customer` to `SMS` or `EMAIL` to have ESTO send
        the `purchase_url` directly to the customer — requires
        `customer.phone` (for `SMS`) or `customer.email` (for `EMAIL`).

        ```bash
        curl -u your-shop-id:your-secret-key \
          -X POST \
          -H "Content-Type: application/json" \
          -d '{
            "amount": 91.89,
            "reference": "order-1234",
            "return_url": "https://your-site.com/return",
            "notification_url": "https://your-site.com/notification",
            "items": [
              { "name": "Bitcoin 101", "unit_price": 30.30, "quantity": 3 },
              { "name": "The One Ring", "unit_price": 0.99, "quantity": 1 }
            ]
          }' \
          https://api.esto.ee/v2/purchase
        ```

        The response's `data` field (a JSON string — decode it) contains
        `purchase_url`. Redirect your customer there:

        ```json
        {
          "id": 4815162342,
          "status": "CREATED",
          "purchase_url": "https://esto.ee/purchase/vgks90vmd3mg09r0scakk",
          "merchant_reference": "order-1234",
          "amount": 91.89,
          "currency": "EUR",
          "is_test": false
        }
        ```
      security:
        - basicAuth: []
      requestBody:
        $ref: '#/components/requestBodies/StoreRedirectPurchaseRequest'
      responses:
        '200':
          $ref: '#/components/responses/StoreRedirectPurchaseResponse'
      callbacks:
        statusChanged:
          $ref: '#/components/callbacks/MerchantStatusCallback'
  /purchase/local:
    post:
      operationId: createPurchaseLocal
      tags: [Purchase]
      summary: Create purchase (local / embedded flow)
      description: |
        Creates an application using customer details collected directly on
        the merchant's own checkout — including the personal ID code
        (`pin`) — and returns an instant eligibility decision:

        - `POSITIVE` — approved. Redirect the customer to `redirect_url` to
          sign the contract.
        - `PENDING` — needs manual review or more information. Redirect the
          customer to `redirect_url` to continue on ESTO's pages.
        - `NEGATIVE` — rejected. There's no `redirect_url`; show your own
          decline messaging.

        Only `REGULAR`, `ESTO_X`, and `PAY_LATER` schedule types are
        supported here — ESTO Pay is redirect-flow only. Because you collect
        the `pin` and other sensitive personal data yourself, your checkout
        needs to handle that data according to your compliance obligations
        — talk to ESTO if you're unsure what's required.

        `POSITIVE` / `PENDING` / `NEGATIVE` is a separate vocabulary from the
        purchase lifecycle status (`CREATED` / `APPROVED` / `REJECTED` /
        `CANCELLED` / `DELETED`) returned by `GET /purchase/{id}` and the
        redirect flow — don't conflate the two.

        ```bash
        curl -u your-shop-id:your-secret-key \
          -X POST \
          -H "Content-Type: application/json" \
          -d '{
            "amount": 150.00,
            "down_payment": 20.00,
            "period_months": 12,
            "reference": "order-1234",
            "items": [
              { "name": "Banana", "unit_price": 10.00, "quantity": 15 }
            ],
            "customer": {
              "pin": "11412090004",
              "first_name": "Diane",
              "last_name": "Nguyen",
              "email": "email@address.com",
              "phone": "567891234",
              "address": "Hollywoo Blvd. 42",
              "allow_pension_query": true
            }
          }' \
          https://api.esto.ee/v2/purchase/local
        ```

        ```json
        {
          "id": 4815162342,
          "status": "POSITIVE",
          "redirect_url": "https://esto.ee/p/LWYRUP?target=signing&logout=1",
          "terms": {
            "amount": 150,
            "down_payment": 20,
            "period_months": 12,
            "monthly_payment": 15.50
          }
        }
        ```

        The `terms` figures above are illustrative — the actual figures ESTO
        returns depend on the merchant's active campaign terms, not on
        values fixed by this API.
      security:
        - basicAuth: []
      requestBody:
        $ref: '#/components/requestBodies/StoreLocalPurchaseRequest'
      responses:
        '200':
          $ref: '#/components/responses/StoreLocalPurchaseResponse'
      callbacks:
        statusChanged:
          $ref: '#/components/callbacks/MerchantStatusCallback'
  /purchase/payment-methods:
    get:
      operationId: getPaymentMethods
      tags: [Purchase]
      summary: List available payment methods
      description: |
        Returns the payment methods enabled for the authenticated merchant,
        optionally filtered by country. Cache the response for at least 10
        minutes — it changes infrequently.
      security:
        - basicAuth: []
      parameters:
        - name: country_code
          in: query
          required: false
          schema:
            type: string
            enum: [EE, LV, LT, FI]
          example: EE
        - name: test_mode
          in: query
          required: false
          schema:
            type: boolean
            default: false
      responses:
        '200':
          description: List of available payment methods for the merchant.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/PaymentMethod'
              example:
                - key: ESTO_HIRE_PURCHASE_LOAN
                  name: ESTO Regular hire purchase
                  country_code: EE
                  schedule_type: REGULAR
                  type: LOAN
                  logo_url: https://api.esto.ee/images/esto-logo-black.png
                  is_test: false
                - key: ESTO_ESTO_X_LOAN
                  name: ESTO 3
                  country_code: EE
                  schedule_type: ESTO_X
                  type: LOAN
                  logo_url: https://api.esto.ee/images/converting-schedule/esto-x-3.png
                  is_test: false
                - key: ESTO_PAY_LATER_LOAN
                  name: ESTO Pay Later
                  country_code: EE
                  schedule_type: PAY_LATER
                  type: LOAN
                  logo_url: https://api.esto.ee/images/converting-schedule/en-us/pay-later.png
                  is_test: false
        '422':
          description: Invalid country_code.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    example: error
                  message:
                    type: string
                    example: Country code is not allowed or wrong.
                  allowed_countries:
                    type: array
                    items:
                      type: string
  /purchase/{id}:
    get:
      operationId: getPurchase
      tags: [Purchase]
      summary: Get purchase by ID
      description: |
        Returns the current status, terms, basket items, and modification
        history for a purchase. Use this to poll for status, or to
        double-check a callback you received. Only the merchant that owns
        the application can read it.

        | Status | Meaning |
        |---|---|
        | `CREATED` | Just created, or still pending — not yet a final answer. |
        | `APPROVED` | Contract signed. |
        | `REJECTED` | Application rejected. |
        | `CANCELLED` | Application cancelled. |
        | `DELETED` | Application deleted. |
      security:
        - basicAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
          example: 4815162342
      responses:
        '200':
          $ref: '#/components/responses/GetPurchaseResponse'
        '403':
          description: The authenticated merchant does not own this application.
        '404':
          description: Purchase not found.
  /purchase/{id}/modification-request:
    post:
      operationId: createModificationRequest
      tags: [Purchase]
      summary: Request an amount modification
      description: |
        Requests an amount change on an existing purchase — for example,
        after a partial return.

        ```json
        { "reason": "Some items from the purchase were missing", "amount": 123.45 }
        ```

        This queues the request; it does not apply the change immediately.
        Once handled, the change appears in the `modifications` array on
        `GET /purchase/{id}`. Responds with `{"status": "CREATED"}` on
        success, or an `errors` array if it couldn't be queued (for example,
        the purchase is already in a terminal state). Only the merchant that
        owns the purchase can request a modification — the API returns
        `403 Forbidden` otherwise.
      security:
        - basicAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ModificationRequestBody'
            example:
              reason: Some items from the purchase were missing
              amount: 123.45
      responses:
        '200':
          description: Modification request created, or an error describing why it wasn't.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RequestStatusResponse'
              example:
                status: CREATED
  /purchase/{id}/cancellation-request:
    post:
      operationId: createCancellationRequest
      tags: [Purchase]
      summary: Request a purchase cancellation
      description: |
        Requests cancellation of the purchase.

        ```json
        { "reason": "Client returned the purchase" }
        ```

        Same pattern as a modification request: this queues a cancellation
        rather than applying it immediately, and responds with
        `{"status": "CREATED"}` on success, or an `errors` array if the
        request couldn't be queued (for example, the purchase is already in
        a terminal state). Only the merchant that owns the purchase can
        request a cancellation — the API returns `403 Forbidden` otherwise.
      security:
        - basicAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CancellationRequestBody'
            example:
              reason: Client returned the purchase
      responses:
        '200':
          description: Cancellation request created, or an error describing why it wasn't.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RequestStatusResponse'
              example:
                status: CREATED
  /merchant/{shop_id}:
    get:
      operationId: getMerchant
      tags: [Merchant]
      summary: Get merchant, cashier, and store info
      description: |
        Returns cashier and store lists for the merchant. Primarily used by
        POS / plugin integrations that need to populate `cashier_id` or
        `store_id` on a purchase request.
      security:
        - basicAuth: []
      parameters:
        - name: shop_id
          in: path
          required: true
          schema:
            type: string
          example: my-shop
      responses:
        '200':
          description: Merchant info.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MerchantInfo'
              example:
                shop_id: my-shop
                advertiser_id: 999
                cashiers:
                  - id: 901
                    name: John Doe 1
                  - id: 902
                    name: John Doe 2
                stores:
                  - id: 101
                    name: Store 1
                  - id: 102
                    name: Store 2
                ef_region_token: null
        '404':
          description: Merchant not found.
  /merchant/{shop_id}/purchases:
    get:
      operationId: getMerchantPurchases
      tags: [Merchant]
      summary: List merchant purchases
      description: Paginated list of purchases for the merchant, optionally filtered by store.
      security:
        - basicAuth: []
      parameters:
        - name: shop_id
          in: path
          required: true
          schema:
            type: string
        - name: store_id
          in: query
          required: false
          description: Filter by store. Must be a store belonging to this merchant.
          schema:
            type: integer
        - name: page
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            default: 1
      responses:
        '200':
          description: Paginated purchase list.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MerchantPurchasesResponse'
              example:
                data:
                  - id: 4815162342
                    customer_name: BoJack Horseman
                    amount: 91.89
                    is_test: false
                    schedule_type: REGULAR
                    merchant_reference: gwjke9gdsf
                    created_at: "08.07.2026 09:12"
                page: 1
                total: 1
                total_pages: 1
        '403':
          description: The authenticated merchant does not own this shop_id.
        '422':
          description: Validation error (bad store_id or page).
  /calculate/all-payments:
    get:
      operationId: calculateAllPayments
      tags: [Calculate]
      summary: Calculate instalment options for every available period
      description: |
        Public endpoint, no authentication required. CORS-enabled for direct
        calls from the storefront frontend. Cache responses client-side for
        at least 30 minutes per amount/merchant combination.
      security: []
      parameters:
        - name: amount
          in: query
          required: true
          schema:
            type: number
            format: float
            minimum: 0.1
          example: 543.49
        - name: down_payment
          in: query
          required: false
          schema:
            type: number
            format: float
            minimum: 0
            default: 0
        - name: shop_id
          in: query
          required: false
          schema:
            type: string
        - $ref: '#/components/parameters/CalcApproximate'
          description: >-
            When false, figures are exact and reflect the merchant's active campaign.
            Defaults to true, which returns a lighter approximate estimate.
      responses:
        '200':
          description: Monthly payment for every period the merchant offers at this amount.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AllPaymentsResponse'
              example:
                periods:
                  - period: 3
                    monthly_payment: 163.27
                  - period: 12
                    monthly_payment: 45.17
                  - period: 24
                    monthly_payment: 27.10
        '422':
          $ref: '#/components/responses/CalcValidationError'
  /calculate/payment:
    get:
      operationId: calculatePayment
      tags: [Calculate]
      summary: Calculate the payment for one period
      description: Public endpoint, no authentication required. CORS-enabled.
      security: []
      parameters:
        - $ref: '#/components/parameters/CalcAmount'
        - name: period_months
          in: query
          required: false
          description: If omitted, the longest period offered for the amount is used.
          schema:
            type: integer
            minimum: 1
            maximum: 60
        - $ref: '#/components/parameters/CalcDownPayment'
        - $ref: '#/components/parameters/CalcApproximate'
        - $ref: '#/components/parameters/CalcShopId'
      responses:
        '200':
          description: Monthly payment for the requested (or default) period.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SinglePaymentResponse'
              example:
                monthly_payment: 52.69
                period_months: 9
                total_credit: 474.25
        '422':
          $ref: '#/components/responses/CalcValidationError'
  /calculate/periods:
    get:
      operationId: calculatePeriods
      tags: [Calculate]
      summary: List available periods for an amount
      description: Public endpoint, no authentication required. CORS-enabled.
      security: []
      parameters:
        - $ref: '#/components/parameters/CalcAmount'
        - $ref: '#/components/parameters/CalcShopId'
      responses:
        '200':
          description: Periods (in months) available for this amount.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PeriodsResponse'
              example:
                periods: [3, 6, 12, 18, 24]
components:
  securitySchemes:
    basicAuth:
      type: http
      scheme: basic
      description: |
        Username is the merchant `shop_id`, password is the merchant secret
        key. Both are issued in the Partner Portal under Developer Tools. See
        the Authentication section for the full mechanics.
  parameters:
    CalcAmount:
      name: amount
      in: query
      required: true
      schema:
        type: number
        format: float
        minimum: 0.1
      example: 531.99
    CalcDownPayment:
      name: down_payment
      in: query
      required: false
      schema:
        type: number
        format: float
        minimum: 0
        default: 0
    CalcShopId:
      name: shop_id
      in: query
      required: false
      description: Restricts the calculation to a specific merchant's terms/campaigns.
      schema:
        type: string
    CalcApproximate:
      name: approximate
      in: query
      required: false
      description: >-
        When false, figures are the exact computed result. Defaults to true,
        which returns a lighter approximate estimate.
      schema:
        type: boolean
        default: true
  requestBodies:
    StoreRedirectPurchaseRequest:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/StoreRedirectPurchaseBody'
          example:
            amount: 91.89
            reference: fwejigjwe8g32g3jg
            return_url: https://your-site.com/return
            notification_url: https://your-site.com/notification
            cancel_url: https://your-site.com/cancel
            connection_mode: live
            schedule_type: REGULAR
            items:
              - name: Bitcoin 101
                unit_price: 30.30
                quantity: 3
              - name: The One Ring
                unit_price: 0.99
                quantity: 1
            customer:
              first_name: BoJack
              last_name: Horseman
              email: email@address.com
              phone: "567891234"
              address: Hollywoo Blvd. 42
              city: Los Angeles
              post_code: "12345"
            cashier_id: 999
            store_id: 111
    StoreLocalPurchaseRequest:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/StoreLocalPurchaseBody'
          example:
            amount: 150.00
            down_payment: 20.00
            period_months: 12
            reference: fwejigjwe8g32g3jg
            connection_mode: live
            schedule_type: REGULAR
            items:
              - name: Banana
                unit_price: 10.00
                quantity: 15
            customer:
              pin: "11412090004"
              document_nr: A12345678
              document_type: ID_CARD
              is_verified: true
              first_name: Diane
              last_name: Nguyen
              email: email@address.com
              phone: "567891234"
              address: Hollywoo Blvd. 42
              city: Los Angeles
              post_code: "12345"
              occupation_category: STUDENT
              allow_pension_query: true
              is_politically_exposed: false
            cashier_id: 999
            store_id: 111
  responses:
    CalcValidationError:
      description: >-
        Validation failed. `message` summarises the first error; `errors` maps each
        rejected field to its messages.
      content:
        application/json:
          schema:
            type: object
            properties:
              message:
                type: string
              errors:
                type: object
                additionalProperties:
                  type: array
                  items:
                    type: string
          example:
            message: validation.boolean
            errors:
              approximate:
                - validation.boolean
    StoreRedirectPurchaseResponse:
      description: |
        Purchase created. The top-level `data` field is a **JSON-encoded
        string** (not a nested object) containing the purchase payload below;
        decode it before reading. `mac` authenticates that string — see
        the Authentication section.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/StoreRedirectPurchaseEnvelope'
          example:
            errors: []
            data: "{\"id\":4815162342,\"status\":\"CREATED\",\"merchant_reference\":\"fwejigjwe8g32g3jg\",\"merchant_message\":null,\"is_test\":false,\"amount\":91.89,\"schedule_type\":\"REGULAR\",\"currency\":\"EUR\",\"terms\":{\"amount\":91.89,\"down_payment\":0,\"period_months\":3,\"monthly_payment\":30.63,\"total_expected\":91.89,\"annual_interest\":0,\"contract_fee\":0,\"apr\":0},\"cashier_id\":999,\"store_id\":111,\"modifications\":null,\"items\":[],\"notification_url\":\"https://your-site.com/notification\",\"return_url\":\"https://your-site.com/return\",\"purchase_url\":\"https://esto.ee/purchase/vgks90vmd3mg09r0scakk\"}"
            mac: D0F02C03D132D58F26948AAB08001494282D7F358DCED4F3C300D4499FDB67314BF7CE47E16781DEB3DC349F967526DC64033ABAF710A87FFE1C1667C38C4E4D
    StoreLocalPurchaseResponse:
      description: |
        Eligibility decision returned. `data` is a JSON-encoded string, same
        as the redirect flow.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/StoreLocalPurchaseEnvelope'
          example:
            errors: []
            data: "{\"id\":4815162342,\"status\":\"POSITIVE\",\"merchant_reference\":\"fwejigjwe8g32g3jg\",\"merchant_message\":null,\"is_test\":false,\"amount\":150,\"schedule_type\":\"REGULAR\",\"currency\":\"EUR\",\"terms\":{\"amount\":150,\"down_payment\":20,\"period_months\":12,\"monthly_payment\":15.50,\"total_expected\":206,\"annual_interest\":9.9,\"contract_fee\":4.9,\"apr\":35.5},\"cashier_id\":999,\"store_id\":111,\"modifications\":null,\"items\":[],\"notification_url\":\"https://your-site.com/notification\",\"return_url\":\"https://your-site.com/return\",\"purchase_url\":\"https://esto.ee/p/LWYRUP?target=signing&logout=1\",\"redirect_url\":\"https://esto.ee/p/LWYRUP?target=signing&logout=1\"}"
            mac: A1B2C3D4E5F60718293A4B5C6D7E8F90112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF0
    GetPurchaseResponse:
      description: |
        Purchase details. `data` is a JSON-encoded string, same envelope shape
        as the create-purchase responses.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/GetPurchaseEnvelope'
          example:
            data: "{\"id\":4815162342,\"status\":\"APPROVED\",\"merchant_reference\":\"gwjke9gdsf\",\"merchant_message\":null,\"is_test\":false,\"amount\":794.51,\"schedule_type\":\"REGULAR\",\"currency\":\"EUR\",\"terms\":{\"amount\":794.51,\"down_payment\":0,\"period_months\":12,\"monthly_payment\":68.21,\"total_expected\":818.52,\"annual_interest\":9.9,\"contract_fee\":4.9,\"apr\":35.5},\"cashier_id\":999,\"store_id\":111,\"modifications\":[{\"old_amount\":913.65,\"new_amount\":794.51,\"reason\":\"Discount applied\",\"handling_date\":\"2026-05-27 08:37:15\",\"created_date\":\"2026-05-27 08:37:15\"}],\"items\":[{\"name\":\"Bitcoin 101\",\"unit_price\":30.3,\"quantity\":3}]}"
            mac: D0F02C03D132D58F26948AAB08001494282D7F358DCED4F3C300D4499FDB67314BF7CE47E16781DEB3DC349F967526DC64033ABAF710A87FFE1C1667C38C4E4D
  schemas:
    ScheduleType:
      type: string
      enum: [REGULAR, ESTO_X, PAY_LATER, ESTO_PAY]
      description: |
        - `REGULAR` — a regular hire purchase application.
        - `ESTO_X` (ESTO 3 in customer-facing copy) — no additional fees, fixed short period. Must be enabled by an ESTO admin for the merchant.
        - `PAY_LATER` — Pay Later: no additional fees, customer pays within 30 days. Must be enabled by an ESTO admin for the merchant.
        - `ESTO_PAY` — a direct payment from the customer to the merchant. Redirect flow only. Must be enabled by an ESTO admin for the merchant.

        The API accepts additional loan schedule types (e.g. small and purpose-specific loans) that are out of scope for standard merchant checkout integrations and are intentionally not documented here.
    ConnectionMode:
      type: string
      enum: [live, test]
      default: live
      description: Use `test` to create a purchase in ESTO's test environment. See the Structure of an API request section.
    PurchaseCustomerType:
      type: string
      enum: [NATURAL_PERSON, LEGAL_PERSON]
      description: Accepted customer types. Values other than these are ignored rather than strictly rejected, so treat this as the set of meaningful values rather than an enforced allowlist.
    DocumentType:
      type: string
      description: Identity document type. Optional. VISA is defined but currently not used by ESTO.
      enum: [DRIVING_LICENSE, ID_CARD, PASSPORT, VISA]
    OccupationCategory:
      type: string
      description: |
        Self-reported occupation category. The full set is large; commonly
        used values are listed below — see UserDocumentType/OccupationCategory
        in the codebase for the authoritative list.
      enum:
        - UNEMPLOYED
        - ENTREPRENEUR
        - PRIVATE_SECTOR_WORKER
        - PUBLIC_SECTOR_WORKER
        - STUDENT
        - RETIRED
        - UNDER_GOVERNMENT_ALLOWANCE
        - EMPLOYEE
        - SOLE_BUSINESS_OWNER
        - OFFICIAL
        - FARMER
        - SELF_EMPLOYED
        - TOP_MIDDLE_MGMT
        - GOV_OR_SPECIALIST
        - CARETAKER
        - ARTISAN
        - SEAFARER
        - LAWYER
        - PENSIONER
        - FOREIGN_PENSIONER
        - DISABILITY_ALLOWANCE
        - WORKING_ABROAD
        - AUTHOR_SPORTSPERSON
        - CLERIC
        - DAILY_ALLOWANCE
        - MATERNITY_ALLOWANCE
        - RENT
    PurchaseItem:
      type: object
      required: [name, unit_price, quantity]
      properties:
        name:
          type: string
          description: Item name.
        unit_price:
          type: number
          format: float
          description: Price of a single unit, tax included.
        quantity:
          type: number
          format: float
          minimum: 0.01
        seller:
          type: [string, "null"]
          description: Which seller sold the item. Used for marketplaces, where each item can come from a different seller.
      example:
        name: Bitcoin 101
        unit_price: 30.30
        quantity: 3
    RedirectCustomer:
      type: object
      description: Optional customer pre-fill for the redirect flow. All fields are optional unless send_url_message_to_customer requires phone or email.
      properties:
        first_name:
          type: string
          maxLength: 255
        last_name:
          type: string
          maxLength: 255
        email:
          type: string
          format: email
          maxLength: 255
        phone:
          type: string
          maxLength: 31
        address:
          type: string
          maxLength: 255
          description: Street and house number.
        city:
          type: string
          maxLength: 255
        post_code:
          type: string
          maxLength: 31
    LocalCustomer:
      type: object
      required:
        - pin
        - document_nr
        - first_name
        - last_name
        - email
        - phone
        - address
        - allow_pension_query
      properties:
        pin:
          type: string
          description: Personal identification number (for example, the Estonian ID code). Validated against a country-specific PIN format.
        is_verified:
          type: boolean
          default: false
          description: Set to true if the customer's ID was verified in a physical retail store.
        document_nr:
          type: string
          maxLength: 50
          description: Required whenever document_type is set.
        document_type:
          $ref: '#/components/schemas/DocumentType'
        first_name:
          type: string
          maxLength: 255
        last_name:
          type: string
          maxLength: 255
        email:
          type: string
          format: email
          maxLength: 255
        phone:
          type: string
          maxLength: 31
        address:
          type: string
          maxLength: 255
        city:
          type: [string, "null"]
          maxLength: 255
        post_code:
          type: [string, "null"]
          maxLength: 31
        occupation_category:
          $ref: '#/components/schemas/OccupationCategory'
        allow_pension_query:
          type: boolean
          description: Allows a Pension Center query on behalf of ESTO. Required.
        is_politically_exposed:
          type: boolean
          default: false
        net_income_monthly:
          type: number
          format: float
          minimum: 0
          description: Self-reported monthly net income.
        expenditure_monthly:
          type: number
          format: float
          minimum: 0
          description: Self-reported monthly financial expenditure (loans, leases, etc).
    StoreRedirectPurchaseBody:
      type: object
      required: [amount, reference]
      properties:
        amount:
          type: number
          format: float
          minimum: 0.01
          description: Total purchase amount.
        reference:
          type: string
          maxLength: 255
          description: Merchant's own order reference. Echoed back as merchant_reference.
        message:
          type: [string, "null"]
          maxLength: 1000
        return_url:
          type: string
          format: uri
          description: Where ESTO redirects the customer after finishing the flow.
        notification_url:
          type: string
          format: uri
          description: Where ESTO sends the status callback — see the MerchantStatusCallback operations.
        cancel_url:
          type: string
          format: uri
        connection_mode:
          $ref: '#/components/schemas/ConnectionMode'
        items:
          type: array
          items:
            $ref: '#/components/schemas/PurchaseItem'
        allowed_customer_types:
          type: array
          description: Restricts which customer types may complete the purchase. See PurchaseCustomerType for the accepted values; unrecognised entries are ignored rather than rejected.
          items:
            $ref: '#/components/schemas/PurchaseCustomerType'
        customer:
          $ref: '#/components/schemas/RedirectCustomer'
        send_url_message_to_customer:
          type: [string, "null"]
          enum: [SMS, EMAIL, null]
          description: If set, ESTO automatically sends the purchase URL to the customer by SMS or email. Requires customer.phone (for SMS) or customer.email (for EMAIL).
        buyer_type:
          type: string
          enum: [PRIVATE, COMPANY]
          default: PRIVATE
          description: >-
            Who the purchase is for. A COMPANY purchase is a company hire purchase on the REGULAR schedule_type
            and needs company hire purchase switched on for the merchant and for the country. The API answers
            with a 400 error and one of these codes:
            ApplicationException COMPANY_PRODUCT_NOT_ENABLED (47), company hire purchase is off in the country;
            ApplicationException INVALID_SCHEDULE_TYPE (22), buyer_type COMPANY on any schedule_type other than REGULAR;
            MerchantException COMPANY_HIRE_PURCHASE_NOT_ENABLED (31), the merchant has not switched company hire purchase on;
            MerchantException COMPANY_HIRE_PURCHASE_MERCHANT_SETTINGS_MISSING (34), the merchant has no settings for it;
            MerchantException COMPANY_HIRE_PURCHASE_TERM_UNAVAILABLE (32), no term fits the net total;
            ApplicationException PURCHASE_TOTAL_NOT_IN_ALLOWED_RANGE (5), the net total is outside the merchant's company band.
            Omit it for a private customer.
        schedule_type:
          $ref: '#/components/schemas/ScheduleType'
        display_schedule_types:
          type: array
          items:
            $ref: '#/components/schemas/ScheduleType'
          description: When schedule_type is omitted, controls which schedule type options are offered to the customer on the redirect page (subject to what the merchant's campaign has enabled).
        bank_id:
          type: [string, "null"]
          description: Pre-selects a bank in the payment step. Use the code matching the customer's country and bank.
          enum:
            - EE_SWEDBANK
            - EE_SEB
            - EE_CITADELE
            - EE_LHV
            - EE_REVOLUT
            - EE_COOP
            - EE_LUMINOR
            - LV_SWEDBANK
            - LV_SEB
            - LV_CITADELE
            - LV_REVOLUT
            - LV_INDUSTRA
            - LV_SIGNETBANK
            - LV_LUMINOR
            - LT_SWEDBANK
            - LT_SEB
            - LT_MEDICINOS
            - LT_CITADELE
            - LT_REVOLUT
            - LT_SIAULIU
            - LT_LUMINOR
            - FI_ALANDSBANKEN
            - FI_NORDEA
            - FI_REVOLUT
            - FI_S_PANKKI
            - FI_BANK_NORWEGIAN
            - FI_HANDELSBANKEN
            - FI_OP_FINANCIAL
            - FI_SBANK
            - FI_DANSKE_BANK
            - FI_OMA_SAASTOPANKKI
            - FI_POP_PANKKI
            - null
        payment_method_key:
          type: [string, "null"]
          description: Payment method key from GET /purchase/payment-methods. Used to route directly to a specific payment method (for example, a Direct Payment provider).
        cashier_id:
          type: [integer, "null"]
          description: Must belong to the authenticated merchant.
        store_id:
          type: [integer, "null"]
        from_retail:
          type: boolean
          default: false
    StoreLocalPurchaseBody:
      type: object
      required: [amount, reference, customer]
      properties:
        amount:
          type: number
          format: float
          minimum: 0.01
        down_payment:
          type: number
          format: float
          minimum: 0
          default: 0
        period_months:
          type: integer
          minimum: 3
        reference:
          type: string
          maxLength: 255
        message:
          type: [string, "null"]
          maxLength: 1000
        return_url:
          type: string
          format: uri
        notification_url:
          type: string
          format: uri
        connection_mode:
          $ref: '#/components/schemas/ConnectionMode'
        items:
          type: array
          items:
            $ref: '#/components/schemas/PurchaseItem'
        allowed_customer_types:
          type: array
          description: Restricts which customer types may complete the purchase. See PurchaseCustomerType for the accepted values; unrecognised entries are ignored rather than rejected.
          items:
            $ref: '#/components/schemas/PurchaseCustomerType'
        customer:
          $ref: '#/components/schemas/LocalCustomer'
        schedule_type:
          type: string
          enum: [REGULAR, ESTO_X, PAY_LATER]
          description: ESTO_PAY is not available on the local flow — use the redirect flow instead.
        display_schedule_types:
          type: array
          items:
            $ref: '#/components/schemas/ScheduleType'
        cashier_id:
          type: [integer, "null"]
        store_id:
          type: [integer, "null"]
        from_retail:
          type: boolean
          default: false
    PurchaseTerms:
      type: object
      properties:
        amount:
          type: number
          format: float
          description: Total purchase price.
        down_payment:
          type: number
          format: float
        period_months:
          type: integer
          description: Contract period in months. May differ from the period that was requested.
        monthly_payment:
          type: number
          format: float
        total_expected:
          type: number
          format: float
          description: |
            Total amount expected to be paid back by the customer (credit +
            down payment). Called total_credit in older documentation — the
            current API field name is total_expected.
        annual_interest:
          type: number
          format: float
          description: Annual interest rate percentage. Neutral placeholder value in examples — actual rates depend on merchant campaign terms.
        contract_fee:
          type: number
          format: float
          description: Contract fee. Already included in monthly_payment; not charged separately.
        apr:
          type: number
          format: float
          description: Annual percentage rate. Neutral placeholder value in examples.
    Modification:
      type: object
      properties:
        old_amount:
          type: number
          format: float
        new_amount:
          type: number
          format: float
        reason:
          type: string
        handling_date:
          type: [string, "null"]
        created_date:
          type: [string, "null"]
    PurchaseStatus:
      type: string
      enum: [CREATED, APPROVED, REJECTED, CANCELLED, DELETED]
      description: |
        - `CREATED` — application created, and also returned while it is pending.
        - `APPROVED` — contract signed.
        - `REJECTED` — application rejected.
        - `CANCELLED` — application cancelled.
        - `DELETED` — application deleted.
    LocalPurchaseAnswer:
      type: string
      enum: [POSITIVE, PENDING, NEGATIVE]
      description: Instant eligibility decision returned by the local flow only.
    PurchaseData:
      type: object
      description: Decoded contents of the data field (ESTO sends data as a JSON-encoded string, not a nested object — decode it before reading these fields).
      properties:
        id:
          type: integer
        status:
          $ref: '#/components/schemas/PurchaseStatus'
        merchant_reference:
          type: string
        merchant_message:
          type: [string, "null"]
        is_test:
          type: boolean
        amount:
          type: number
          format: float
        schedule_type:
          $ref: '#/components/schemas/ScheduleType'
        currency:
          type: string
          enum: [EUR]
        terms:
          $ref: '#/components/schemas/PurchaseTerms'
        cashier_id:
          type: [integer, "null"]
        store_id:
          type: [integer, "null"]
        modifications:
          type: [array, "null"]
          items:
            $ref: '#/components/schemas/Modification'
        items:
          type: array
          items:
            $ref: '#/components/schemas/PurchaseItem'
    StoreRedirectPurchaseData:
      allOf:
        - $ref: '#/components/schemas/PurchaseData'
        - type: object
          properties:
            status:
              $ref: '#/components/schemas/PurchaseStatus'
            notification_url:
              type: [string, "null"]
            return_url:
              type: [string, "null"]
            purchase_url:
              type: string
              description: Redirect the customer here to start/continue the application.
    StoreLocalPurchaseData:
      allOf:
        - $ref: '#/components/schemas/PurchaseData'
        - type: object
          properties:
            status:
              $ref: '#/components/schemas/LocalPurchaseAnswer'
            notification_url:
              type: [string, "null"]
            return_url:
              type: [string, "null"]
            purchase_url:
              type: [string, "null"]
              description: Present when status is POSITIVE or PENDING. Redirect the customer here to finish signing.
            redirect_url:
              type: [string, "null"]
              deprecated: true
              description: Deprecated — identical to purchase_url. Use purchase_url instead.
    ApiError:
      type: object
      properties:
        code:
          type: integer
        detail:
          type: string
    StoreRedirectPurchaseEnvelope:
      type: object
      properties:
        errors:
          type: array
          items:
            $ref: '#/components/schemas/ApiError'
        data:
          type: string
          contentMediaType: application/json
          contentSchema:
            $ref: '#/components/schemas/StoreRedirectPurchaseData'
          description: JSON-encoded StoreRedirectPurchaseData. The string "[]" (empty JSON array) when errors is non-empty; the mac is computed over that "[]" string.
        mac:
          type: string
          description: Uppercase SHA-512 MAC over the raw data string. See the Authentication section.
    StoreLocalPurchaseEnvelope:
      type: object
      properties:
        errors:
          type: array
          items:
            $ref: '#/components/schemas/ApiError'
        data:
          type: string
          contentMediaType: application/json
          contentSchema:
            $ref: '#/components/schemas/StoreLocalPurchaseData'
          description: JSON-encoded StoreLocalPurchaseData. The string "[]" (empty JSON array) when errors is non-empty; the mac is computed over that "[]" string.
        mac:
          type: string
    GetPurchaseEnvelope:
      type: object
      properties:
        data:
          type: string
          contentMediaType: application/json
          contentSchema:
            $ref: '#/components/schemas/PurchaseData'
          description: JSON-encoded PurchaseData (with items and modifications populated).
        mac:
          type: string
    ModificationRequestBody:
      type: object
      required: [amount, reason]
      properties:
        amount:
          type: number
          format: float
        reason:
          type: string
    CancellationRequestBody:
      type: object
      required: [reason]
      properties:
        reason:
          type: string
    RequestStatusResponse:
      type: object
      properties:
        status:
          type: string
          enum: [CREATED]
        errors:
          type: array
          items:
            $ref: '#/components/schemas/ApiError'
    PaymentMethod:
      type: object
      properties:
        key:
          type: string
        name:
          type: string
        country_code:
          type: string
        schedule_type:
          $ref: '#/components/schemas/ScheduleType'
        type:
          type: string
          enum: [BANKLINK, CARD, BANK_WIRE, LOAN]
          description: Loan-based methods (hire purchase, ESTO X, Pay Later) are always LOAN; BANKLINK, CARD, and BANK_WIRE appear for direct-payment (ESTO Pay) gateway methods.
        logo_url:
          type: string
          format: uri
        is_test:
          type: boolean
    Cashier:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
    Store:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
    MerchantInfo:
      type: object
      properties:
        shop_id:
          type: string
        advertiser_id:
          type: [integer, "null"]
        cashiers:
          type: array
          items:
            $ref: '#/components/schemas/Cashier'
        stores:
          type: array
          items:
            $ref: '#/components/schemas/Store'
        ef_region_token:
          type: [string, "null"]
          description: Only set for merchants with deal tracking and Everflow enabled. Not relevant to most integrations.
    MerchantPurchase:
      type: object
      properties:
        id:
          type: integer
        customer_name:
          type: [string, "null"]
        amount:
          type: number
          format: float
        is_test:
          type: boolean
        schedule_type:
          $ref: '#/components/schemas/ScheduleType'
        merchant_reference:
          type: [string, "null"]
        created_at:
          type: [string, "null"]
          description: Formatted as d.m.Y H:i.
    MerchantPurchasesResponse:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/MerchantPurchase'
        page:
          type: integer
        total:
          type: integer
        total_pages:
          type: integer
    AllPaymentsResponse:
      type: object
      properties:
        periods:
          type: array
          items:
            type: object
            properties:
              period:
                type: integer
              monthly_payment:
                type: number
                format: float
    SinglePaymentResponse:
      type: object
      properties:
        monthly_payment:
          type: number
          format: float
        period_months:
          type: integer
        total_credit:
          type: number
          format: float
    PeriodsResponse:
      type: object
      properties:
        periods:
          type: array
          items:
            type: integer
    MerchantCallbackPayload:
      type: object
      description: |
        Decoded contents of the json field sent in the merchant status
        callback. See the MerchantStatusCallback GET/POST operations for the
        delivery mechanism and MAC verification. connection_mode,
        reference, and shop_id are deprecated legacy fields kept for
        backward compatibility — read is_test and merchant_reference
        instead.
      properties:
        id:
          type: integer
        status:
          $ref: '#/components/schemas/PurchaseStatus'
        merchant_reference:
          type: string
        merchant_message:
          type: [string, "null"]
        is_test:
          type: boolean
        amount:
          type: number
          format: float
        schedule_type:
          $ref: '#/components/schemas/ScheduleType'
        currency:
          type: string
        terms:
          $ref: '#/components/schemas/PurchaseTerms'
        cashier_id:
          type: [integer, "null"]
        store_id:
          type: [integer, "null"]
        modifications:
          type: [array, "null"]
          items:
            $ref: '#/components/schemas/Modification'
        items:
          type: array
          items:
            $ref: '#/components/schemas/PurchaseItem'
        auto:
          type: boolean
          description: true when ESTO triggered the callback asynchronously (for example, after signing); false is not emitted by this notification path but is reserved for parity with the synchronous return flow.
        connection_mode:
          type: string
          deprecated: true
          description: Deprecated — use is_test instead.
        reference:
          type: string
          deprecated: true
          description: Deprecated — use merchant_reference instead.
        shop_id:
          type: string
          deprecated: true
          description: Deprecated, scheduled for removal.
  callbacks:
    MerchantStatusCallback:
      '{$request.body#/notification_url}':
        post:
          operationId: merchantStatusCallbackPost
          summary: Merchant status callback (POST)
          description: |
            Fires when a purchase reaches a signed, rejected, or cancelled
            state, and only if the purchase has a `notification_url` (a
            per-purchase `notification_url` takes priority over the
            merchant account's default). Sent when the merchant account's
            `callback_method` setting is POST: `json` and `mac` are
            delivered as an `application/x-www-form-urlencoded` body.

            `json` is a JSON-encoded string — decode it before reading its
            fields (see MerchantCallbackPayload; treat `connection_mode`,
            `reference`, and `shop_id` as deprecated legacy fields — read
            `is_test` and `merchant_reference` instead). Verify `mac`
            exactly like the MAC on a purchase response — see the
            Authentication section. Respond with any 2xx/3xx status to
            acknowledge receipt; anything else queues a retry.
          requestBody:
            content:
              application/x-www-form-urlencoded:
                schema:
                  type: object
                  properties:
                    json:
                      type: string
                      contentMediaType: application/json
                      contentSchema:
                        $ref: '#/components/schemas/MerchantCallbackPayload'
                      description: JSON-encoded MerchantCallbackPayload.
                    mac:
                      type: string
          responses:
            '200':
              description: Any 2xx/3xx response is treated as delivered. Non-2xx/3xx or a network error triggers a retry.
        get:
          operationId: merchantStatusCallbackGet
          summary: Merchant status callback (GET, default)
          description: |
            Fires when a purchase reaches a signed, rejected, or cancelled
            state, and only if the purchase has a `notification_url` (a
            per-purchase `notification_url` takes priority over the
            merchant account's default). Sent when the merchant account's
            `callback_method` setting is GET (the default): `json` and
            `mac` are appended as query string parameters to
            `notification_url`.

            `json` is a JSON-encoded string — decode it before reading its
            fields (see MerchantCallbackPayload; treat `connection_mode`,
            `reference`, and `shop_id` as deprecated legacy fields — read
            `is_test` and `merchant_reference` instead). Verify `mac`
            exactly like the MAC on a purchase response — see the
            Authentication section. Respond with any 2xx/3xx status to
            acknowledge receipt; anything else queues a retry.
          parameters:
            - name: json
              in: query
              schema:
                type: string
                contentMediaType: application/json
                contentSchema:
                  $ref: '#/components/schemas/MerchantCallbackPayload'
              description: JSON-encoded MerchantCallbackPayload.
            - name: mac
              in: query
              schema:
                type: string
          responses:
            '200':
              description: Any 2xx/3xx response is treated as delivered. Non-2xx/3xx or a network error triggers a retry.
