> For the complete documentation index, see [llms.txt](https://docs.phptravels.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.phptravels.com/support/for-developers/integration/stays.md). Agents can also search and read this documentation through its [MCP server](https://docs.phptravels.com/~gitbook/mcp).

# Stays

This guide is for developers who connect a **new hotel supplier** (for example GRNConnect, Hotelbeds, TBO or any XML/JSON hotel API) to a PHPTRAVELS v10 website.

It covers everything from A to Z:

* how the module system works and where your code lives
* how supplier credentials are saved, tested and switched between test and live
* how hotel content (names, images, addresses, regions) is imported into the database
* the exact request and response contract for **search, hotel details, rooms, rate check, booking, issue, cancel, void and refund**
* pricing, markup, currency and tax
* logging, error handling and security rules
* a complete test plan
* how to move the integration from a **staging** server to **production** safely, and keep it working after official updates

{% hint style="info" %} Throughout this guide the example supplier is **GRNConnect** and its module name is `grnconnect`. Replace it with your own supplier name. The name must be **lowercase**, use only `a-z`, `0-9` and `-`, and must be unique. {% endhint %}

***

### 1. How the stays system works <a href="#user-content-1-how-the-stays-system-works" id="user-content-1-how-the-stays-system-works"></a>

#### 1.1 The big picture <a href="#user-content-11-the-big-picture" id="user-content-11-the-big-picture"></a>

A PHPTRAVELS website does not talk to a hotel supplier directly from the page. Every supplier lives in its own **module** under `modules/stays/<name>/`, and every call goes through one **module gateway** (modules/index.php).

{% code overflow="wrap" %}

```
 Customer browser       │       ▼ PHPTRAVELS website (core)                      Supplier module (your code)              Supplier API ─────────────────────────                      ───────────────────────────              ──────────── /stays/... search page  ──POST──►  /modules/stays/grnconnect/search   ──HTTPS──►  GRN search /stay/... hotel page    ──POST──►  /modules/stays/grnconnect/details  ──HTTPS──►  GRN hotel info / local DB                         ──POST──►  /modules/stays/grnconnect/rooms    ──HTTPS──►  GRN rates room selected           ──POST──►  /modules/stays/grnconnect/prebook  ──HTTPS──►  GRN rate check (optional) checkout + payment       (core creates the booking row: pending / unpaid) payment success (server)──POST──►  /modules/stays/grnconnect/issue    ──HTTPS──►  GRN book / confirm admin booking page      ──POST──►  /modules/stays/grnconnect/cancel|void|refund ─► GRN cancel
```

{% endcode %}

**The core owns:** the search page, filters, hotel page layout, room selection, checkout form, travellers, promo codes, tax, payment gateways, the `bookings` table, invoices, PDF vouchers, emails and notifications, the customer dashboard and the admin booking pages.

**Your module owns:** talking to the supplier, converting the supplier's data into the PHPTRAVELS format, applying markup through the shared helper, and booking or cancelling at the supplier.

#### 1.2 Where things live <a href="#user-content-12-where-things-live" id="user-content-12-where-things-live"></a>

| Path                                          | What it is                                                                               |
| --------------------------------------------- | ---------------------------------------------------------------------------------------- |
| modules/index.php                             | The module gateway. Every `/modules/*` request lands here; it includes every module.     |
| modules/helpers.php                           | Shared helpers: `MARKUP()`, `CURRENCY_CONVERT()`, logging, request signatures.           |
| modules/.htaccess                             | Sends every `/modules/*` URL to modules/index.php.                                       |
| `modules/stays/<name>/`                       | **Your module.** One folder per supplier.                                                |
| `modules` (database table)                    | One row per supplier: credentials, test/live switch, markup, tax, status.                |
| `app/views/modules/stays/`                    | The core pages: listing, hotel details, rooms, booking, invoice.                         |
| app/views/admin/settings/modules-settings.php | Admin → Settings → Modules → (supplier) page: credentials, markup, content import, logs. |
| `assets/img/modules/<name>.png`               | The supplier logo shown in the admin.                                                    |

#### 1.3 Reference modules to read <a href="#user-content-13-reference-modules-to-read" id="user-content-13-reference-modules-to-read"></a>

You do not need to start from nothing. These modules ship with v10 and are good references:

| Module                      | Read it for                                                                                                               |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `modules/stays/hotels/`     | The **simplest** module (the site's own hotels). Minimal issue/cancel actions.                                            |
| `modules/stays/wanderbeds/` | A **clean template**: one shared `api.php` wrapper, prebook, all actions.                                                 |
| `modules/stays/ratehawk/`   | A **complete, certified** integration: content sync, region search, prebook, asynchronous booking, cancellation policies. |
| `modules/stays/hotelbeds/`  | A large **content import** (staging tables, atomic swap) and CheckRate.                                                   |

***

### 2. Before you start <a href="#user-content-2-before-you-start" id="user-content-2-before-you-start"></a>

#### 2.1 Server requirements <a href="#user-content-21-server-requirements" id="user-content-21-server-requirements"></a>

| Item             | Requirement                                                                                        |
| ---------------- | -------------------------------------------------------------------------------------------------- |
| PHP              | 8.2 or newer                                                                                       |
| PHP extensions   | `curl`, `pdo_mysql`, `mysqli`, `openssl`, `mbstring`, `fileinfo`, `gd`, `zip`, `json`              |
| Database         | MySQL 8 / MariaDB 10.4+, `utf8mb4`                                                                 |
| Web server       | Apache with `mod_rewrite` (both `.htaccess` files must work), or Nginx with the same rewrite rules |
| Outbound HTTPS   | To your supplier's API, to `api.github.com` (updates) and to `app.phptravels.com` (licence)        |
| Writable folders | `uploads/`, `app/cache/`, `modules/stays/<name>/logs/`, `modules/stays/<name>/cache/`              |
| Cron             | Ability to add cron jobs (curl) — see Admin → Settings → Automation                                |

#### 2.2 What you need from the supplier <a href="#user-content-22-what-you-need-from-the-supplier" id="user-content-22-what-you-need-from-the-supplier"></a>

Collect these before writing code:

* [ ] &#x20;**Test (sandbox)** and **live (production)** API URLs
* [ ] &#x20;Credentials for both: API key / username / password / client id / agency code, etc.
* [ ] &#x20;IP whitelisting needs (give the supplier the IP of **both** your staging and production servers)
* [ ] &#x20;The **content** method: a static dump (file), a content API, or "hotel info on demand"
* [ ] &#x20;The **booking flow**: is there a separate rate check / prebook step? Is booking synchronous or asynchronous (poll for status)?
* [ ] &#x20;**Test hotels** or test rules: which hotels/rates may be booked in sandbox without being charged
* [ ] &#x20;Cancellation rules: deadlines, penalties, how a cancellation is confirmed
* [ ] &#x20;Certification requirements (many suppliers test your integration before giving live access)

#### 2.3 Environments <a href="#user-content-23-environments" id="user-content-23-environments"></a>

{% hint style="warning" %} **Never develop on the production website.** Use a staging copy of the site (its own domain or subdomain, its own database), with the supplier in **test** mode. Move to production only after the full test plan in section 13 passes. {% endhint %}

Keep staging and production on the **same PHPTRAVELS version**: install every official update on staging first, then on production, before you deploy your module (see section 14).

***

### 3. Create the module <a href="#user-content-3-create-the-module" id="user-content-3-create-the-module"></a>

{% stepper %} {% step %}

#### Create the folder <a href="#user-content-create-the-folder" id="user-content-create-the-folder"></a>

Create `modules/stays/grnconnect/`. The folder name **must be exactly** the lowercase supplier name you will save in the `modules` table, because the core builds URLs as `modules/stays/<lowercase name>/...`.

{% code overflow="wrap" %}

```
modules/stays/grnconnect/├── index.php            # includes everything below (no other code)├── api.php              # one function that calls the supplier (auth, timeouts, logging)├── creds.php            # POST stays/grnconnect/creds    — "Test credentials" button├── search.php           # POST stays/grnconnect/search   — hotel list├── details.php          # POST stays/grnconnect/details  — one hotel├── rooms.php            # POST stays/grnconnect/rooms    — rooms and rates├── prebook.php          # POST stays/grnconnect/prebook  — rate check (if the supplier has one)├── actions/│   ├── issue.php        # POST stays/grnconnect/issue    — book at the supplier after payment│   ├── cancel.php       # POST stays/grnconnect/cancel│   ├── void.php         # POST stays/grnconnect/void│   └── refund.php       # POST stays/grnconnect/refund├── content/             # static content import (optional, see section 5)│   ├── grnconnect-import.php    # admin "Import" tab│   └── imported.php             # admin "Contents" tab├── cache/               # runtime cache (git-ignored)├── logs/                # request/response logs (git-ignored)└── README.md            # your own notes: credentials mapping, flow, contacts
```

{% endcode %}

{% endstep %}

{% step %}

#### Write `index.php` <a href="#user-content-write-indexphp" id="user-content-write-indexphp"></a>

`index.php` only includes the other files. It must not run any other code.

{% code title="modules/stays/grnconnect/index.php" lineNumbers="true" %}

```
<?php// ============================================================================// GRNCONNECT (STAYS) — MODULE ENTRY// INCLUDED BY modules/index.php ON EVERY /modules/* REQUEST: ONLY INCLUDES HERE,// NO CODE THAT RUNS ON ITS OWN.// ============================================================================@$SECURE or die('Access Denied!');
require_once __DIR__ . '/api.php';
include __DIR__ . '/creds.php';include __DIR__ . '/search.php';include __DIR__ . '/details.php';include __DIR__ . '/rooms.php';include __DIR__ . '/prebook.php';include __DIR__ . '/actions/issue.php';include __DIR__ . '/actions/cancel.php';include __DIR__ . '/actions/void.php';include __DIR__ . '/actions/refund.php';
```

{% endcode %} {% endstep %}

{% step %}

#### Register it in the gateway <a href="#user-content-register-it-in-the-gateway" id="user-content-register-it-in-the-gateway"></a>

Open modules/index.php, find the **STAYS MODULES** block, and add one line:

{% code title="modules/index.php" %}

```
include __DIR__ . '/stays/grnconnect/index.php';
```

{% endcode %}

{% hint style="danger" %} **Every module file is included on every module request** (search, rooms, issue… for all suppliers). If any file runs code at the top level, prints output, or throws an error, it breaks **all** suppliers on the site. Put everything inside route closures or inside `if (!function_exists(...))` blocks. {% endhint %} {% endstep %}

{% step %}

#### Add the `modules` row <a href="#user-content-add-the-modules-row" id="user-content-add-the-modules-row"></a>

In the admin go to **Settings → Modules → Add module**:

| Field            | Value                                                                          |
| ---------------- | ------------------------------------------------------------------------------ |
| Name             | `grnconnect` (lowercase, same as the folder)                                   |
| Type             | `stays`                                                                        |
| Currency         | The currency the supplier returns prices in (the **net** currency), e.g. `USD` |
| Environment      | **Test / Sandbox** while you develop                                           |
| Markup B2C / B2B | Your selling markup (percentage or fixed)                                      |
| Tax              | Optional site tax added at checkout (percentage or fixed)                      |
| Logging          | On                                                                             |
| Content import   | On, if you import hotel content (section 5)                                    |

The module appears on the website only when it is **enabled** (Settings → Modules → switch on). The search page asks every enabled stays module in parallel, so a new module adds its hotels to the same results. {% endstep %}

{% step %}

#### Add the logo <a href="#user-content-add-the-logo" id="user-content-add-the-logo"></a>

Save a square PNG as assets/img/modules/grnconnect.png. The admin shows it next to the module name. {% endstep %} {% endstepper %}

#### 3.1 How a route is written <a href="#user-content-31-how-a-route-is-written" id="user-content-31-how-a-route-is-written"></a>

Routes are registered on the gateway router **without** the `/modules` prefix. Each handler reads its input, calls the supplier, and prints JSON:

{% code title="modules/stays/grnconnect/search.php (shape)" %}

```
<?php@$SECURE or die('Access Denied!');
$router->post('stays/grnconnect/search', function () use ($db) {    header('Content-Type: application/json; charset=utf-8');
    // 1. READ THE MODULE ROW (CREDENTIALS, TEST/LIVE, CURRENCY)    $module = $db->get('modules', '*', ['name' => 'grnconnect', 'type' => 'stays']);    if (!$module) {        echo json_encode(['status' => 'error', 'message' => 'Module not configured', 'results' => []]);        return;    }
    // 2. READ THE INPUT, 3. CALL THE SUPPLIER, 4. MAP + MARKUP, 5. PRINT JSON    // ... (see section 6)});
```

{% endcode %}

Rules that apply to every route:

* Always answer **JSON** with `Content-Type: application/json`, also on errors.
* Never `echo` HTML, warnings or debug output. Clean output buffers before printing if a library may print.
* Read credentials from the database row on the server. **Never send credentials to the browser.**
* Use the shared timeouts: connect **10 s**, request **30 s** (constants `SUPPLIER_CONNECT_TIMEOUT` / `SUPPLIER_REQUEST_TIMEOUT`), except where noted for booking.

***

### 4. Credentials <a href="#user-content-4-credentials" id="user-content-4-credentials"></a>

#### 4.1 Where credentials are stored <a href="#user-content-41-where-credentials-are-stored" id="user-content-41-where-credentials-are-stored"></a>

Every module row has six credential columns, **`c1` to `c6`**, plus a test/live switch **`dev_mode`** (`1` = test, `0` = live). There is one set of credentials per module: when you switch from test to live, you change the values in `c1..c6` and turn `dev_mode` off.

Decide your mapping and write it down in your module's `README.md`, for example:

| Column | GRNConnect meaning          | Field type |
| ------ | --------------------------- | ---------- |
| `c1`   | API key                     | password   |
| `c2`   | Username / client id        | text       |
| `c3`   | Password / secret           | password   |
| `c4`   | API base URL (test or live) | text       |
| `c5`   | Agency / account code       | text       |
| `c6`   | (free)                      | —          |

{% hint style="info" %} Putting the **base URL** in a credential field (like RateHawk's `c4`) lets the admin switch between sandbox and live without code changes. Alternatively choose the URL from `dev_mode` in your code (like Hotelbeds). {% endhint %}

#### 4.2 Labels on the admin page <a href="#user-content-42-labels-on-the-admin-page" id="user-content-42-labels-on-the-admin-page"></a>

The labels, help texts and field types shown on **Settings → Modules → grnconnect → Credentials** come from the `$moduleCredentials` array at the top of app/views/admin/settings/modules-settings.php. Add an entry for your module:

{% code title="app/views/admin/settings/modules-settings.php" %}

```
'stays' => [    // ...    'grnconnect' => [        'c1' => ['label' => 'API key',        'required' => true,  'type' => 'password', 'placeholder' => 'Your GRNConnect API key', 'help' => 'From the GRNConnect partner portal'],        'c2' => ['label' => 'Client ID',      'required' => true,  'type' => 'text',     'placeholder' => 'client id'],        'c3' => ['label' => 'Secret',         'required' => true,  'type' => 'password', 'placeholder' => '••••••••'],        'c4' => ['label' => 'API base URL',   'required' => true,  'type' => 'text',     'placeholder' => 'https://api-sandbox.example.com/v3'],        'c5' => ['label' => 'Agency code',    'required' => false, 'type' => 'text',     'placeholder' => 'Optional'],    ],],
```

{% endcode %}

Without an entry, the page shows six generic fields ("Credential 1" … "Credential 6"), which still work.

How saving works:

* Saved secrets (`password` fields) are **never printed back** to the page. The field stays empty and a hidden `keep_cN=1` keeps the stored value when the form is saved again.
* Saving updates `c1..c6`, `dev_mode`, markup, tax and currency of the row.

#### 4.3 Reading credentials at runtime <a href="#user-content-43-reading-credentials-at-runtime" id="user-content-43-reading-credentials-at-runtime"></a>

```
$module  = $db->get('modules', '*', ['name' => 'grnconnect', 'type' => 'stays']);$apiKey  = trim((string) $module['c1']);$baseUrl = rtrim((string) $module['c4'], '/');$isTest  = (string) $module['dev_mode'] === '1';
```

Read the row **inside the route** (not at the top of a file), so a missing row never breaks other modules.

#### 4.4 The "Test credentials" button (`creds.php`) <a href="#user-content-44-the-test-credentials-button-credsphp" id="user-content-44-the-test-credentials-button-credsphp"></a>

The admin credentials tab has a **Test** button. It POSTs the form to `modules/stays/grnconnect/creds` with:

| Field       | Value                                                                                                                                                        |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `c1` … `c6` | The values typed in the form. For secrets that were not retyped, the gateway fills in the **saved** value on the server (only for logged-in administrators). |
| `env`       | `test` or `production`                                                                                                                                       |
| `module_id` | The module row id                                                                                                                                            |

Make the cheapest authenticated call the supplier offers (a "ping", "account info" or a one-hotel availability) and answer:

{% tabs %} {% tab title="Success (HTTP 200)" %}

```
{  "success": true,  "message": "Connected to GRNConnect (sandbox)",  "data": {    "connection_status": "connected",    "api_details": {      "provider": "GRNConnect",      "api_version": "v3",      "response_time": "412 ms",      "supported_services": ["search", "book", "cancel"]    }  },  "metadata": {    "module": "grnconnect",    "service": "stays",    "environment": "test",    "timestamp": "2026-10-19T10:00:00Z",    "response_time_ms": 412  }}
```

{% endtab %}

{% tab title="Failure (HTTP 400)" %}

```
{  "success": false,  "message": "Authentication failed",  "data": {    "error_type": "authentication",    "error_code": "401",    "error_description": "Invalid API key",    "issue": "The API key or secret is wrong, or this server's IP is not whitelisted",    "solutions": [      "Check the API key and secret",      "Ask GRNConnect to whitelist this server's IP address",      "Make sure the base URL matches the environment (sandbox vs live)"    ]  }}
```

{% endtab %} {% endtabs %}

On success the admin page saves the form automatically. Give clear `solutions` on failure: this is what the site owner sees.

***

### 5. Static content import (hotels, images, regions) <a href="#user-content-5-static-content-import-hotels-images-regions" id="user-content-5-static-content-import-hotels-images-regions"></a>

#### 5.1 Why import content <a href="#user-content-51-why-import-content" id="user-content-51-why-import-content"></a>

Most suppliers separate **static content** (hotel name, address, coordinates, stars, images, amenities, description, region) from **availability** (rooms and prices). Calling the supplier for static content on every search is slow and often rate-limited. PHPTRAVELS therefore keeps static content in a local database and calls the supplier live only for prices.

Decide which model your supplier supports:

| Supplier offers                                 | Approach                                                                 |
| ----------------------------------------------- | ------------------------------------------------------------------------ |
| A downloadable dump (JSON/JSONL/CSV/XML file)   | Import the file in **resumable batches** (section 5.3).                  |
| A content API ("hotels by ids / updated since") | **Incremental sync** with a queue table and a cron (section 5.4).        |
| Full content inside the availability response   | No import needed; map it during search.                                  |
| Nothing but "hotel info by id"                  | Cache each hotel's info in your table on first view, refresh after 24 h. |

#### 5.2 Where the content lives <a href="#user-content-52-where-the-content-lives" id="user-content-52-where-the-content-lives"></a>

Each module can use its **own content database**, set on the module's **Database** tab: `host`, `database`, `username`, `password` (with a **Test connection** button). This keeps millions of hotel rows out of the main website database.

{% hint style="warning" %} The Database tab and the saving of these four fields are enabled per module name. Add `grnconnect` to the module-name lists in app/views/admin/settings/modules-settings.php (the `$showDatabaseTab` list) and app/routes/admin/modulesRoutes.php (the list of modules whose content-database fields are saved). Without this, the fields are not shown or not saved. {% endhint %}

Open the content database inside your routes:

```
$content = new \Medoo\Medoo([    'type'     => 'mysql',    'host'     => $module['host'],    'database' => $module['database'],    'username' => $module['username'],    'password' => $module['password'],    'charset'  => 'utf8mb4',]);
```

**Table naming:** prefix every table with your module name: `grnconnect_hotels`, `grnconnect_regions`, `grnconnect_import_progress`. Never reuse a name that exists in PHPTRAVELS' install/db.sql.

**Creating tables:** there is no migration runner. Create your tables with `CREATE TABLE IF NOT EXISTS` from your **import code** (an `ensureTables()` function), never from search/rooms requests. A suggested minimum:

{% code title="grnconnect\_hotels (suggested)" %}

```
CREATE TABLE IF NOT EXISTS `grnconnect_hotels` (  `id`           INT UNSIGNED NOT NULL AUTO_INCREMENT,  `hotel_code`   VARCHAR(64)  NOT NULL,            -- the supplier's hotel id (no "/" allowed)  `name`         VARCHAR(255) NOT NULL,  `address`      VARCHAR(500) DEFAULT NULL,  `city`         VARCHAR(150) DEFAULT NULL,  `city_code`    VARCHAR(64)  DEFAULT NULL,  `country`      VARCHAR(100) DEFAULT NULL,  `country_code` CHAR(2)      DEFAULT NULL,  `latitude`     DECIMAL(10,7) DEFAULT NULL,  `longitude`    DECIMAL(10,7) DEFAULT NULL,  `stars`        DECIMAL(2,1) DEFAULT NULL,  `images`       JSON         DEFAULT NULL,        -- ["https://...", ...]  `amenities`    JSON         DEFAULT NULL,        -- ["Wi-Fi", "Pool", ...]  `description`  MEDIUMTEXT   DEFAULT NULL,  `check_in`     VARCHAR(20)  DEFAULT NULL,  `check_out`    VARCHAR(20)  DEFAULT NULL,  `is_active`    TINYINT(1)   NOT NULL DEFAULT 1,  `updated_at`   DATETIME     DEFAULT NULL,  PRIMARY KEY (`id`),  UNIQUE KEY `uq_hotel_code` (`hotel_code`),  KEY `idx_city` (`city`),  KEY `idx_city_code` (`city_code`),  KEY `idx_country` (`country_code`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

{% endcode %}

#### 5.3 Importing a dump file (resumable batches) <a href="#user-content-53-importing-a-dump-file-resumable-batches" id="user-content-53-importing-a-dump-file-resumable-batches"></a>

Large dumps (hundreds of MB to several GB) cannot be imported in one request. Use the same pattern as RateHawk and Hotelston:

1. The admin places the file in the module's `content/` folder (or the import downloads it).
2. A **progress table** stores `file_offset` (bytes), `file_size`, `imported`, `status` (`running`, `paused`, `done`, `error`), `updated_at`.
3. Each import call: `fseek()` to the saved offset, read and **upsert** about 1,000 lines, save the new offset with `ftell()`, and return progress JSON.
4. The admin **Import** tab calls the import repeatedly (AJAX polling) until `done`, showing a progress bar. A **Pause** button sets `status=paused`, which the loop checks between batches.
5. A bad line is logged and **skipped**; the offset still moves on, so one bad record never blocks the import.
6. Upsert by `hotel_code` (`INSERT ... ON DUPLICATE KEY UPDATE`), so running the import twice is safe.
7. Raise limits only inside the import handler: `set_time_limit(300)`, `ini_set('memory_limit', '1G')`, and stream the file — never `file_get_contents()` a large dump.

For a **full replacement** (a new dump every week), import into a staging table (`CREATE TABLE grnconnect_hotels_new LIKE grnconnect_hotels`) and swap atomically with `RENAME TABLE`, so searches never see a half-imported table (Hotelbeds does this).

The admin **Import** and **Contents** tabs appear when the module's **Content import** switch is on. They include modules/stays/grnconnect/content/grnconnect-import.php (your import screen) and modules/stays/grnconnect/content/imported.php (a list/search of imported hotels).

{% hint style="danger" %} Import endpoints change the database. Check that the caller is a logged-in administrator before running any import, reset or delete action. {% endhint %}

#### 5.4 Incremental sync with a content API <a href="#user-content-54-incremental-sync-with-a-content-api" id="user-content-54-incremental-sync-with-a-content-api"></a>

If the supplier offers "hotel ids updated since" and "content by ids":

1. **Discover:** fetch changed hotel ids since the last run and upsert them into a queue table `grnconnect_content_queue(hotel_code, needs_content, attempts, last_error, queued_at)`. Save the time of this call as the new watermark.
2. **Sync:** take 100 queued ids (the usual API maximum), fetch their content, upsert into `grnconnect_hotels`, mark them done. Ids that fail get `attempts+1`; after 4 attempts they are parked and reported.
3. **Time budget:** each run works for a fixed number of seconds and stops cleanly; the next run continues from the queue.
4. **Deleted / closed hotels:** set `is_active=0` (or delete) so search skips them.

Run the sync daily from a cron route and list it on **Settings → Automation** so the site owner can see the cron line and the last run (see section 11.4).

#### 5.5 Destination search box (autocomplete) <a href="#user-content-55-destination-search-box-autocomplete" id="user-content-55-destination-search-box-autocomplete"></a>

The search box suggests cities, areas and hotels from `POST /hotels-destination-suggestion`. It reads the site's own hotels and locations, and the content tables of the suppliers listed in the `$apiModuleTables` map in app/routes/stays/destinationSuggestionRoutes.php.

To make your imported cities and hotels appear in the box, add an entry for your module with your table and column names (`table`, `id_col`, `name_col`, `city_col`, and optional destination/zone/country tables). Your search route then receives the chosen place as `destination`, `destination_code`, `destination_zone` and `destination_country` (section 6).

***

### 6. Search <a href="#user-content-6-search" id="user-content-6-search"></a>

#### 6.1 Request <a href="#user-content-61-request" id="user-content-61-request"></a>

The listing page POSTs **form data** (`multipart/form-data`) to `modules/stays/grnconnect/search` once per page of results.

| Field                 | Example                                                                                | Notes                                              |
| --------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------- |
| `destination`         | `Dubai`                                                                                | City/area name, or a code chosen in the search box |
| `destination_code`    | `DXB`                                                                                  | Optional code from the search box                  |
| `destination_zone`    | `Deira`                                                                                | Optional                                           |
| `destination_country` | `AE`                                                                                   | Optional                                           |
| `checkin`             | `20-11-2026`                                                                           | **dd-mm-yyyy**                                     |
| `checkout`            | `23-11-2026`                                                                           | **dd-mm-yyyy**                                     |
| `nationality`         | `PK`                                                                                   | ISO 3166-1 alpha-2                                 |
| `rooms`               | `2`                                                                                    | Number of rooms                                    |
| `adults`              | `3`                                                                                    | Total adults                                       |
| `children`            | `1`                                                                                    | Total children                                     |
| `rooms_data`          | `[{"adults":2,"children":1,"childAges":[5]},{"adults":1,"children":0,"childAges":[]}]` | JSON string, one object per room                   |
| `currency`            | `PKR`                                                                                  | The visitor's display currency                     |
| `language`            | `en`                                                                                   | The visitor's language                             |
| `page`                | `1`                                                                                    | Page number                                        |
| `per_page`            | `20`                                                                                   | Results per page                                   |
| `hotel_name`          | `Hilton`                                                                               | Optional name filter                               |

#### 6.2 What the route does <a href="#user-content-62-what-the-route-does" id="user-content-62-what-the-route-does"></a>

1. Read the module row and the input. Validate dates (check-in not in the past, check-out after check-in) and the room configuration.
2. Resolve the destination to the supplier's city/region code (from your content tables).
3. Call the supplier's availability search. Use a short, fixed timeout: a slow supplier must not hold the whole results page.
4. For each hotel with availability, join your local content (name, images, address, stars) by hotel code. **Skip hotels without content** rather than showing empty cards.
5. Apply markup and convert currency with `MARKUP()` (section 10).
6. Cache the mapped result for a few minutes (e.g. `cache/search_<sha256 of the request>.json`, 10 min), and paginate from the cache.
7. Return JSON (6.3).

#### 6.3 Response <a href="#user-content-63-response" id="user-content-63-response"></a>

{% code title="200 OK" %}

```
{  "status": "success",  "results": [    {      "id": "GRN123456",      "hotel_id": "GRN123456",      "name": "Example Grand Hotel",      "stars": 4,      "rating": 8.6,      "address": "Sheikh Zayed Road, Dubai",      "city": "Dubai",      "country": "United Arab Emirates",      "location": "Dubai, United Arab Emirates",      "latitude": 25.2048,      "longitude": 55.2708,      "image": "https://cdn.example.com/hotels/123456/main.jpg",      "images": ["https://cdn.example.com/hotels/123456/1.jpg", "https://cdn.example.com/hotels/123456/2.jpg"],      "price": 58230.50,      "price_per_night": 19410.17,      "original_price": 182.40,      "original_currency": "USD",      "currency": "PKR",      "nights": 3,      "meal": "Breakfast included",      "refundable": true,      "has_available_rooms": true,      "supplier": "grnconnect"    }  ],  "total": 342,  "page": 1,  "per_page": 20,  "total_pages": 18,  "has_more": true}
```

{% endcode %}

| Field                                  | Meaning                                                                                    |
| -------------------------------------- | ------------------------------------------------------------------------------------------ |
| `hotel_id` / `id`                      | The supplier's hotel id. It is used in the hotel page URL, so it **must not contain `/`**. |
| `price`                                | Total for the whole stay and all rooms, **after markup**, in the display `currency`.       |
| `price_per_night`                      | `price / nights`.                                                                          |
| `original_price` / `original_currency` | The supplier's **net** price before markup, in the supplier currency.                      |
| `currency`                             | The display currency (the `currency` you received).                                        |
| `supplier`                             | Your module name.                                                                          |

Optional response headers the listing page reads: `X-Total-Results`, `X-Total-Pages`, `X-Current-Page`, `X-Has-More`, and `X-Supplier-Notice` (a URL-encoded message shown to the visitor, e.g. "Some hotels could not be priced").

**No results or an error:** answer `{"status":"error","message":"...","results":[],"has_more":false}`. The page shows other suppliers' hotels and simply has none from yours, so never let an exception or a PHP warning reach the output.

***

### 7. Hotel details <a href="#user-content-7-hotel-details" id="user-content-7-hotel-details"></a>

The hotel page URL contains the supplier **module id** and the hotel id:

{% code overflow="wrap" %}

```
/stay/{hotel-slug}/{hotel_id}/{module_id}/{checkin}/{checkout}/{nationality}/{rooms}/{adults-children-ages…}
```

{% endcode %}

The page POSTs **JSON** to `modules/stays/grnconnect/details`:

```
{  "hotel_id": "GRN123456",  "supplier": "grnconnect",  "checkin": "20-11-2026",  "checkout": "23-11-2026",  "nationality": "PK",  "rooms": [{ "adults": 2, "children": 1, "childAges": [5] }],  "currency": "PKR",  "address": "...", "city": "Dubai", "country": "United Arab Emirates",  "rating": 8.6, "stars": 4}
```

Read JSON input with `json_decode(file_get_contents('php://input'), true)`.

Answer from your **local content** (call the supplier only if a field is missing, and store the result):

{% code title="200 OK" %}

```
{  "success": true,  "data": {    "id": "GRN123456",    "name": "Example Grand Hotel",    "description": "<p>Hotel description (safe HTML)</p>",    "address": "Sheikh Zayed Road",    "city": "Dubai",    "country": "United Arab Emirates",    "country_code": "AE",    "postal_code": "00000",    "location": "Dubai, United Arab Emirates",    "latitude": 25.2048,    "longitude": 55.2708,    "stars": 4,    "rating": 8.6,    "images": ["https://cdn.example.com/hotels/123456/1.jpg"],    "amenities": ["Free Wi-Fi", "Swimming pool", "Airport shuttle"],    "check_in_time": "14:00",    "check_out_time": "12:00",    "hotel_policies": "<ul><li>Pets are not allowed</li></ul>",    "cancellation_policy": "Cancellation rules depend on the selected rate.",    "email": "", "phone_number": "",    "supplier": "grnconnect",    "checkin": "20-11-2026",    "checkout": "23-11-2026",    "rooms": []  }}
```

{% endcode %}

Errors: `{"success": false, "message": "Hotel not found"}` — the page shows the message.

***

### 8. Rooms and rates <a href="#user-content-8-rooms-and-rates" id="user-content-8-rooms-and-rates"></a>

The hotel page then POSTs **JSON** to `modules/stays/grnconnect/rooms`:

```
{  "hotel_id": "GRN123456",  "supplier": "grnconnect",  "checkin": "20-11-2026",  "checkout": "23-11-2026",  "destination": "Dubai",  "rooms": 1,  "adults": 2,  "children": 1,  "rooms_data": [{ "adults": 2, "children": 1, "childAges": [5] }],  "nationality": "PK",  "currency": "PKR"}
```

Call the supplier's live rates for this hotel and return rooms, each with one or more **options** (rates):

{% code title="200 OK" %}

```
{  "success": true,  "data": {    "hotel_id": "GRN123456",    "checkin": "20-11-2026",    "checkout": "23-11-2026",    "nights": 3,    "currency": "PKR",    "live_pricing": true,    "rooms": [      {        "room_id": "DLX-KING",        "room_name": "Deluxe King Room",        "description": "32 m², city view",        "size_sqm": 32,        "max_adults": 2,        "max_children": 1,        "bed_type": "1 King bed",        "amenities": [{ "id": "wifi", "name": "Free Wi-Fi" }],        "room_images": ["https://cdn.example.com/rooms/dlx-1.jpg"],        "room_main_image": "https://cdn.example.com/rooms/dlx-1.jpg",        "min_price_per_night": 19410.17,        "options": [          {            "option_id": "R1",            "rate_key": "SUPPLIER-RATE-TOKEN-ABC123",            "board_name": "Breakfast included",            "board_code": "BB",            "breakfast_included": true,            "refundable": true,            "cancellation_free": true,            "price_per_night": 19410.17,            "total_price": 58230.50,            "currency": "PKR",            "original_price": 182.40,            "supplier_amount": 182.40,            "supplier_currency": "USD",            "adults": 2,            "children": 1,            "available_quantity": 3,            "excluded_taxes": [              { "name": "Tourism dirham fee", "amount": 15.00, "currency_code": "AED" }            ],            "cancellation_policy": {              "has_free_cancellation": true,              "free_cancellation_before": "2026-11-17T23:59:00Z",              "free_cancellation_before_label": "17 Nov 2026, 23:59 (UTC)",              "layers": [                { "from": null, "to": "2026-11-17T23:59:00Z", "amount": 0, "is_free": true },                { "from": "2026-11-17T23:59:00Z", "to": null, "amount": 19410.17, "is_free": false }              ],              "text": "Free cancellation until 17 Nov 2026, 23:59 (UTC). After that, the first night is charged."            }          }        ]      }    ]  }}
```

{% endcode %}

| Option field                                               | Meaning                                                                                                                                     |
| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `rate_key` (or `book_hash`)                                | The supplier token you need later to check and book this rate. Keep everything needed to book in the option; it is stored with the booking. |
| `total_price`                                              | Whole stay, this option, **after markup**, display currency.                                                                                |
| `original_price` / `supplier_amount` / `supplier_currency` | The net amount you will pay the supplier. The core stores it to calculate your commission.                                                  |
| `available_quantity`                                       | How many of this rate can be booked.                                                                                                        |
| `excluded_taxes`                                           | Taxes paid **at the hotel** (not in the price). Shown separately as "Payable at hotel".                                                     |
| `cancellation_policy`                                      | Deadlines and penalties. Always show times with their time zone.                                                                            |

{% hint style="danger" %} **Never return placeholder or estimated prices.** If the supplier's rates call fails, answer `{"success": false, "message": "Rooms are not available right now. Please try again."}` so nobody can book a room at a price that does not exist. {% endhint %}

***

### 9. Rate check, booking and issue <a href="#user-content-9-rate-check-booking-and-issue" id="user-content-9-rate-check-booking-and-issue"></a>

#### 9.1 Rate check / prebook (if your supplier has one) <a href="#user-content-91-rate-check--prebook-if-your-supplier-has-one" id="user-content-91-rate-check--prebook-if-your-supplier-has-one"></a>

Many suppliers require a **rate check** (also called prebook, revalidate or check-availability) before booking, which confirms the price and may return a new booking token.

Implement it as `POST stays/grnconnect/prebook`:

{% tabs %} {% tab title="Request" %}

```
{ "rate_key": "SUPPLIER-RATE-TOKEN-ABC123", "hotel_id": "GRN123456", "checkin": "20-11-2026", "checkout": "23-11-2026", "rooms_data": [{ "adults": 2, "children": 1, "childAges": [5] }], "currency": "PKR" }
```

{% endtab %}

{% tab title="Response: OK" %}

```
{  "success": true,  "data": {    "rate_key": "SUPPLIER-BOOKING-TOKEN-XYZ",    "price_changed": false,    "total_price": 58230.50,    "supplier_amount": 182.40,    "supplier_currency": "USD",    "cancellation_policy": { "has_free_cancellation": true, "text": "..." }  }}
```

{% endtab %}

{% tab title="Response: price changed" %}

```
{  "success": true,  "data": {    "rate_key": "SUPPLIER-BOOKING-TOKEN-XYZ",    "price_changed": true,    "old_total_price": 58230.50,    "total_price": 59105.00,    "supplier_amount": 185.10,    "supplier_currency": "USD"  }}
```

{% endtab %}

{% tab title="Response: sold out" %}

```
{ "success": false, "message": "This rate is no longer available. Please choose another room." }
```

{% endtab %} {% endtabs %}

**Where the core calls it:** the rate check runs when the visitor selects a rate on the hotel page (app/views/modules/stays/details/rooms.php) and/or on the checkout page (app/views/modules/stays/booking/index.php). These pages have one branch per supplier that needs a rate check (for example `ratehawk`, `hotelbeds`, `tbo-holidays`, `wanderbeds`). Add a branch for your module in the same style:

* call your `prebook` endpoint,
* if the price changed, update the selected option (the core then saves it with `POST /api/stay/booking/update-draft`) and tell the visitor,
* if the rate is gone, unselect it and show the message.

Do the rate check **again** inside `issue` right before booking: prices can change between checkout and payment.

#### 9.2 How the booking is created (the core does this) <a href="#user-content-92-how-the-booking-is-created-the-core-does-this" id="user-content-92-how-the-booking-is-created-the-core-does-this"></a>

You do not create the booking row. The flow is:

1. The visitor selects rooms. The core saves a **draft** (`POST /api/stay/booking/save-draft`) containing the hotel, dates, `rooms_data`, nationality and **`selected_rooms`** — each selected option **with every field you returned** (including your `rate_key`).
2. The visitor fills the guest form on `/stays/booking/{draft}` and submits.
3. The core inserts a row into **`bookings`** with `module='grnconnect'`, `module_type='stays'`, `booking_status='pending'`, `payment_status='unpaid'`, the draft JSON in `booking_data`, the guests in `travellers`, the net price in `price_original` and the selling price in `price_markup`. The visitor is sent to the invoice page `/invoice/stays/{invoice_id}`.
4. The visitor pays (card gateway, wallet, bank transfer or pay later).
5. When payment succeeds and **Settings → Auto-Issue After Payment** is on, the **server** calls your `issue` endpoint.

The fields your `issue` endpoint will use from the `bookings` row:

| Column                                      | Content                                                                                                                                                         |
| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `invoice_id`                                | The booking reference on the website                                                                                                                            |
| `booking_data`                              | JSON: `hotel_id`, `checkin`, `checkout`, `nationality`, `rooms_data`, `selected_rooms[].option` (your option, with `rate_key`), `total_amount`, `actual_amount` |
| `travellers`                                | JSON: one entry per guest (title, first name, last name, type, age, room)                                                                                       |
| `first_name`, `last_name`, `email`, `phone` | The lead guest / contact                                                                                                                                        |
| `price_original`                            | Net amount (your cost)                                                                                                                                          |
| `price_markup`                              | Amount the customer paid                                                                                                                                        |
| `payment_status`                            | Must be `paid` before you book                                                                                                                                  |

#### 9.3 Issue (book at the supplier) <a href="#user-content-93-issue-book-at-the-supplier" id="user-content-93-issue-book-at-the-supplier"></a>

`POST stays/grnconnect/issue` receives **form data**:

| Field        | Meaning                                                          |
| ------------ | ---------------------------------------------------------------- |
| `invoice_id` | The booking to issue                                             |
| `sig`        | A server signature. The gateway checks it before your code runs. |

Only two callers can reach `issue`, `cancel`, `void` and `refund`: the website's own server (with a valid `sig`), and a logged-in administrator (or an employee with the matching booking permission) for a **paid** booking. You do not need to check this yourself, but **never** remove or bypass it.

What `issue` must do:

1. Load the booking by `invoice_id`. Stop if it is not paid, or if it already has a `pnr` (**idempotency**: a booking must never be booked twice at the supplier).
2. Take the `rate_key` from `booking_data.selected_rooms[*].option`, and the guests from `travellers`.
3. Re-check the rate (if the supplier supports it). If the price went **up** beyond a small tolerance, do not book; answer a failure with a clear message so an administrator can decide.
4. Book at the supplier with a client reference (use `invoice_id`), so a retried request can be matched instead of creating a duplicate.
5. Save what you got back into the booking (supplier booking id, confirmation number, raw response) — for example into `booking_data.grnconnect_booking`, and the response JSON into `booking_response`.
6. Answer JSON (below).

{% tabs %} {% tab title="Success (HTTP 200)" %}

```
{  "status": true,  "success": true,  "Prn": "GRN-88442211",  "pnr": "GRN-88442211",  "booking_reference": "GRN-88442211",  "reference": "GRN-88442211",  "booking_status": "confirmed",  "message": "Booking confirmed",  "response_error": "",  "invoice_id": "A1B2C3D4",  "data": { "supplier_booking_id": "88442211", "hotel_confirmation": "HC-7781" }}
```

{% endtab %}

{% tab title="Pending at supplier (HTTP 200)" %}

```
{  "status": true,  "success": true,  "Prn": "GRN-88442211",  "pnr": "GRN-88442211",  "booking_status": "pending",  "message": "Booking received; the supplier is confirming it"}
```

{% endtab %}

{% tab title="Failure (HTTP 400)" %}

```
{  "status": false,  "success": false,  "Prn": "",  "message": "The rate is no longer available at the booked price",  "error": "price_changed",  "response_error": "price_changed"}
```

{% endtab %} {% endtabs %}

How the core uses your answer:

* **Success** = `status` or `success` is `true`. The supplier reference is read from `Prn`, `pnr`, `confirmation_number`, `booking_reference` or `reference` (send all). The booking gets `booking_status` from your answer (default `confirmed`), the reference is saved as `pnr`, the customer and the administrators are notified, and the voucher PDF is generated.
* **Failure** keeps the booking `pending` and **paid**, saves your message, and notifies the administrators ("booking needs attention"). An administrator can retry with **Issue booking** on the admin booking page, or refund the customer.
* `booking_status` can only be `confirmed`, `pending` or `cancelled`. Keep finer states (for example "processing at supplier") inside `booking_data`.

**Timeouts:** the server waits up to **300 seconds** for `issue`. If your supplier's booking can take longer, book **asynchronously**: start the booking, answer `pending` quickly, and finish it with a status check (a `bookinfo`/`status` action called by a cron or by the invoice page), as RateHawk does.

#### 9.4 Cancel, void and refund <a href="#user-content-94-cancel-void-and-refund" id="user-content-94-cancel-void-and-refund"></a>

The admin booking page (**Bookings → edit**) has **Cancel**, **Void** and **Refund** buttons. Each POSTs `invoice_id` to your module:

| Endpoint                       | Meaning                                                                 | After success, set                                                                                      |
| ------------------------------ | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `POST stays/grnconnect/cancel` | Cancel the booking at the supplier (penalties may apply)                | `booking_status='cancelled'`, `cancellation_status=1`, `cancellation_response` = supplier response JSON |
| `POST stays/grnconnect/void`   | Cancel a booking created by mistake / within the supplier's void window | `booking_status='cancelled'`, `cancellation_response` with `"status":"voided"`                          |
| `POST stays/grnconnect/refund` | Cancel and mark the payment refunded                                    | as cancel, plus `payment_status='refunded'`                                                             |

Answer:

```
{ "status": true, "success": true, "message": "Booking cancelled at GRNConnect. Penalty: 0.00 USD", "data": { "cancellation_id": "C-5521", "penalty": 0, "currency": "USD" } }
```

or `{ "status": false, "success": false, "message": "Cancellation deadline has passed" }`.

Notes:

* Read the booking's supplier id from what `issue` saved. Refuse if the booking was never issued (no `pnr`).
* Store the supplier's penalty amount in `cancellation_response`, so the administrator knows what to refund.
* Changing `payment_status` to `refunded` does **not** move money. The refund itself is done in the payment gateway (or the customer's wallet) by the administrator.
* Customers do not cancel directly: the **Request cancellation** button on the invoice only flags the booking (`cancellation_request=1`) and notifies the administrators, who then use the buttons above.

***

### 10. Pricing: markup, currency and tax <a href="#user-content-10-pricing-markup-currency-and-tax" id="user-content-10-pricing-markup-currency-and-tax"></a>

#### 10.1 Always use `MARKUP()` <a href="#user-content-101-always-use-markup" id="user-content-101-always-use-markup"></a>

Never calculate markup yourself. Call the shared helper for every price you return:

```
// $net = the supplier's price, in the supplier currency ($module['currency'] or the currency of the response)$priced = MARKUP($net, 'grnconnect', $db, $supplierCurrency, $displayCurrency);
$sell     = round((float) $priced['price'], 2);   // selling price, display currency$markup   = $priced['markup'];                    // markup amount$netShown = $priced['converted_base_price'];      // net converted to the display currency
```

`MARKUP()`:

1. picks the **B2B** markup for agents and the **B2C** markup for everyone else (a customer's own custom markup overrides both),
2. applies it in the **supplier currency** (a fixed markup, set in the site's default currency, is converted first),
3. converts the result to the display currency with the rates on **Settings → Currencies** (updated daily by the currency cron).

#### 10.2 Currencies <a href="#user-content-102-currencies" id="user-content-102-currencies"></a>

* Return prices in the **display currency** you receive (`currency`), and the net price in the **supplier currency** (`original_price` / `supplier_amount` + `supplier_currency`).
* The core converts the selected price to the site's **base currency** when it saves the booking.
* Set the module's **Currency** field to the supplier's net currency.

#### 10.3 Tax <a href="#user-content-103-tax" id="user-content-103-tax"></a>

* **Site tax** (Settings → Modules → grnconnect → tax, percentage or fixed) is added by the core at checkout. Do not add it in your module.
* **Taxes payable at the hotel** (city tax, tourism fee) go in `excluded_taxes` and are shown separately; they are not part of `total_price`.
* If the supplier's price **includes** taxes and fees, return the full amount as the net price.

#### 10.4 Price changes <a href="#user-content-104-price-changes" id="user-content-104-price-changes"></a>

Between search and booking a price can change. Recommended policy:

* At **rate check**: accept a small increase (for example up to 2%) and show the new price; reject anything larger and ask the visitor to choose again.
* At **issue**: never book above the price the customer paid (plus your accepted tolerance). Fail with a clear message instead; the booking stays paid and pending for an administrator.

***

### 11. Logging, errors and security <a href="#user-content-11-logging-errors-and-security" id="user-content-11-logging-errors-and-security"></a>

#### 11.1 Log every supplier call <a href="#user-content-111-log-every-supplier-call" id="user-content-111-log-every-supplier-call"></a>

Write one request file and one response file per call in `modules/stays/grnconnect/logs/`:

{% code overflow="wrap" %}

```
logs/search_request_2026-11-20_10-15-02_6543abcd.jsonlogs/search_response_2026-11-20_10-15-02_6543abcd.jsonlogs/issue_A1B2C3D4_request_2026-11-20_10-30-44_6543abce.json
```

{% endcode %}

* Include: endpoint, method, HTTP status, duration, request body, response body.
* **Mask secrets** (API keys, passwords, `Authorization` headers, card data).
* Truncate very large search responses (e.g. > 200 KB).
* Respect the module's **Logging** switch (`modules.logging_enabled`) for search and rooms; always log `issue`, `cancel`, `void` and `refund`.
* The admin can list, download and delete these files on the module's **Logs** tab. Add `grnconnect` to the list of module names that show the Logs tab in app/views/admin/settings/modules-settings.php.

Suppliers ask for these logs (request + response of a booking) during certification and when you report a problem. Keep them at least 30 days.

#### 11.2 Error answers <a href="#user-content-112-error-answers" id="user-content-112-error-answers"></a>

| Endpoint                            | On error answer                                                                             |
| ----------------------------------- | ------------------------------------------------------------------------------------------- |
| `search`                            | `{"status":"error","message":"...","results":[],"has_more":false}`                          |
| `details`, `rooms`, `prebook`       | `{"success":false,"message":"..."}` — the message is shown to the visitor, so make it human |
| `issue`, `cancel`, `void`, `refund` | `{"status":false,"success":false,"message":"...","response_error":"..."}` with HTTP 400     |
| `creds`                             | `{"success":false,"message":"...","data":{"issue":"...","solutions":[...]}}` with HTTP 400  |

Never show raw supplier errors, SQL errors, file paths or stack traces to visitors. Write the details to your log and show a short, clear message.

#### 11.3 Security rules <a href="#user-content-113-security-rules" id="user-content-113-security-rules"></a>

* Credentials stay on the server. Never put them in a response, a page, JavaScript or a log file.
* Use prepared queries / Medoo for every database query; never put request values into SQL strings.
* Validate every input (dates, numbers, ISO codes, ids) before sending it to the supplier.
* Do not weaken the booking-action guard: `issue`, `cancel`, `void` and `refund` must only run for the server or an authorised administrator.
* Book only **paid** bookings, and only once.
* Protect import/reset/delete endpoints with an administrator check.
* Use HTTPS to the supplier and keep certificate verification on.

#### 11.4 Cron jobs (content sync, booking status) <a href="#user-content-114-cron-jobs-content-sync-booking-status" id="user-content-114-cron-jobs-content-sync-booking-status"></a>

If your module needs a scheduled job (daily content sync, checking pending bookings), expose it as a GET route and list it on **Settings → Automation**. That page shows each job with its cron line, schedule and last run. Every job is called with curl:

{% code overflow="wrap" %}

```
0 4 * * * curl -s "https://your-site.com/grnconnect_content_sync" > /dev/null 2>&1
```

{% endcode %}

A job must:

* stop within a time budget (e.g. 4–5 minutes) and continue next time,
* never run twice at the same time (store "started at" before working),
* record its last run so the Automation page shows it.

***

### 12. Things to add in core files (wiring checklist) <a href="#user-content-12-things-to-add-in-core-files-wiring-checklist" id="user-content-12-things-to-add-in-core-files-wiring-checklist"></a>

PHPTRAVELS v10 does not discover modules automatically. A complete stays module touches these places:

| # | File                                                                               | What to add                                                           | Needed                                                |
| - | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------- | ----------------------------------------------------- |
| 1 | modules/index.php                                                                  | `include __DIR__ . '/stays/grnconnect/index.php';` in the STAYS block | Always                                                |
| 2 | Admin → Settings → Modules                                                         | The `modules` row (name, type `stays`, currency, markup, test mode)   | Always                                                |
| 3 | assets/img/modules/grnconnect.png                                                  | Logo                                                                  | Always                                                |
| 4 | app/views/admin/settings/modules-settings.php                                      | Credential labels (`$moduleCredentials['stays']['grnconnect']`)       | Recommended                                           |
| 5 | app/views/admin/settings/modules-settings.php + app/routes/admin/modulesRoutes.php | Your name in the content-database lists and the Logs list             | If you use a content DB / logs tab                    |
| 6 | app/routes/stays/destinationSuggestionRoutes.php                                   | Your tables in `$apiModuleTables`                                     | If your cities/hotels should appear in the search box |
| 7 | app/views/modules/stays/details/rooms.php and/or booking/index.php                 | A rate-check branch for your supplier                                 | If the supplier needs a rate check                    |
| 8 | app/lib/payment-gateway.php                                                        | A longer issue timeout for your supplier                              | Only if booking takes more than 300 s                 |
| 9 | app/lib/automation.php + a cron route                                              | Your scheduled jobs                                                   | If you have cron jobs                                 |

{% hint style="warning" %} Items 1 and 4–9 are **official files**. An official update that changes one of them replaces it with the official version and **removes your lines**. Keep a written list of these edits and re-check them after every update (section 15), or ask PHPTRAVELS to include your module in the official release (section 15.3). {% endhint %}

***

### 13. Testing <a href="#user-content-13-testing" id="user-content-13-testing"></a>

#### 13.1 Set up the test environment <a href="#user-content-131-set-up-the-test-environment" id="user-content-131-set-up-the-test-environment"></a>

* Staging website with the module in **Test / Sandbox** mode and sandbox credentials.
* A payment gateway in **test mode** too. Test mode of the module and of the gateway must **match**: a paid test booking with a live gateway (or the opposite) is not issued automatically.
* Card gateways have test cards (for example Stripe `4242 4242 4242 4242`, any future date, any CVC). **Pay later** and **Wallet** need no card.
* **Settings → Auto-Issue After Payment** on, to test the automatic issue.

#### 13.2 Test plan <a href="#user-content-132-test-plan" id="user-content-132-test-plan"></a>

Run every case and keep the request/response logs: suppliers usually ask for them.

| #  | Case                                                  | Expected                                                                        |
| -- | ----------------------------------------------------- | ------------------------------------------------------------------------------- |
| 1  | Test credentials (right, wrong key, wrong URL)        | Success message / clear failure with solutions                                  |
| 2  | Content import from scratch, pause, resume, run again | Progress, no duplicates, resumes from the same point                            |
| 3  | Search a big city, 1 room 2 adults                    | Hotels with images and prices, pages 1–3 load                                   |
| 4  | Search 2 rooms, child with age, different nationality | Correct occupancy sent; prices match the supplier                               |
| 5  | Search with no availability / unknown city            | Empty result, no error on the page                                              |
| 6  | Supplier down / timeout                               | Other suppliers' results still show                                             |
| 7  | Hotel page and rooms                                  | Description, images, rooms, boards, cancellation text with time zone            |
| 8  | Refundable and non-refundable rates                   | Labels and policies correct                                                     |
| 9  | Rate check: same price / price up / sold out          | Continue / new price shown / rate unselected                                    |
| 10 | Book and pay (test card)                              | `issue` called once, `pnr` saved, status confirmed, voucher PDF and emails sent |
| 11 | Pay twice / refresh the payment return page           | Booked **once** at the supplier                                                 |
| 12 | Issue fails (sold out at booking)                     | Booking stays paid + pending, admin notified, clear message                     |
| 13 | Admin "Issue booking" retry                           | Works only for a paid booking without `pnr`                                     |
| 14 | Cancel within free period                             | Cancelled at supplier, penalty 0, status cancelled                              |
| 15 | Cancel after the deadline                             | Penalty returned and stored                                                     |
| 16 | Void / refund                                         | Status and payment status updated                                               |
| 17 | Agent account (B2B) vs customer (B2C)                 | Different markup applied                                                        |
| 18 | Different display currencies                          | Converted prices, net stays in supplier currency                                |
| 19 | Mobile layout                                         | Listing, hotel, checkout work                                                   |
| 20 | Logs                                                  | Request/response files written, secrets masked                                  |

***

### 14. Deploying from staging to production <a href="#user-content-14-deploying-from-staging-to-production" id="user-content-14-deploying-from-staging-to-production"></a>

This is the safe order to move a finished integration to the live website.

{% stepper %} {% step %}

#### Freeze and compare <a href="#user-content-freeze-and-compare" id="user-content-freeze-and-compare"></a>

* Stop changing code on staging.
* Make sure staging and production run the **same PHPTRAVELS version**: open `/updates` on both and install all pending official updates on **both** first.
* Make a list of every file you **added** and every official file you **changed** (with `git status` / `git diff`, or by comparing the two servers). Usually:
  * added: `modules/stays/grnconnect/**`, assets/img/modules/grnconnect.png, your cron route (if any)
  * changed: the official files from the table in section 12 {% endstep %}

{% step %}

#### Back up production <a href="#user-content-back-up-production" id="user-content-back-up-production"></a>

* Full database export (`mysqldump`) of the website database **and** of the content database if it is separate.
* A copy of the website files (or at least every file you will touch).
* Note the exact time; keep the backup until the module has run in production for a few weeks. {% endstep %}

{% step %}

#### Prepare the supplier side <a href="#user-content-prepare-the-supplier-side" id="user-content-prepare-the-supplier-side"></a>

* Get **live** credentials and the live API URL from the supplier (after certification).
* Ask the supplier to whitelist the **production** server's IP address.
* Confirm the live booking/cancellation rules and the support contact. {% endstep %}

{% step %}

#### Copy the files <a href="#user-content-copy-the-files" id="user-content-copy-the-files"></a>

* Upload the `modules/stays/grnconnect/` folder and the logo.
* Apply your edits to the official files **by hand** (do not overwrite whole official files with your staging copies, unless both sites are on exactly the same version).
* Make `modules/stays/grnconnect/logs/` and `cache/` writable by the web server.
* Do not copy `logs/`, `cache/`, `.env` or test data from staging. {% endstep %}

{% step %}

#### Prepare the content database <a href="#user-content-prepare-the-content-database" id="user-content-prepare-the-content-database"></a>

Either run the content import on production (recommended: it uses production limits and proves the import works there), or import a database dump of the staging content database. Check the hotel count matches. {% endstep %}

{% step %}

#### Create the module row (disabled) <a href="#user-content-create-the-module-row-disabled" id="user-content-create-the-module-row-disabled"></a>

In the production admin: **Settings → Modules → Add** `grnconnect` / `stays`, enter the **live** credentials, set **Environment = Live**, currency, markup and tax, content database, and **leave the module switched off**. Press **Test credentials**. {% endstep %}

{% step %}

#### Add the cron jobs <a href="#user-content-add-the-cron-jobs" id="user-content-add-the-cron-jobs"></a>

Copy the cron lines from **Settings → Automation** into the server's crontab (production URLs). Check the "last run" after the first run. {% endstep %}

{% step %}

#### Smoke test while disabled <a href="#user-content-smoke-test-while-disabled" id="user-content-smoke-test-while-disabled"></a>

Call the endpoints directly as an administrator (or temporarily enable the module during a quiet hour) and check: search returns hotels, a hotel page opens, rooms load, logs are written. {% endstep %}

{% step %}

#### Go live <a href="#user-content-go-live" id="user-content-go-live"></a>

* Switch the module **on**.
* Make **one real booking** on a refundable rate (or the supplier's designated test hotel), pay, check the voucher and the supplier's back office, then **cancel** it and check the cancellation.
* Watch the logs and the admin notifications for the first days. {% endstep %} {% endstepper %}

#### 14.1 Rollback <a href="#user-content-141-rollback" id="user-content-141-rollback"></a>

If something goes wrong in production:

1. **Switch the module off** in Settings → Modules. The website immediately stops showing and booking its hotels; other suppliers keep working.
2. If the site itself is affected (a PHP error in a module file breaks all module calls), remove the `include` line for your module from modules/index.php, or restore the backed-up files.
3. Restore the database from the backup only if data was damaged.

#### 14.2 Go-live checklist <a href="#user-content-142-go-live-checklist" id="user-content-142-go-live-checklist"></a>

* [ ] &#x20;Same PHPTRAVELS version on staging and production
* [ ] &#x20;Backups of database(s) and files taken
* [ ] &#x20;Live credentials, live URL, production IP whitelisted
* [ ] &#x20;Module row created with **Environment = Live**
* [ ] &#x20;Credentials test passes on production
* [ ] &#x20;Content imported, hotel count checked
* [ ] &#x20;Cron jobs added and running
* [ ] &#x20;Payment gateway in **live** mode, **Auto-Issue After Payment** on
* [ ] &#x20;Logs folder writable, logs written, secrets masked
* [ ] &#x20;One real booking issued and cancelled successfully
* [ ] &#x20;Your list of edits to official files saved for future updates

***

### 15. Keeping your integration working after official updates <a href="#user-content-15-keeping-your-integration-working-after-official-updates" id="user-content-15-keeping-your-integration-working-after-official-updates"></a>

#### 15.1 How updates work <a href="#user-content-151-how-updates-work" id="user-content-151-how-updates-work"></a>

Official updates are installed from **`/updates`**, one at a time, oldest first. Each update replaces the files it changes with the official version.

* Files **only you** created (your `modules/stays/grnconnect/` folder, your logo) are **never touched**, as long as the official release never ships a file with the same path. That is why module names must be unique.
* Official files you edited (section 12) are **replaced** when an update changes them, and your lines disappear.
* `.env`, `uploads/` and the update history are never overwritten.
* The **Database Update** tool (on `/updates`) only **adds** missing official tables, columns and module rows. It never drops your tables. Keep your table names prefixed so they never collide with an official table.

#### 15.2 After every update <a href="#user-content-152-after-every-update" id="user-content-152-after-every-update"></a>

1. Check that your include line is still in modules/index.php.
2. Check your other edits from section 12.
3. Run a search and open a hotel page from your supplier.
4. Keep your module and your list of edits in your own version control (git) so you can re-apply them in minutes.

#### 15.3 Make it official <a href="#user-content-153-make-it-official" id="user-content-153-make-it-official"></a>

The most robust option is to have your module **included in the official PHPTRAVELS release**. Then the wiring in the official files ships with every update and nothing needs re-applying. Contact PHPTRAVELS with your module folder, its README and your test results.

***

### 16. Quick reference <a href="#user-content-16-quick-reference" id="user-content-16-quick-reference"></a>

#### Endpoints your module provides <a href="#user-content-endpoints-your-module-provides" id="user-content-endpoints-your-module-provides"></a>

| Method + route              | Called by                           | Input                              | Main output                                         |
| --------------------------- | ----------------------------------- | ---------------------------------- | --------------------------------------------------- |
| `POST stays/<name>/creds`   | Admin "Test credentials"            | form: `c1..c6`, `env`, `module_id` | `success`, `message`, `data`                        |
| `POST stays/<name>/search`  | Search results page                 | form fields (section 6.1)          | `status`, `results[]`, `total`, `has_more`          |
| `POST stays/<name>/details` | Hotel page                          | JSON (section 7)                   | `success`, `data{...}`                              |
| `POST stays/<name>/rooms`   | Hotel page                          | JSON (section 8)                   | `success`, `data.rooms[].options[]`                 |
| `POST stays/<name>/prebook` | Hotel / checkout page (your branch) | JSON with `rate_key`               | `success`, `data.price_changed`, `data.total_price` |
| `POST stays/<name>/issue`   | Server after payment / admin        | form: `invoice_id`, `sig`          | `status`, `Prn`/`pnr`, `booking_status`             |
| `POST stays/<name>/cancel`  | Admin booking page                  | form: `invoice_id`                 | `status`, `message`                                 |
| `POST stays/<name>/void`    | Admin booking page                  | form: `invoice_id`                 | `status`, `message`                                 |
| `POST stays/<name>/refund`  | Admin booking page                  | form: `invoice_id`                 | `status`, `message`                                 |

#### Booking statuses <a href="#user-content-booking-statuses" id="user-content-booking-statuses"></a>

| `booking_status` | `payment_status` | Meaning                                                                            |
| ---------------- | ---------------- | ---------------------------------------------------------------------------------- |
| `pending`        | `unpaid`         | Created, waiting for payment                                                       |
| `confirmed`      | `paid`           | Paid and booked at the supplier (`pnr` set)                                        |
| `pending`        | `paid`           | Paid, but not (yet) booked: supplier pending, issue failed, or automatic issue off |
| `cancelled`      | `paid`           | Cancelled at the supplier, refund to be handled                                    |
| `cancelled`      | `refunded`       | Cancelled and refunded                                                             |
| `cancelled`      | `unpaid`         | Cancelled before payment                                                           |

Unpaid bookings expire after the time set in **Settings → Booking Expiry Time** (minutes). The customer gets a reminder shortly before the deadline (the booking reminders cron).

#### Dates and formats <a href="#user-content-dates-and-formats" id="user-content-dates-and-formats"></a>

| Item                              | Format                                                             |
| --------------------------------- | ------------------------------------------------------------------ |
| Check-in / check-out in requests  | `dd-mm-yyyy`                                                       |
| Dates in your cancellation policy | ISO 8601 with time zone (`2026-11-17T23:59:00Z`) and a human label |
| Countries / nationality           | ISO 3166-1 alpha-2 (`PK`, `AE`)                                    |
| Currencies                        | ISO 4217 (`USD`, `PKR`)                                            |
| Prices                            | Numbers (not strings), 2 decimals                                  |
| Hotel ids                         | Supplier ids, no `/`                                               |
|                                   |                                                                    |

***

### 17. Support <a href="#user-content-17-support" id="user-content-17-support"></a>

* Read the reference modules in `modules/stays/` (section 1.3) — most questions are answered there.
* Keep your module's `README.md` up to date: credentials mapping, endpoints, supplier contacts, known limits.
* For help with the core (booking flow, payment, admin), or to have your module included in the official release, contact PHPTRAVELS support with your website URL, the module name, the booking `invoice_id` and the request/response logs of the call that failed.
