# Mereu API v1 — integration guide

Base URL: https://mereu.md/api/v1. This guide and OpenAPI are public and require no key. Integrations run on the client’s server over HTTPS.

## 1. Authentication and API keys

Each key grants access to one business and the locations and scopes selected in the cabinet. Send requests from your integration server over HTTPS.

1. Verify the owner’s email address before creating or rotating an API key.
2. Open Administration → Integrations → API keys in the cabinet.
3. Choose a name, authorized locations and the scopes your integration needs.
4. Keep “No expiry”, or select an optional term of 1–365 days.
5. Copy the secret shown once and store it in your secret manager or the server environment variable `MEREU_API_KEY`.

| Operation | What happens |
| --- | --- |
| Create without a deadline | The key does not expire automatically; `expiresAt=null`. |
| Rotate | The previous key is revoked immediately. Update the key on your integration server. |
| Revoke | The connection stays revoked. Create a new connection to restore access. |
| Lost creation response | Reload the list and rotate the key. Repeating the request never reveals the secret. |

> **Keep the key on your server**
> Do not include the key in browser JavaScript, mobile applications, Git or logs. A signed-in business administrator manages keys in the cabinet; a public Bearer key cannot manage keys.

> **Claiming an unconfirmed account**
> When the real owner claims a self-service account that has never been confirmed, the business’s existing API connections and keys are revoked. After the claim, create a new connection and update the key in your POS/CRM. This security revocation also applies to keys with no expiry.

An expired key can be rotated in the cabinet. Indefinite keys need no scheduled renewal. An expired sync cursor does not mean the API key expired.

### Read company details · cURL

```bash
curl --fail-with-body --silent --show-error \
  -H "Authorization: Bearer $MEREU_API_KEY" \
  -H 'Accept: application/json' \
  https://mereu.md/api/v1/account
```

### Read company details · JavaScript

```javascript
import {createMereuClient} from './mereu-client.mjs';

const api = createMereuClient({
  baseUrl: 'https://mereu.md/api/v1',
  apiKey: process.env.MEREU_API_KEY
});

const {data: account} = await api('GET', '/account');
console.log(account.name, account.base_currency);
```

### Read company details · Python

```python
import os
from mereu_client import MereuClient

api = MereuClient(
    'https://mereu.md/api/v1',
    os.environ['MEREU_API_KEY']
)

account = api.request('GET', '/account')['data']
print(account['name'], account['base_currency'])
```

## 2. Company, locations and programs

Read configuration before sending sales or displaying amounts in your CRM. Always use the central origin `https://mereu.md/api/v1`, including for businesses with a public customer page on a subdomain.

| Endpoint | Returned data | Scope |
| --- | --- | --- |
| GET /account | Company, country, currency, time zone, access mode and authorized locations. | account:read |
| GET /reference-data | Countries, supported currencies and time zone suggestions. | account:read |
| GET /locations | Authorized locations and their status. | locations:read |
| GET /programs | Published program versions and exposed rules. | programs:read |

The `/locations` and `/programs` lists accept only `limit` and `cursor`: 50 results by default, at most 100. Follow `next_cursor` until it is `null`. The cursor lasts one hour and is bound to the current key; restart from the first page after rotating the key.

> **Configuration is not a changes feed**
> The `sync_token` field in these lists is reserved. Use `/data/*` for CRM synchronization. `/checkouts/preview` is the authoritative benefit calculation.

### List authorized locations · cURL

```bash
curl --fail-with-body --silent --show-error \
  -H "Authorization: Bearer $MEREU_API_KEY" \
  -H 'Accept: application/json' \
  --get \
  --data-urlencode 'limit=100' \
  https://mereu.md/api/v1/locations
```

## 3. Identify a card in your POS

Send the complete scanned code to `POST /cards/resolve`. The response includes `card_id`, `program_version_id` and `currency`, without contact data.

- Use the full barcode or the exact public card code; do not convert it into a UUID.
- The key needs `checkouts:write` and access to the supplied location.
- Inactive, test and other-business cards return 404.
- This lookup does not require `Idempotency-Key`. Keep your POS customer mapping in your own system.

## 4. POS integration: apply a benefit before payment

Use this flow when your POS applies a discount or spends points before collecting payment. Grant `checkouts:write` and explicitly authorize financial operations in the cabinet.

| Cabinet binding | Value from your system |
| --- | --- |
| source | A stable integration identifier, for example `my_pos`. |
| accountId | The merchant or POS account identifier. |
| externalLocationId | The store identifier in your POS. |
| locationId | The UUID of the corresponding Mereu location. |
| eligiblePolicy | Use `paid_excluding_tips_surcharges`. |

