For the complete documentation index, see llms.txt. This page is also available as Markdown.

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

1.1 The big picture

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).

 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

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

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

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

2.1 Server requirements

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

Collect these before writing code:

2.3 Environments

{% 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

{% stepper %} {% step %}

Create the folder

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>/....

{% endstep %}

{% step %}

Write index.php

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

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

{% endcode %} {% endstep %}

{% step %}

Register it in the gateway

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

{% code title="modules/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

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 %}

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

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)" %}

{% 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

4.1 Where credentials are stored

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

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" %}

{% 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

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)

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)" %}

{% endtab %}

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

{% 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)

5.1 Why import content

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

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:

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)" %}

{% endcode %}

5.3 Importing a dump file (resumable batches)

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

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)

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.1 Request

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

  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

{% code title="200 OK" %}

{% 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

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

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

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" %}

{% endcode %}

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


8. Rooms and rates

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

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

{% code title="200 OK" %}

{% 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

9.1 Rate check / prebook (if your supplier has one)

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" %}

{% endtab %}

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

{% endtab %}

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

{% endtab %}

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

{% 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)

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)

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)" %}

{% endtab %}

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

{% endtab %}

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

{% 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

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:

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

10.1 Always use MARKUP()

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

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

  • 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

  • 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

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

11.1 Log every supplier call

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

  • 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

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

  • 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)

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:

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)

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

13.1 Set up the test environment

  • 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

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

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

{% stepper %} {% step %}

Freeze and compare

  • 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

  • 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

  • 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

  • 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

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)

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

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

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

  • 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

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


15. Keeping your integration working after official updates

15.1 How updates work

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

  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

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

Endpoints your module provides

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

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

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

  • 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.

Last updated