This binding maps document references; it does not grant Mereu access to a POS provider account. Keep these values unchanged across key rotation.

1. Calculate the benefit with `POST /checkouts/preview`. Send amounts and `reward.mode`: `none`, `points` or `visit_reward`. For `points`, supply a decimal string such as `10.25`.
2. Read `discount` and `expected_paid_total` from the quote. The quote lasts 120 seconds. Do not recalculate these values in your POS.
3. Reserve the benefit with `POST /checkouts`, using `quote_id` and the stable sale reference.
4. Send `POST /checkouts/{id}/payment-started` with the reservation’s `expected_revision` and wait for success.
5. Only now apply the benefit and collect payment in your own POS or payment system.
6. After verifying payment, confirm with `POST /checkouts/{id}/commit`. Use the revision from `payment-started`, the real amount equal to `expected_paid_total`, the payment time and its reference. Save `transaction_id`.

> **Persist requests before sending**
> Each financial step has its own `Idempotency-Key` UUID. Save the UUID and exact request body in your database. Repeat the same step with the same values instead of creating another sale.

A card can have only one reservation, shared with Casa. A reservation whose payment has not started expires after 10 minutes. Read `GET /checkouts/{id}` to check its status.

If payment did not occur, cancellation requires the current revision and a reason. Once payment might have started, `payment_not_completed:true` is an explicit attestation of non-payment, never an assumption after a timeout.

> **Uncertain payment**
> A lost response does not prove payment failed. Do not charge again or create another reservation. Verify your POS, read the checkout and, when needed, resolve the case in Integrations → Reconciliation in the cabinet.

### POS operation order · Flow

```text
1. POST /checkouts/preview
2. POST /checkouts
3. POST /checkouts/{id}/payment-started

   Collect and verify payment in your POS.

4. POST /checkouts/{id}/commit

   Save transaction_id for refunds.
```

## 5. Already-paid sales

Use `POST /purchases` when payment has already happened and you want to record the purchase for loyalty accrual. Grant `purchases:write` and an authorized financial binding.

- Send `location_id`, `card_id`, `external_ref` and the operation UUID.
- `paid_total` is the actual amount paid; `eligible_amount` is the eligible amount paid, excluding tips and surcharges.
- `paid_at` and `provider_payment_id` must come from a verified payment in your system.
- When observing a sale already committed through checkout, use the same sale and payment references.

> **No retrospective benefits**
> This endpoint never applies retrospective discounts or spends points. Sales before binding activation or card creation are recorded without retrospective accrual (`accrual_enabled=false`).

A receipt alone does not prove payment. Verify payment before importing. Mereu does not collect money through this endpoint.

## 6. Refunds and full reversals

Read the transaction with `GET /transactions/{id}` and `transactions:read`. Refunds require `refunds:write` and the sale’s financial UUID.

| Endpoint | When to use it |
| --- | --- |
| POST /transactions/{id}/refunds | A verified partial or full refund. |
| POST /transactions/{id}/reversal | A full reversal; refused after any applied refund. |

| Field | What to send |
| --- | --- |
| external_ref | A stable, distinct reference for the return document. |
| refunded_total | Actual money refunded. It may be zero for a purchase fully paid with benefits. |
| refunded_eligible_amount | The ORIGINAL eligible goods value before the Mereu benefit. |
| occurred_at / provider_refund_id | The real return time and identifier from your system. |
| reason | The verified reason, without personal data. |

Use the original sale’s item allocations, not the current program rules. For a regular `/purchases` import without a redeemed benefit, the returned eligible value matches the eligible amount paid.

Partial refunds allocate cumulatively with exact integer rounding; the final allocation closes the sale. Refunded cash may include returned noneligible payment within the original amount paid. The original currency and program are preserved.

> **A refund requiring review**
> `needs_review` is an already-saved case. Do not resend it with another UUID. Points or visits already spent or expired may require explicit acceptance of compensation in Reconciliation.

Read `GET /transactions/{refund_id}` to check the refund’s status. Mereu does not instruct a bank or POS to send money: record the refund only after verifying the actual return in your system.

## 7. CRM integration: export and synchronization

Your CRM reads Mereu data through GET requests. This API cannot create or modify customers.

| Resource | What to synchronize | Scope |
| --- | --- | --- |
| /data/customers | Business-local identity, names, available contact details and marketing consent. | customers:read |
| /data/cards | Cards, program, status and balances calculated at read time. | cards:read |
| /data/transactions | Applied Casa/POS ledger entries and exposed loyalty amounts. | transactions:read |

1. Start each resource with `mode=snapshot&limit=100`. Read every page using `next_cursor` until it becomes `null`.
2. Save pages to a staging dataset. Replace the active CRM dataset only after completing the export.
3. Keep the initial snapshot’s `sync_cursor`. Then request the SAME resource with `mode=changes` and that cursor.
4. Apply pages in order: insert or update by ID; for `operation=delete`, delete by `record_id`.
5. Commit the data and new cursor in the SAME CRM database transaction. If saving fails, resume from the previously saved cursor.

> **One cursor per resource**
> Do not use a customers cursor for cards or transactions. Cursors are bound to connection, resource and authorized locations, survive key rotation and expire after 7 days.

On `410 CURSOR_EXPIRED`, start a new full snapshot and replace the local dataset. If authorization or connection changes, rebuild the export and remove data you can no longer access. There is no total exported-row quota; respect request limits.

Changes describe current state, not an immutable historical audit. A replayed event can carry newer content: do not skip its body just because you have seen the same `event_id`. Process sequentially and apply `operation=delete` / `deleted=true`, including removing local contact data.

Snapshot pages read current rows; changes after the snapshot anchor cover updates during pagination. Transactions still in flight can temporarily delay visibility. `changed_at` is not a version number.

`customer.id` is the card UUID within this business. Do not automatically merge people across businesses. In the ledger, `id` and `original_id` are native entry IDs; only a non-null `financial_transaction_id` works with financial transaction and refund endpoints. Staff operations may not have this ID.

Periodically read `/account` for the current currency and time zone. Store CRM mappings in your own system; `/resource-links` is retired (410). Do not put contact data in identifiers or logs.

### 1. Initial customer snapshot · cURL

```bash
curl --fail-with-body --silent --show-error \
  -H "Authorization: Bearer $MEREU_API_KEY" \
  -H 'Accept: application/json' \
  --get \
  --data-urlencode 'mode=snapshot' \
  --data-urlencode 'limit=100' \
  https://mereu.md/api/v1/data/customers
```

### 2. Changes from the saved cursor · cURL

```bash
curl --fail-with-body --silent --show-error \
  -H "Authorization: Bearer $MEREU_API_KEY" \
  -H 'Accept: application/json' \
  --get \
  --data-urlencode 'mode=changes' \
  --data-urlencode "cursor=$CUSTOMERS_SYNC_CURSOR" \
  --data-urlencode 'limit=100' \
  https://mereu.md/api/v1/data/customers
```

## 8. Scopes and locations

Grant only the access your integration needs. Scopes and locations are explicit; no key grants access to another business.

| Scope | Grants access to |
| --- | --- |
| account:read | Company details and reference data. |
| locations:read | Authorized locations. |
| programs:read | Published programs. |
| customers:read | Reading and synchronizing contact data. |
| cards:read | Reading and synchronizing cards and balances. |
| transactions:read | The ledger and financial transaction status reads. |
| checkouts:write | Card lookup and reservation/commit workflows. |
| purchases:write | Recording already-paid sales. |
| refunds:write | Refunds and full reversals. |

> **Public API scope**
> The API cannot modify customers, issue cards, manually edit balances or control automations, offers or notifications. It does not change company settings. Writes are limited to sale and return workflows.

## 9. JavaScript, Python and Postman examples

Download the examples from Resources. Run them on your server with `MEREU_API_URL=https://mereu.md/api/v1` and the key in `MEREU_API_KEY`.

| File | Purpose |
| --- | --- |
| mereu-client.mjs / mereu-client.py | Authentication, requests and GET query encoding. |
| crm-sync.mjs / crm-sync.py | One snapshot or changes page with a durable checkpoint. |
| pos-checkout.mjs | Reservation, sale commit, purchase import and refunds. |
| mereu-postman.json | Manual requests with references, UUIDs and amounts to fill in. |

For Python imports, rename the modules to `mereu_client.py` and `crm_sync.py`. Python module names cannot contain hyphens.

- CRM: load the saved state and call `syncMereuPage(api, resource, state, commitPage)` or `sync_mereu_page(api.request, resource, state, commit_page)`.
- `state=null` / `None` starts a snapshot. Each call processes ONE page and returns `phase` and `cursor`.
- In the callback, reset staging on `reset=true`, add non-deleted rows and replace the active dataset only on `complete=true`. In changes mode, apply inserts, updates and deletes.
- Commit the checkpoint with the data in one transaction. Let save errors propagate. Schedule the next page in your job queue within the request limit.

- POS: `prepareCheckout` sends only preview, reservation and payment-started through your durable `persist` callback.
- Supply UUIDs from your persisted order. Start payment in your system only after the function succeeds and the journal commits.
- After verifying payment, call `commitVerifiedPayment`. Use `recordVerifiedPurchase` for paid imports and `recordVerifiedReturn` for verified returns.
- A journal failure after a response may mean the operation was already applied. Recover the saved request and read its status before replaying it.

In Postman, fill the empty variables and integer money amounts. For commit, copy `expected_paid_total` from the quote and the revision from payment-started. For refunds, use the original eligible allocation and actual returned cash.

> **Examples do not start payments**
> No module collects or refunds money, contacts providers or automatically retries writes. Replace illustrative OpenAPI UUIDs and amounts with authorized references and verified facts.

## 10. Errors and recovery

Errors include `error.code`, `error.message` and `error.request_id`; validation may add `field_errors`. Keep `X-Request-Id` for support, without keys or personal data.

| Code | What to do |
| --- | --- |
| 401 INVALID_API_KEY | Check the key, revocation or chosen expiry in the cabinet. Indefinite keys need no renewal. |
| 403 INSUFFICIENT_SCOPE | Check scopes, locations, financial authorization/binding and the business export window. |
| 404 | Check the authorized resource. A native ledger ID is not automatically a financial ID. |
| 409 IDEMPOTENCY_CONFLICT | Recover the original UUID and body; never change the UUID to bypass an uncertain result. |
| 409 STALE_QUOTE / QUOTE_EXPIRED | Read the status and obtain a new quote before a new verified attempt. |
| 409 STALE_REVISION / CARD_RESERVED | Read the checkout and inspect the existing operation; do not start another payment. |
| 409 REFUND_ALLOCATION_MISMATCH | Use original gross values and cumulative allocations, including any returned noneligible cash. |
| 410 CURSOR_EXPIRED | Rebuild the full snapshot. Retired endpoints have their own 410 codes. |
| 422 INVALID_CURSOR / VALIDATION_ERROR | Fix parameters. For configuration lists, restart at page 1 after the one-hour cursor expires. |
| 423 SERVICE_SUSPENDED | Financial operations are unavailable; resolve service status in the cabinet. |
| 429 RATE_LIMITED | Honor Retry-After and spread requests within the shared connection budget. |
| 503 or timeout | Preserve UUID and body, back off and read/reconcile an uncertain operation before retrying. |

> **Keep expiry rules separate**
> Do not rotate a valid key to fix a cursor error. Never blindly retry a 401. For 400/422 validation errors, fix input before starting a new operation.

## 11. Money, time zones and limits

Supported currencies: MDL, RON, EUR, USD, GBP, UAH, PLN, TRY, CHF, RUB, GEL, KZT. All have two minor-unit decimals: `10000` means `100.00`. Send integer money amounts; do not use floating-point rounding.

New operations use the current company currency. Reservations and API refunds retain their recorded currency. Changing company currency relabels existing amounts without FX conversion. The data ledger also exposes `recorded_currency` when available.

Send RFC3339 timestamps with an offset; UTC `Z` is recommended. Convert local dates using the business/location IANA time zone and explicitly resolve daylight-saving ambiguity. Never assume the server or browser time zone.

| Limit | Value |
| --- | --- |
| Requests per connection | 120/minute, shared across API calls. |
| Requests per IP | 300/minute per group: configuration, datasets, financial operations. |
| Page | 50 results by default, at most 100. |
| JSON body | At most 100000 bytes. |
| Financial values | 0–100000000 minor units; some operations require a positive amount. |
| Connections | At most 20 active connections and 10 authorized locations per connection. |
| Key | No expiry by default, or an optional 1–365 day term. |
| Configuration / dataset cursor | 1 hour / 7 days. |
| Quote / unstarted reservation | 120 seconds / 10 minutes. |

Financial command results are retained. Preview replay is retained for at least 24 hours and never extends the quote. Key validity, revocation, expiry, scopes and authorized bindings are checked again on replay.

On 429, honor `Retry-After`. Increase the polling interval when there are no changes. Never log Authorization, card codes, customer identifiers or complete financial payloads.

## 12. Versioning and operations

Use `/api/v1`. Accept new optional response fields and ignore unknown fields. Breaking changes require a new API version and migration instructions.

The client or its integrator builds and maintains the connection to their POS/CRM. No provider credentials or accounts are required by Mereu. Managed Loyverse/Square/Poster connectors, OAuth, provider webhooks and `/connector-events` are retired with `410 CONNECTORS_RETIRED`.

API v1 provides no outgoing webhooks, asynchronous provider events or remote marketing controls. Financial operations require active service and explicit authorization; reads remain available for authorized export when contractual writes stop. Disabled or unavailable API access returns 503.

Resolve uncertain payments and refunds requiring review in the cabinet under Integrations → Reconciliation. Do not directly edit the Casa ledger.
