Tell your AI coding assistant (such as Cursor, for example) that you want to integrate HolestPay for payments, fiscalization, and shipping, and provide it with this MD markup: https://apps.holest.com/holest-pay/AI_INTEGRATION_GUIDE_FRONTCORE.md.txt
Your AI assistant will then know exactly how to guide you through the process.
Make sure to SET UP FIRST ALL methods you plan to use on https://sandbox.pay.holest.com/ (payment | fiscal | shipping) and test them using “pay-by-link” (entirely off-site). If everything is configured properly, the integration will go smoothly with just a few queries.
HolestPay FrontCore (JavaScript-Only) Payment Integration Guide for AI Coding Assistants – MD file…
# HolestPay Integration Guide — FrontCore
> This guide is written for AI coding assistants. It describes how to implement HolestPay payment integration using the **FrontCore approach** — a JavaScript-only integration that does **not require a server-side signature** for the initial payment request.
> Reference implementation: `hpay_frontcore_sample.html`
>
> **Sample data files — read these to understand real data structures:**
> - `pos_as_read.json` — https://apps.holest.com/holest-pay/pos_as_read.json
> Full `client.POS` (same as HPay.POS) object as returned by `HPayInit()`. Contains `payment`, `shipping`, and `fiscal` method arrays with all their properties (`Uid`, `HPaySiteMethodId`, `Name`, `Hidden`, `SubsciptionsType`, `POps`, `PayInputUrl`, `Use IFRAME`, etc.).
> - `response_sample.json` — https://apps.holest.com/holest-pay/response_sample.json
> Full `hpay_response` object as received in `onHPayResult` event and as POST-back `hpay_forwarded_payment_response`. Contains `payment_status`, `status`, `transaction_uid`, `transaction_user_info`, `vault_token_uid`, `vault_card_brand`, `vault_card_umask`, `vault_exp`, `payment_html`, `fiscal_html`, `integr_html`, `shipping_html`, and all other result fields.
---
## What is FrontCore?
FrontCore is a HolestPay integration mode where:
- The HPay script is **automatically loaded** from the payment server when the buyer's browser visits a **whitelisted origin** (domain).
- **No Secret Key is needed on the frontend** — the payment request is signed internally by the HPay infrastructure based on the trusted origin.
- The developer only needs the **Merchant Site UID** in the browser.
- The **Secret Key is still required on your server** for backend charges (COF/MIT) , admin operations, and result signature verification.
### Recommendation
Use FrontCore selectively.
- For most production implementations, **Standard integration** should be the primary/default choice.
- FrontCore is best when you need to connect a site quickly and start payment flow fast.
- Even with FrontCore, production-grade backend verification, webhook idempotency, and secure server ownership are still required.
---
## Prerequisites
1. A configured HolestPay POS on `pay.holest.com` (production) or `sandbox.pay.holest.com` (sandbox).
2. All desired payment methods, fiscal methods, and shipping methods activated on the POS in the HPay panel.
3. In the HPay panel ? site/POS settings:
- **Merchant Site UID** (`merchant_site_uid`) — **not** required as an input parameter to `HPayInit()` for FrontCore. It is automatically available as `client.MerchantsiteUid` after `HPayInit()` resolves, and must be saved for use in backend charge requests and admin operations.
- **POS Secret Key** — needed only on your **server** (for charges, admin ops, result verification).
- **Frontend Script-Core Origins** — add your site's domain (e.g. `yoursite.com` or `*.yoursite.com`) to the whitelist. **Without this, the FrontCore script will not load.**
---
## Pre-Implementation Client Questions (Ask Before Building)
Before writing integration code, confirm the following with the client:
- Do you want us to implement the bank-required footer logotypes strip (card logos, bank logos, 3DS logos) using HolestPay POS parameters, visible in the site footer on **all pages** (not only checkout)?
- For Terms of Service, do you want to use the HolestPay-provided TOS page directly, compare/merge its clauses into your existing TOS page, or handle TOS in another way?
- Do you require an `I accept Terms of Service` checkbox on checkout with a clickable Terms link (page link or modal)?
---
## Recommended Quick-Start from HPay Panel
Before implementing from scratch, open HPay panel:
- `PLATFORM MODULES` -> at the bottom use:
- `Get HTML with embeded POS (selected POS) credentials (production requires server-side sigining)...`
- `Get HPay-FrontCore HTML with embeded POS (selected POS) credentials (signing automatic, javascript-only implementable) ...`
- Download generated sample files and deploy them to an HTTPS test location.
- For FrontCore, explicitly add that HTTPS test location to `Frontend Script-Core Origins`; otherwise the FrontCore script will not load there.
- Use these files for immediate end-to-end checks (form rendering, payment flow, event payloads, response format, order fields).
- AI assistants and developers can inspect these generated samples during development to discover integration details that may not be fully documented.
For this FrontCore guide, start from the FrontCore generated sample (based on `hpay_frontcore_sample.html`) and validate script loading + origin whitelist behavior first.
---
## Platform Clarifications (Important)
- In HolestPay terminology, a `POS` means your website/app sales endpoint (web, Android, iOS, desktop), not a physical in-store terminal.
- `sandbox` and `production` are intentionally isolated environments. Configure POS, methods, and credentials separately in each environment.
- For status processing, treat HolestPay `status` format as canonical for order lifecycle across panel/API/webhooks:
- `PAYMENT:<payment_status>`
- optional fiscal/integration segments: `<module_uid>_FISCAL:<status>` or `<module_uid>_INTEGR:<status>`
- optional shipping segments: `<module_uid>_SHIPPING:<packet_no>@<shipping_status>`
- Keep section order in composed status as: `PAYMENT` -> `FISCAL/INTEGRATION` -> `SHIPPING`.
- Handle additional payment statuses beyond only paid/failed flows, especially `AWAITING`, `PAYING`, `RESERVED`, and `OBLIGATED`, depending on your business process.
---
## HolestPay Order Status Format
```shell
[PAYMENT:payment_status][ (fmethod1_uid)_FISCAL:(fmethod1_status) [(fmethod2_uid)_FISCAL:(fmethod2_status)]...][ (imethod1_uid)_INTEGR:(imethod1_status) [(imethod2_uid)_INTEGR:(imethod2_status)]...][ (smethod1_uid)_SHIPPING:packet_no@shipping_status [(smethod2_uid)_SHIPPING:packet_no@shipping_status]...]
```
- ORDER OF SUB-STATUSES SECTIONS PAYMENT -> FISCAL & INTEGRATION -> SHIPPING IS IMPORTANT.
- ORDER OF METHOD STATUSES WITHIN SAME SUB-STATUSES SECTION IS NOT IMPORTANT.
- ONE AND ONLY ONE SPACE CHARACTER AS SUB-STATUSES SEPARATOR IS IMPORTANT.
```shell
Possible payment status:
SUCCESS (alias of PAID)
PAID
PAYING (partially paid, indicates all partial payments are on time; used for advance payments or multi-source payments)
AWAITING (waiting bank transfer, for example)
REFUNDED
PARTIALLY-REFUNDED
VOID
OVERDUE
RESERVED (amount is reserved but still not captured from buyer card)
EXPIRED (used with methods that have expiration)
OBLIGATED (same as AWAITING but when service delivery has started or there is legal means to guarantee payment will happen)
REFUSED
FAILED
CANCELED
```
`PAYMENT:payment_status` may not exist if HolestPay payment module is not used and you do not set it explicitly.
```shell
Possible fiscal module status:
- varies depending on module
```
Fiscal/Integration statuses exist only if fiscal/integration modules add status and are executed.
```shell
Possible packet shipping status:
PREPARING - initial status if shipping address is OK; instructions can be submitted to courier from this status
READY - used by some companies to indicate goods are checked and ready for courier submission
SUBMITTED - request submitted to courier
DELIVERY - under delivery
DELIVERED - delivered
ERROR - error in courier API request
RESOLVING - shipping address (or something else) needs backend attention
FAILED - delivery permanently failed, or courier API refused the request
REVOKED - explicitly canceled by buyer or company
```
Shipping statuses exist only when packets are handled by HolestPay shipping modules.
---
## How It Works — Overview
```
HPay Server Browser (your site) Your Server
| | |
|-- auto-serve hpay.frontcore.js -->| |
| (only for whitelisted origins) | |
| | |
|<-- HPayInit() --------------------| |
|<-- presentHPayPayForm(request) ---| |
| (no verificationhash needed) | |
| | |
|-- onHPayResult ------------------>| |
| |-- verify & fulfil -------->|
| | |
| (server-to-server webhook) -------|----------> notify_url ---->|
```
The key difference from Standard: **no `verificationhash` field is needed** in the initial pay_request because the trusted origin acts as the authorization.
---
## Step 0 — Configure Origins and Get the FrontCore Script URL
### 1. Whitelist your domain/origin patterns
In the HPay panel, under your POS/site settings, add allowed entries to **"Frontend Script-Core Origins"**.
- Enter **one origin/pattern per line**.
- `*` wildcard is supported.
- Example pattern: `*holest.com/all-fontcore-tests/*`
This allows matching subdomains and subfolders that satisfy the pattern.
### 2. Copy the FrontCore script tag from HPay panel
After saving origins, the HPay panel outputs a **full `<script>` tag** that can be copied/pasted directly below the FrontCore Origins field.
FrontCore script URL format:
```
https://sandbox.pay.holest.com/clientpay/handlers/pos/{merchant_site_uid}/frontend-script-core.js
```
Production format:
```
https://pay.holest.com/clientpay/handlers/pos/{merchant_site_uid}/frontend-script-core.js
```
Example (sandbox):
```html
<script src="https://sandbox.pay.holest.com/clientpay/handlers/pos/07f689c5-5bc8-44b6-a563-8facc6870fab/frontend-script-core.js"></script>
```
In this URL, the `07f689c5-5bc8-44b6-a563-8facc6870fab` segment is the **Merchant Site UID**.
When this FrontCore script loads on an allowed origin, `HolestPayCheckout` and FrontCore signing (`hpay_frontend_script_core_sign`) become available.
After loading, the global `HolestPayCheckout` object and `HPayInit()` become available.
When the HPay script is loaded, it also exposes these globals on `window`:
- `window.presentHPayPayForm` — function
- `window.HPayIsSandbox` — environment flag variable
Add a check to warn about misconfiguration (add after page loads):
```javascript
setTimeout(function() {
if (typeof HolestPayCheckout === 'undefined') {
alert(
'HOLESTPAY FRONT-CORE SCRIPT IS NOT LOADED. ' +
'YOU PROBABLY FORGOT TO ADD CURRENT ORIGIN TO ' +
'"Frontend Script-Core Origins" PARAMETER UNDER SITE/POS SETTINGS!'
);
}
}, 5000);
```
---
## Step 1 — Initialize HPay and Fetch POS Configuration
`HPayInit()` returns a Promise resolving to `client` (= global `HPay`).
```javascript
HPayInit(
language // string — e.g. "en", "rs", "de" — also optional.
// If omitted, HPay will use the HTML <html lang="..."> attribute,
// or fall back to the fixed language configured in HPay panel POS settings.
// NOTE: merchant_site_uid and environment are NOT required for FrontCore —
// they are determined automatically by the POS-specific script URL.
).then(async client => {
// client.MerchantsiteUid — the Merchant Site UID read from the loaded POS config
const merchantSiteUid = client.MerchantsiteUid; // save for use in charge_request / admin ops
// client.POS.payment — array of payment method objects
// client.POS.shipping — array of shipping method objects
// client.POS.fiscal — array of fiscal method objects
// Filter by buyer country (optional but recommended):
let availablePayment = [];
let availableShipping = [];
const country = 'RS';
try {
availablePayment = await HPay.availablePaymentMethods(country, orderAmount, orderCurrency);
} catch(e) { console.error(e); }
try {
availableShipping = await HPay.availableShippingMethods(country, orderAmount, orderCurrency);
} catch(e) { console.error(e); }
// Build payment method selector from client.POS.payment:
client.POS.payment.forEach(pm => {
if (!pm.Hidden && (!availablePayment.length || availablePayment.find(m => m.Uid == pm.Uid))) {
// pm.HPaySiteMethodId — use as pay_request.payment_method value
// pm.Name — display name
// pm.SubsciptionsType — contains "cof" or "mit" if card saving is supported
// pm.POps — available backend operations e.g. "charge,refund"
// pm.PayInputUrl — set means docking (embedded form) is supported
// pm['Use IFRAME'] — if false, method uses redirect flow
}
});
// Build shipping method selector from client.POS.shipping:
if (client.POS.shipping) {
client.POS.shipping.forEach(sm => {
if (!sm.Hidden && (!availableShipping.length || availableShipping.find(m => m.Uid == sm.Uid))) {
// sm.HPaySiteMethodId — use as pay_request.shipping_method value
}
});
}
});
```
---
## Step 2 — Build the `pay_request` Object
```javascript
const pay_request = {
// NOTE: merchant_site_uid is NOT included in pay_request for FrontCore.
// The POS-specific script authenticates the request automatically.
hpaylang: "en", // optional UI language
order_uid: "20260315-621417", // required unique order ID
order_name: "#Order 204", // optional order label
order_amount: "15000", // required
order_currency: "RSD", // required ISO 4217
payment_method: "179", // required pm.HPaySiteMethodId
shipping_method: "45", // optional sm.HPaySiteMethodId
order_user_url: "https://yoursite.com/thanks", // optional redirect/thank-you URL
notify_url: "https://yoursite.com/webhook", // optional public webhook URL
order_data: { // optional custom payload -> stored as order.Data
customer_segment: "B2C",
source: "checkout-web"
},
cof: "optional", // optional: optional|required|none
vault_token_uid: "saved-token-uuid", // optional: saved token, or 1|true|new
// Optional billing object (template fields):
order_billing: {
email: "customer@example.com",
first_name: "TEST",
last_name: "TEST",
phone: "+38111111111",
is_company: 0,
company: "", // company legal name
company_tax_id: "", // company tax ID in merchant's country
company_reg_id: "", // company registration ID in merchant's country
address: "TEST", // street name
address2: "", // recommended for street number / address addition
city: "Beograd",
country: "RS",
state: "Beograd",
postcode: "11000",
lang: "sr_RS" // language from merchant platform/system
},
// Optional shipping object (template fields):
order_shipping: {
shippable: false,
is_cod: 1, // set to 1 when COD logic is used/allowed
first_name: "",
last_name: "",
phone: "",
company: "",
address: "", // street name
address2: "", // recommended for street number / address addition
city: "",
country: "",
state: "",
postcode: ""
},
// Optional items array (template fields):
order_items: [
{
posuid: 114, // merchant's own internal item ID (string or number)
type: "product",
name: "Sample product name",
sku: "000550",
qty: 1,
price: 4695.99,
subtotal: 4695.99,
refunded: 0,
refunded_qty: 0,
tax_label: "",
tax_amount: 0,
length: "",
width: "",
height: "",
weight: "",
split_pay_uid: "",
virtual: true,
tax_percent: 0
}
]
};
// NOTE: For initial FrontCore checkout, do not send signature hash.
// Remove empty fields:
Object.keys(pay_request).forEach(k => { if (pay_request[k] === '') delete pay_request[k]; });
```
**Important — `order_items` naming must use HolestPay keys (do not pass raw platform keys):**
- Use `name`, not `title`
- Use `posuid`, not `variantId`
- Use `qty`, not `quantity`
- `subtotal` is mandatory for each item line
- `posuid` can be any identifier from the merchant's system (SKU/variant/product/internal DB ID)
Common Shopify mapping before send:
- `variantId -> posuid`
- `title -> name`
- `quantity -> qty`
- top-level `items -> order_items`
The same order payload structure is used across all three markups/docs (Lovable prompt, FrontCore guide, Standard guide).
Address convention recommendation: use `address` for street name and `address2` for street number/additional address details.
### Full Template Field Catalog (Standalone)
- `Top-level pay_request` (FrontCore — `merchant_site_uid` is **not** included here):
- `hpaylang`, `order_uid`, `order_name`, `order_amount`, `order_currency`
- `payment_method`, `shipping_method`, `order_user_url`, `notify_url`
- `order_data`, `cof`, `vault_token_uid`
- `order_billing`:
- `email`, `first_name`, `last_name`, `phone`
- `is_company`, `company` (legal name), `company_tax_id` (tax ID), `company_reg_id` (registration ID)
- `address`, `address2`, `city`, `country`, `state`, `postcode`, `lang`
- `order_shipping`:
- `shippable`, `is_cod`
- `first_name`, `last_name`, `phone`, `company`
- `address`, `address2`, `city`, `country`, `state`, `postcode`
- `dispenser`, `dispenser_desc`, `dispenser_method_id` (locker/paket-shop flows)
- `order_items[]`:
- `posuid`, `type`, `name`, `sku`, `qty`, `price`, `subtotal`
- Required minimum per line for reliable processing: `posuid`, `name`, `qty`, `subtotal`
- `refunded`, `refunded_qty`, `tax_label`, `tax_amount`
- `length`, `width`, `height`, `weight`, `split_pay_uid`, `virtual`, `warehouse`
- `setPaymentMethodDock(...)` data:
- `order_amount`, `order_currency`, `monthly_installments`, `vault_token_uid`, `hpaylang`, `cof`
- Signature input/result fields used for backend charge and verification:
- `transaction_uid`, `status`, `order_uid`, `order_amount`, `order_currency`, `vault_token_uid`, `subscription_uid`, `rand`
- Compare generated signature with response `vhash` (not request `verificationhash`).
- `Extensibility`:
- `order_data` may contain any custom key/value pairs; it is persisted to `order.Data` in HPay order.
- `order_billing` and `order_shipping` may include additional custom fields besides the listed ones.
- Total serialized order payload should stay below **64 KB**.
---
## Step 3 — Present the Payment Form
```javascript
// Option A: Modal
HPay.presentHPayPayForm(pay_request);
// Option B: Docked (embedded) — only if pm.PayInputUrl is set
const dockElement = document.getElementById('paymentMethodDock');
HPay.setPaymentMethodDock(
pay_request.payment_method,
{
order_amount: pay_request.order_amount,
order_currency: pay_request.order_currency,
monthly_installments: null,
vault_token_uid: pay_request.vault_token_uid || null,
hpaylang: pay_request.hpaylang,
cof: pay_request.cof
},
dockElement
);
// Trigger payment on Pay button click:
HPay.presentHPayPayForm(pay_request);
```
Dock container CSS:
```css
#paymentMethodDock { background: #ffffff9e; }
```
---
## Step 4 — Handle the Result Events
Use these event handlers on your FrontCore page:
```javascript
document.addEventListener('onHPayResult', function(e) {
const r = e.hpay_response;
if (!r) return;
if (r.error && r.error.code) {
HPay.presentHPayPayForm(pay_request); // retry
return;
}
if (/PAID|RESERVED|SUCCESS|PAYING|OBLIGATED|AWAITING/i.test(r.payment_status)) {
// r.payment_html, r.fiscal_html, r.integr_html, r.shipping_html — HTML receipts
// r.transaction_user_info — object with card/transaction details
// r.order_user_url — redirect to thank-you page if needed
// IMPORTANT: AWAITING/OBLIGATED are NOT failed; show r.payment_html on thank-you page
// IMPORTANT: clear cart for PAID/RESERVED and also for PAYING/AWAITING/OBLIGATED.
// window.location.href = r.order_user_url;
if (r.vault_token_uid) {
// IMPORTANT: save to your database linked to the user account!
const saveCardData = {
vault_token_uid: r.vault_token_uid,
vault_card_brand: r.vault_card_brand,
vault_card_umask: r.vault_card_umask,
vault_exp: r.vault_exp,
vault_scope: r.vault_scope,
vault_onlyforuser: r.vault_onlyforuser,
pay_method_uid: r.pay_method_uid
};
// TODO: POST saveCardData to your backend and store in DB
}
}
// r.status — order status (always present)
});
document.addEventListener('onHPayPanelClose', function(e) {
const r = e.hpay_response; // null if closed without completing
const reason = String((r && r.reason) || '').toLowerCase();
// If pay button was locked during payment start, unlock it on close reasons below.
if (/^(user|timeout|cancel|error)$/.test(reason)) {
const payBtn = document.getElementById('do-pay');
if (payBtn) payBtn.disabled = false;
}
});
document.addEventListener('onHPayOrderOpExecuted', function(e) {
// admin operation result
});
```
### Thank-You Page Rendering Rule (Mandatory)
On the thank-you page, always render:
1) `transaction_user_info` block first,
2) `payment_html`, `fiscal_html`, `shipping_html`, `integr_html` blocks.
Bank production approval also requires a complete order summary on this page (for all outcomes: success, failed, awaiting payment):
- buyer/customer identity data
- billing and email data
- shipping data
- order number
- ordered products list with quantity, unit price, and line totals
- shipping cost
- payment method name and shipping method name
- grand total amount
If any field is missing in response, keep the block visible and show a placeholder message.
Keys in `transaction_user_info` can be translated for UI labels, but values should be shown exactly as received.
```javascript
function renderTransactionUserInfo(info, keyMap) {
const host = document.getElementById('hpay-transaction-user-info');
if (!host) return;
host.innerHTML = '';
if (!info || typeof info !== 'object' || !Object.keys(info).length) {
host.innerHTML = '<p class="hpay-placeholder">Transaction details are not available.</p>';
return;
}
const dl = document.createElement('dl');
Object.entries(info).forEach(([k, v]) => {
const dt = document.createElement('dt');
const dd = document.createElement('dd');
dt.textContent = keyMap[k] || k; // translate keys only
dd.textContent = String(v ?? ''); // do not alter values
dl.appendChild(dt);
dl.appendChild(dd);
});
host.appendChild(dl);
}
renderTransactionUserInfo(r.transaction_user_info, {
'Order UID': 'Order UID',
'Payment Status': 'Payment Status',
'Transaction Time': 'Transaction Time',
'Amount in order currency': 'Amount in order currency',
'Amount in payment currency': 'Amount in payment currency',
'Bank Account': 'Bank Account',
'REF MOD97 PNB': 'REF MOD97 PNB',
'Purphose': 'Purpose'
});
const FALLBACK_HTML = '<p class="hpay-placeholder">Not available for this payment.</p>';
document.getElementById('hpay-receipt-payment').innerHTML = r.payment_html || FALLBACK_HTML;
document.getElementById('hpay-receipt-fiscal').innerHTML = r.fiscal_html || FALLBACK_HTML;
document.getElementById('hpay-receipt-shipping').innerHTML = r.shipping_html || FALLBACK_HTML;
document.getElementById('hpay-receipt-integr').innerHTML = r.integr_html || FALLBACK_HTML;
```
Example payload:
```json
{
"transaction_user_info": {
"Order UID": "NIPI-1777290504591-8X6YD2",
"Payment Status": "AWAITING",
"Transaction Time": "2026-04-27 13:48:27.847Z",
"Amount in order currency": "1360.00 RSD",
"Amount in payment currency": "1360.00 RSD",
"Bank Account": "160-6000002552312-02",
"REF MOD97 PNB": "(97) 2726042713",
"Purphose": "Order npinipi17772905045918x6yd2"
}
}
```
---
## Result Verification — Webhook (Notify URL)
HPay calls webhook URL via HTTP POST JSON (server-to-server).
If `notify_url` is sent in request payload, it overrides panel setting:
- `I(P|S|F|I)N - Link za instant notifikacije - plaćanje/isporuka/fiskal/integracije`
- `I(P|S|F|I)N - Instant payment/shipping/fiscal/integation notification url`
HPay appends query string parameter `topic` and sends POST JSON.
Supported `topic` values:
- `payresult`: same payload shape as `onHPayResult` (`e.hpay_response`) / `https://apps.holest.com/holest-pay/response_sample.json`.
- `orderupdate`: root contains at least `order_uid`, `status`, `vhash`; payload fields are the same as `payresult`; and includes `order` object in the same format as `ord` from `HPay.getOrder(order_uid).then(ord => {...})` (`https://apps.holest.com/holest-pay/hpay_order_sample.json`) (`"id"` is ID from HPay system); verify `vhash` the same way.
- `posconfig-updated`: contains POS config (`HPay.POS` compatible + non-public fields), `environment`, and `checkstr = md5(${merchant_site_uid}${secret_token})`.
Important payload mapping note:
- Request and response payloads are similar in shape; response usually contains request fields plus normalization and additional result fields.
- Hash field names are different by direction: request -> `verificationhash`, response -> `vhash`.
- `order` payload is a different model (same as `HPay.getOrder(...)` `ord` object), so do not map it as request/response.
- Example key differences:
- request/response `order_uid`, `order_amount`, `order_currency` -> order object `Uid`, `Amount`, `Currency`
- request/response `order_items`, `order_billing`, `order_shipping` -> order object `Data.items`, `Data.billing`, `Data.shipping`
- fiscal method specific data -> `order.FiscalData[fiscal_method_uid] = {...}` (module-specific payload)
- integration method data -> `order.Data[integr_method_uid] = {...}` (may exist or may be empty/missing)
- shipping method data -> `order.ShippingData[real_or_temp_shipping_code] = { method_uid: shipping_method_uid, ... }`
The same payment result may arrive from browser callback and webhook. Use `vhash` (with order/transaction IDs) for idempotency to avoid duplicate processing.
### Redirect Method POST-back Note (Bank Redirect Flows)
For redirect methods, HPay may return result to `order_user_url` with auto-submitted form:
```html
<form method='POST' id='frmRedirect' action='${order_user_url}'>
<input type='hidden' name='hpay_forwarded_payment_response' id='hpay_response' />
</form>
<script nonce='${csp_nonce}'>
document.getElementById('hpay_response').value = JSON.stringify(hpay_result);
document.getElementById('frmRedirect').submit();
</script>
```
Robust parse fallback example:
```javascript
function parseForwardedHPayResponse(raw) {
if (!raw) return null;
if (typeof raw === 'object') return raw;
try { return JSON.parse(raw); } catch (_) {}
const unescaped = String(raw).replace(/\\\\\"/g, '"').replace(/\\\\\\\\/g, '\\');
try { return JSON.parse(unescaped); } catch (_) {}
return null;
}
```
## Step 5 — Verify Response `vhash` on Server (Node.js)
Rule of thumb:
- request to HPay (`pay_request` / `charge_request`) -> field `verificationhash` -> generate with `generatePOSRequestSignature(...)`
- response from HPay (browser callback / webhook) -> field `vhash` -> validate with `verifyHPayResponse(...)`
```javascript
const crypto = require('crypto');
const md5 = require('md5');
function generatePOSRequestSignature(merchant_site_uid, secretKey, payload) {
const amount = Number(payload.order_amount ?? 0).toFixed(8);
const src =
String(payload.transaction_uid ?? '').trim() + '|' +
String(payload.status ?? '').trim() + '|' +
String(payload.order_uid ?? '').trim() + '|' +
amount + '|' +
String(payload.order_currency ?? '').trim() + '|' +
String(payload.vault_token_uid ?? '').trim() + '|' +
String(payload.subscription_uid ?? '').trim() +
String(payload.rand ?? '').trim();
const srcMd5 = md5(src + merchant_site_uid);
return crypto.createHash('sha512').update(srcMd5 + secretKey).digest('hex').toLowerCase();
}
function verifyHPayResponse(result, merchant_site_uid, secretKey) {
if (!result || !result.vhash) return false;
if (!result.order_uid || !String(result.order_uid).trim()) return false;
const expected = generatePOSRequestSignature(merchant_site_uid, secretKey, {
transaction_uid: result.transaction_uid ?? '',
status: result.status ?? '',
order_uid: result.order_uid,
order_amount: result.order_amount ?? 0,
order_currency: result.order_currency ?? '',
vault_token_uid: result.vault_token_uid ?? '',
subscription_uid: result.subscription_uid ?? '',
rand: result.rand ?? ''
});
return expected === String(result.vhash).toLowerCase();
}
```
---
## Backend Charge (Server Side — Still Requires Secret Key)
FrontCore does not expose the Secret Key on the frontend, but backend charges still need it on your server.
`charge_request` uses the same structure as `pay_request`. The practical difference is that `order_user_url` has no effect for backend charge (no buyer to redirect), so you should omit it. `cof` is also not needed for backend charge requests.
```javascript
// Node.js backend
const crypto = require('crypto');
const md5 = require('md5');
function generatePOSRequestSignature(merchant_site_uid, secretkey, request) {
const amt = parseFloat(request.order_amount || 0).toFixed(8);
let cstr = String(request.transaction_uid || '').trim() + '|';
cstr += String(request.status || '').trim() + '|';
cstr += String(request.order_uid || '').trim() + '|';
cstr += String(amt).trim() + '|';
cstr += String(request.order_currency || '').trim() + '|';
cstr += String(request.vault_token_uid || '').trim() + '|';
cstr += String(request.subscription_uid || '').trim();
cstr += String(request.rand || '').trim();
const md5hash = md5(cstr + merchant_site_uid);
return crypto.createHash('sha512').update(md5hash + secretkey).digest('hex').toLowerCase();
}
const charge_request = {
merchant_site_uid: "YOUR-MERCHANT-SITE-UID",
order_uid: "20260315-999999",
order_amount: "15000",
order_currency: "RSD",
payment_method: "179",
vault_token_uid: "saved-token-uuid", // required
order_data: { source: "subscription-renewal" }, // optional custom data -> order.Data
// same optional fields as pay_request (billing, shipping, items, notify_url, etc.)
// omit order_user_url: no user exists to be redirected in backend charge flow
// omit cof: not applicable for backend charge
};
charge_request.verificationhash = generatePOSRequestSignature(
charge_request.merchant_site_uid, SECRET_KEY, charge_request
);
const baseUrl = 'https://sandbox.pay.holest.com'; // or pay.holest.com
const response = await fetch(`${baseUrl}/s-blue/v1/clientpay/charge`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(charge_request)
});
const result = await response.json();
if (/PAID|PAYING|RESERVED/.test(result.payment_status)) {
// success
}
```
PHP equivalent:
```php
function generatePOSRequestSignature($merchant_site_uid, $secretkey, $request) {
$amt = number_format((float)($request['order_amount'] ?? 0), 8, '.', '');
$cstr = trim($request['transaction_uid'] ?? '') . '|';
$cstr .= trim($request['status'] ?? '') . '|';
$cstr .= trim($request['order_uid'] ?? '') . '|';
$cstr .= trim($amt) . '|';
$cstr .= trim($request['order_currency'] ?? '') . '|';
$cstr .= trim($request['vault_token_uid'] ?? '') . '|';
$cstr .= trim($request['subscription_uid'] ?? '');
$cstr .= trim($request['rand'] ?? '');
return hash('sha512', md5($cstr . $merchant_site_uid) . $secretkey);
}
$charge_request['verificationhash'] = generatePOSRequestSignature(
$merchant_site_uid, $secret_key, $charge_request
);
$body = json_encode($charge_request);
$ch = curl_init($base_url . '/s-blue/v1/clientpay/charge');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
// for simplicity only - do not disable in production:
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => false,
]);
$result = json_decode(curl_exec($ch), true);
curl_close($ch);
```
---
## Admin Operations (Requires Secret Key — Backend or Admin Page Only)
For admin pages, use the **normal HPay script URL**, not the FrontCore handler script:
```html
<!-- Sandbox admin page -->
<script src="https://sandbox.pay.holest.com/clientpay/cscripts/hpay.js"></script>
<!-- Production admin page -->
<script src="https://pay.holest.com/clientpay/cscripts/hpay.js"></script>
```
Do not use `.../frontend-script-core.js` for admin tooling.
```javascript
// Use the 4th parameter of HPayInit to enable admin mode
HPayInit(
merchant_site_uid,
language,
environment,
secret_key // 4th param — enables admin/backend operations
).then(client => client.loadHPayUI())
.then(() => {
HPay.getOrder(order_uid).then(ord => {
// `ord` format sample: https://apps.holest.com/holest-pay/hpay_order_sample.json
const toolbox = document.getElementById('admin_toolbox');
toolbox.innerHTML = '';
[HPay.POS.payment, HPay.POS.fiscal, HPay.POS.shipping].forEach(methods => {
(methods || []).forEach(pm => {
if (pm.initActions) {
if (typeof pm.initActions === 'string') eval('pm.initActions = ' + pm.initActions);
pm.initActions();
}
if (pm.orderActions) {
if (typeof pm.orderActions === 'string') eval('pm.orderActions = ' + pm.orderActions);
const actions = pm.orderActions(ord);
if (actions && actions.length) {
const h6 = document.createElement('h6');
h6.innerHTML = pm.SystemTitle;
toolbox.appendChild(h6);
actions.forEach(action => {
if (action.Run) {
const btn = document.createElement('button');
btn.innerHTML = action.Caption;
btn.addEventListener('click', e => { e.preventDefault(); action.Run(ord); });
toolbox.appendChild(btn);
} else if (action.actions) {
const p = document.createElement('p');
p.innerHTML = action.Caption;
toolbox.appendChild(p);
action.actions.forEach(sub => {
const sbtn = document.createElement('button');
sbtn.innerHTML = sub.Caption;
sbtn.addEventListener('click', e => { e.preventDefault(); sub.Run(ord); });
p.appendChild(sbtn);
});
}
});
}
}
});
});
});
});
```
---
## Difference Summary: FrontCore vs Standard
| Feature | FrontCore | Standard |
|---------|-----------|----------|
| Script source | Auto-served from HPay server (whitelisted origin) | Manual `<script>` tag |
| `HPayInit()` signature | `HPayInit(language)` — no UID or env needed | `HPayInit(merchant_site_uid, language, environment)` |
| `merchant_site_uid` in `pay_request` | **Not required** — script authenticates automatically | Required |
| `merchant_site_uid` for charges/admin | Required (read from `client.MerchantsiteUid`) | Required |
| Admin script URL | Use normal `.../clientpay/cscripts/hpay.js` | Use normal `.../clientpay/cscripts/hpay.js` |
| `verificationhash` in pay_request | Not required (FrontCore initial checkout) | Required (server-side) |
| Secret Key on frontend | Never needed | Never needed (generate signature server-side) |
| Secret Key for backend charges | Required (server-side) | Required (server-side) |
| Secret Key for admin ops | Required (server-side or admin page) | Required (server-side or admin page) |
| Origin whitelist required | Yes — configure in HPay panel | No |
| Result event handling | Identical | Identical |
---
## Implementation Precision Addendum
Use this section as an execution checklist to reduce integration mistakes and speed up debugging.
### FrontCore Safety Rules (Most Important)
- FrontCore initial checkout request does not require `verificationhash`; trusted origin performs signing.
- FrontCore script must be loaded from `.../handlers/pos/{merchant_site_uid}/frontend-script-core.js`.
- Current page origin must match `Frontend Script-Core Origins` rule list; otherwise `HolestPayCheckout` will not initialize.
- Keep one origin/pattern per line in HPay panel and verify wildcard scope carefully before production.
- Use normal `.../clientpay/cscripts/hpay.js` for admin tooling pages; do not use FrontCore handler script for admin.
### Request Validation Rules (Before Calling HPay)
- `order_uid` must be unique per order attempt in your system; do not reuse successful IDs for new purchases.
- `merchant_site_uid` must belong to the same environment where script/API is used (`sandbox` with sandbox, `production` with production).
- `order_amount` must be stable across checkout form, dock config, and presented request.
- `order_currency` must be a valid ISO 4217 code configured on your POS methods.
- `payment_method` must be `pm.HPaySiteMethodId` (not `pm.Uid`).
- `shipping_method` should be omitted if shipping is not used; send it only when user selected a supported shipping option.
- `notify_url` should be a stable server endpoint; avoid temporary dev tunnels for production behavior testing.
- `order_user_url` should point to your own order/thank-you page and include enough context to restore order state.
- `order_data` is ideal for stable metadata like source channel, cart fingerprint, CRM ID, campaign tags, or internal correlation keys.
- Remove empty fields before sending; avoid null/empty noise in logs and state snapshots.
### Signature and Verification Precision (Server Side)
- Even with FrontCore, backend charge and result verification still require Secret Key and signature validation.
- Use exactly the documented signature field order and amount formatting (`toFixed(8)` / `number_format(..., 8)`).
- Compare signatures using exact lowercase hex strings.
- `verificationhash` is used for requests to HPay; `vhash` is used in responses from HPay.
- Verify signatures in both places: browser event result handling path and webhook path.
- Treat unsigned or signature-invalid payload as non-authoritative and do not fulfill order.
### Webhook Reliability Pattern
- Implement webhook idempotency keyed by transaction/order identifiers from result payload.
- Accept webhook retry behavior; return success response only after durable persistence.
- Process business actions once, even if webhook arrives multiple times or after browser callback.
- Record webhook receive timestamp and raw payload snapshot for auditability.
- Never rely on callback ordering between browser event and webhook; either can arrive first.
- Use webhook as final server authority for fulfillment transitions.
### Status Handling Strategy
- Handle `PAID`, `SUCCESS`, `PAYING`, `RESERVED`, `OBLIGATED`, `AWAITING`, `FAILED`, `REFUSED`, `CANCELED`, `VOID`, `REFUNDED`, `PARTIALLY-REFUNDED`, `EXPIRED`, `OVERDUE`.
- Map payment status to business actions explicitly:
- `PAID`/`SUCCESS`: fulfill when signature is valid on server.
- `PAYING`: partially paid; keep order open according to your policy.
- `RESERVED`: authorization only; wait for capture before final fulfillment.
- `AWAITING`/`OBLIGATED`: pending/offline or legally committed flows; these are **not failed** statuses. Do not treat them as card-capture success, but show `payment_html` on thank-you page (often contains account/invoice payment instructions).
- Cart handling rule: clear cart for `PAID`, `RESERVED`, `PAYING`, `AWAITING`, and `OBLIGATED` (same cart behavior for all these statuses).
- `FAILED`/`REFUSED`/`CANCELED`/`EXPIRED`/`OVERDUE`: stop fulfillment and show retry/payment-link path.
- Parse composed HolestPay status (`PAYMENT ... _FISCAL/_INTEGR ... _SHIPPING ...`) as operational context, not payment result only.
### Shipping and Dispenser Precision
- `dispenser`, `dispenser_desc`, and `dispenser_method_id` are meaningful only for shipping methods that support locker/paket-shop mode.
- `dispenser_method_id` must match top-level `shipping_method` to be considered in downstream processing.
- Keep shipping address and shipping method logically aligned (country/state/postcode compatibility).
### Payload Size and Data Modeling
- Keep total serialized order payload below `64 KB`.
- Prefer short stable keys in `order_data`; avoid embedding huge documents.
- Do not place sensitive secrets in `order_data`, `order_items`, or any client-visible payload field.
- Put only metadata needed for reconciliation/debugging into request payload.
### Frontend and Backend Responsibility Split
- Frontend: collect user choices, call initialized HPay APIs, listen to events, render status.
- Backend: verify result signatures, process webhook, enforce idempotency, persist state.
- Backend charge/admin: generate signatures and run protected operations with Secret Key.
### Recommended Test Matrix (Minimal but Complete)
- Test FrontCore script load on an allowed origin and verify failure on a non-allowed origin.
- Test success payment and failed payment (validation/card failure).
- Test close panel before completion and verify no accidental fulfillment.
- Test retry after `onHPayResult` error flow.
- Test with and without shipping section.
- Test one request containing `order_data` and confirm data appears in resulting order `Data`.
- Test one backend charge request with existing `vault_token_uid`.
- Test webhook replay (send same payload twice) and confirm idempotent behavior.
- Test signature mismatch scenario and verify order is not fulfilled.
- Test one `RESERVED`/authorization-capable method if available and confirm capture-dependent flow.
### Logging and Observability
- Log correlation tuple for each request: `order_uid`, `merchant_site_uid`, environment, method IDs, and internal user/session key.
- Store raw HPay response payloads for troubleshooting (with sensitive-data policy applied).
- Keep separate logs for browser callback processing and webhook processing.
- Add clear audit events: `PAYMENT_INIT`, `PAYMENT_RESULT_RECEIVED`, `WEBHOOK_RECEIVED`, `SIGNATURE_VALIDATED`, `FULFILLMENT_TRIGGERED`.
### Common Integration Mistakes to Avoid
- Forgetting to whitelist the exact test/prod origin for FrontCore.
- Using `pm.Uid` instead of `pm.HPaySiteMethodId`.
- Mixing sandbox credentials with production script/API domain.
- Trusting browser callback without server-side verification.
- Reusing old `order_uid` across retries/orders.
- Treating all non-error statuses as final success.
- Sending huge custom payloads over `64 KB`.
### Field Constraints Quick Reference
| Field | Required | Typical format | Precision note |
|---|---|---|---|
| `merchant_site_uid` | Yes | UUID-like string | Must match FrontCore script path and environment POS |
| `hpaylang` | No | `en`, `rs`, `de`, ... | Keep consistent across UI and requests |
| `order_uid` | Yes | App-specific unique string | Unique per purchase attempt |
| `order_name` | No | Human-readable label | Useful for support and logs |
| `order_amount` | Yes | Numeric string | Use same value across client/server |
| `order_currency` | Yes | ISO 4217 | Must be supported by selected method |
| `payment_method` | Yes | `HPaySiteMethodId` string | Never use `pm.Uid` here |
| `shipping_method` | No | `HPaySiteMethodId` string | Send only when shipping is used |
| `order_user_url` | No | HTTPS URL | Browser flow only |
| `notify_url` | No | Public HTTPS URL | Webhook authority endpoint |
| `order_data` | No | Object/map | Stored in resulting order `Data` |
| `cof` | No | `optional|required|none` | Checkout card-save behavior |
| `vault_token_uid` | No | Token UUID or `1|true|new` | Saved card or save-request hint |
| `verificationhash` | No (initial FrontCore pay) | SHA-512 lowercase hex | Required for backend charge/verification |
| `order_billing.email` | No | Email | Validate syntax before send |
| `order_billing.phone` | No | E.164-like | Keep normalized |
| `order_billing.country` | No | ISO-2 | Use uppercase (`RS`, `US`) |
| `order_shipping.country` | No | ISO-2 | Align with shipping method support |
| `order_shipping.dispenser` | No | Provider ID | Locker/paket-shop only |
| `order_shipping.dispenser_method_id` | No | Method ID string | Must match `shipping_method` |
| `order_items[].posuid` | Yes | String/number | Merchant-defined internal item identifier (not a fixed HolestPay enum) |
| `order_items[].name` | Yes | String | Human-readable item name (not `title`) |
| `order_items[].qty` | Yes | Number/string | Positive quantity expected (not `quantity`) |
| `order_items[].price` | No | Number/string | Keep pricing model consistent |
| `order_items[].subtotal` | Yes | Number/string | Mandatory line subtotal |
| `order_items[].virtual` | No | `0|1` | Shipping relevance hint |
### FrontCore Origin and Script Diagnostics
- Validate script URL format exactly: `/clientpay/handlers/pos/{merchant_site_uid}/frontend-script-core.js`.
- Confirm script host matches environment (`sandbox.pay.holest.com` vs `pay.holest.com`).
- Confirm browser page origin is included in `Frontend Script-Core Origins`.
- Use explicit startup guard for missing global:
```javascript
setTimeout(() => {
if (typeof HolestPayCheckout === 'undefined') {
console.error('FrontCore script not loaded: verify origin whitelist and script URL.');
}
}, 5000);
```
- Keep whitelist entries minimal and deliberate; avoid broad wildcards on production unless absolutely necessary.
- Re-check whitelist when moving from local/dev domain to staging/prod domain.
### Server Workflow Blueprint (FrontCore)
```text
1) Frontend loads FrontCore script from handlers/pos/{merchant_site_uid} URL.
2) Frontend initializes HPay and builds pay_request (without verificationhash).
3) Frontend calls HPay.presentHPayPayForm(pay_request).
4) Frontend receives onHPayResult and forwards payload to backend for logging.
5) Backend verifies result signature for authoritative processing.
6) Webhook arrives (possibly before/after browser callback).
7) Backend verifies webhook signature and applies idempotent state transition.
8) Fulfillment runs only once after verified terminal/success policy conditions.
9) For MIT/COF backend charge, backend builds charge_request + verificationhash and calls charge endpoint.
```
### Idempotent Webhook Handling Example (Node.js Pseudocode)
```javascript
// Pseudocode only: adapt to your DB and framework.
app.post('/webhooks/hpay', async (req, res) => {
const payload = req.body || {};
const orderUid = String(payload.order_uid || '');
const txUid = String(payload.transaction_uid || '');
const idempotencyKey = `${orderUid}:${txUid}:${payload.status || ''}`;
if (!orderUid) return res.status(400).json({ ok: false, error: 'missing order_uid' });
// Signature validation is still mandatory for backend authority
const calculated = generatePOSRequestSignature(MERCHANT_SITE_UID, SECRET_KEY, payload);
const valid = calculated === String(payload.vhash || '').toLowerCase();
if (!valid) return res.status(400).json({ ok: false, error: 'invalid signature' });
const alreadyProcessed = await db.idempotency.exists(idempotencyKey);
if (alreadyProcessed) return res.status(200).json({ ok: true, duplicate: true });
await db.tx(async trx => {
await trx.idempotency.insert({ key: idempotencyKey, createdAt: new Date() });
await trx.hpayEvents.insert({
orderUid,
transactionUid: txUid,
paymentStatus: payload.payment_status || null,
orderStatus: payload.status || null,
raw: JSON.stringify(payload),
source: 'webhook'
});
const paymentStatus = String(payload.payment_status || '').toUpperCase();
if (/PAID|SUCCESS|PAYING|RESERVED|OBLIGATED/.test(paymentStatus)) {
await trx.orders.markAsPaidOrReserved(orderUid, paymentStatus);
await trx.jobs.enqueue({ type: 'FULFILLMENT_DECISION', orderUid });
} else if (/AWAITING/.test(paymentStatus)) {
// Not failed: keep order pending and show payment_html instructions on return/thank-you page
await trx.orders.markAsPendingPaymentInstructions(orderUid, paymentStatus);
} else {
await trx.orders.markAsPaymentNotCompleted(orderUid, paymentStatus);
}
});
return res.status(200).json({ ok: true });
});
```
### Browser Callback + Webhook Reconciliation Rules
- If browser callback succeeds first, store it as provisional until webhook check completes.
- If webhook succeeds first, mark server truth immediately; browser callback only enriches logs/UI.
- If callback says success but webhook never arrives, run delayed status query before fulfillment.
- If callback and webhook disagree, trust verified server-side signature + latest authoritative status policy.
- Never ship goods/services exclusively from client-side event data.
### Operational State Model (Recommended)
- `ORDER_CREATED`: order exists locally before payment started.
- `PAYMENT_INITIATED`: FrontCore request sent to payment UI.
- `PAYMENT_CALLBACK_RECEIVED`: browser event stored.
- `WEBHOOK_RECEIVED`: webhook accepted and verified.
- `PAYMENT_CONFIRMED`: business rule says financial completion met.
- `FULFILLMENT_PENDING`: queued for shipping/fiscal/integration actions.
- `FULFILLED`: goods/services delivered or process completed.
- `PAYMENT_FAILED`: terminal non-success status.
- `CLOSED`: final immutable state with audit trail.
### Production Readiness Checklist
- Keep `Frontend Script-Core Origins` strict and reviewed per deployment.
- Protect admin/backend code paths that collect/use Secret Key.
- Add request/response size limits and payload schema validation at backend edge.
- Enable TLS-only endpoints for checkout and webhook.
- Add monitoring alarms for missing FrontCore script load events and webhook signature failures.
- Capture dashboard metrics: conversion by method, callback-to-webhook lag, duplicate webhook rate.
- Create runbook for manual recovery: status query, refund/void/capture decisions, replay-safe reprocessing.
- Test environment cutover with explicit checklist (POS UID, methods, notify URLs, allowed origins, secrets).
### Troubleshooting Cookbook
- Symptom: `HolestPayCheckout` is undefined.
- Check: origin whitelist entry, script URL path includes correct `merchant_site_uid`, environment host.
- Fix: add exact HTTPS test origin to `Frontend Script-Core Origins` and reload.
- Symptom: FrontCore works on one domain but not another.
- Check: wildcard pattern coverage and path-level matching assumptions.
- Fix: add explicit origin/pattern entry for each domain stage (dev/stage/prod) and retest.
- Symptom: payment UI opens but methods list is empty.
- Check: POS method activation in panel, country/amount filters, currency compatibility.
- Fix: verify `availablePaymentMethods(...)` inputs and POS configuration in same environment.
- Symptom: result arrives in browser but order not updated on server.
- Check: callback forwarding endpoint, webhook delivery logs, signature verification result.
- Fix: persist callback as provisional and complete state transition on verified webhook.
- Symptom: signature mismatch on webhook/backend verification.
- Check: amount normalization to 8 decimals, field order in signature string, correct secret key/environment.
- Fix: use one shared signature utility across all server handlers and add test vectors.
- Symptom: webhook endpoint receives duplicates.
- Check: idempotency key existence and transaction wrapping around insert/process logic.
- Fix: move idempotency write before business action and enforce unique DB constraint on key.
- Symptom: charge request fails with saved token.
- Check: token validity/scope, method supports `charge`, signature correctness, environment match.
- Fix: use fresh token tied to same merchant scope and verify method `POps` includes `charge`.
- Symptom: user is not redirected to thank-you URL.
- Check: method iframe/redirect behavior and callback handling.
- Fix: redirect manually in success branch using `r.order_user_url` when appropriate.
### Suggested CI/QA Validation Cases
- Validate JSON schema for `pay_request` and `charge_request` in unit tests.
- Validate signature generation against fixed fixtures in PHP and Node.js implementations.
- Validate idempotency behavior by replaying same webhook payload at least 3 times.
- Validate parser for composed status strings with and without fiscal/shipping segments.
- Validate route-level access control for admin/backend operations requiring Secret Key.
- Validate payload size guard rejects requests above `64 KB`.
- Validate environment guard rejects sandbox credentials on production host and vice versa.
- Validate origin guard behavior: whitelisted origin passes, non-whitelisted origin fails predictably.
- Validate correlation logs always include `order_uid` and `merchant_site_uid`.
### Security No-Go List
- Never hardcode `secret_key` in browser JavaScript, HTML templates, or mobile bundle assets.
- Never process fulfillment on unverified callback payload.
- Never expose raw webhook endpoint without rate limiting and request body size limits.
- Never trust query params from `order_user_url` alone as proof of payment.
- Never log secret values or full PAN/cardholder data in application logs.
- Never reuse one `order_uid` for multiple independent purchases.
### Terminology Quick Map
- `POS` in HolestPay = your app/site sales endpoint, not a physical cashier terminal.
- `FrontCore` = JS-first flow where initial checkout signing is origin-trust based.
- `status` = composed platform state across payment/fiscal/shipping modules.
- `payment_status` = payment module status focus.
- `verificationhash` = request signature hash used for backend charge/operations.
- `vhash` = response signature hash received from HPay result/webhook.
- `order_data` = custom merchant metadata persisted to order `Data`.
---
## Key Object Reference
All fields supported by the template are listed in `Step 2` under `Full Template Field Catalog (Standalone)`.
---
## Important Notes
- The page must be served over **HTTPS**. HPay will not work on `file://` or plain HTTP.
- `payment_method` value is `pm.HPaySiteMethodId` — **not** `pm.Uid` (these are different).
- `availablePaymentMethods(country, amount, currency)` returns methods available for the given buyer country and order. Use billing country for payment, shipping country for shipping.
- If `pm['Use IFRAME'] === false`, the method uses redirect — your page cannot receive the postback inline. Proper server-side integration (webhook) is required.
- After a successful payment, generate a new `order_uid` for the next order — never reuse UIDs.
- `order_data` supports custom metadata and is stored as HPay order `Data`.
- `order_billing` and `order_shipping` can include additional custom fields, but keep total serialized order payload under **64 KB**.
- If your FrontCore page also needs to display the Secret Key prompt (e.g. for admin ops), collect it via a prompt/dialog at runtime — never hardcode it in the page source.
- The Secret Key may be collected once per session (e.g. via `prompt()` or an admin login flow) and stored in a local variable for use during the current session only.
---
## Required for Bank Production Approval — Logotypes and Terms of Service
> ?? **This section has nothing to do with payment functionality** — payments work without it. However, **almost all banks in the region will require these elements to be present on the site before approving the POS for production use.** Implement these alongside the payment integration.
---
### Footer Logotypes (Card logos, Bank logos, 3DS logos)
Banks require card brand logos, acquiring bank logos, and 3DS security logos to appear in the site footer — in a single horizontal line, **no taller than approximately 1 cm visually**. Order: card logos first, bank logos in the middle (with some spacing on both sides), 3DS logos on the right. Bank and 3DS logos must be linked. The footer strip must be visible on **all pages of the website**, not only on checkout.
HolestPay provides all logo image URLs and link targets via `HPay.POS.pos_parameters` after `HPayInit()`. Use them — do not source logos elsewhere.
**CSS for the footer branding strip:**
```css
.hpay_footer_branding_wrapper {
width: 100%;
padding: 8px 0;
border-top: 1px solid #e0e0e0;
}
.hpay_footer_branding {
display: flex;
align-items: center;
gap: 0;
flex-wrap: nowrap;
}
.hpay-footer-branding-cards,
.hpay-footer-branding-bank,
.hpay-footer-branding-3ds {
display: flex;
align-items: center;
flex-wrap: nowrap;
}
.hpay-footer-branding-bank { margin: 0 12px; }
.hpay_footer_branding img { height: 1cm; width: auto; display: inline-block; }
```
**JavaScript — call this after `HPayInit()` resolves:**
```javascript
function renderHPayFooterLogotypes() {
if (!(typeof HPay !== 'undefined' && HPay && HPay.POS)) return;
if (!HPay.POS.pos_parameters) return;
let card_images_html = '';
let banks_html = '';
let threes_html = '';
if (HPay.POS.pos_parameters['Logotypes Card Images']) {
HPay.POS.pos_parameters['Logotypes Card Images'].split('\n').forEach(src => {
if (src.trim()) card_images_html += `<img src="${src.trim()}" alt="Card" />`;
});
}
if (HPay.POS.pos_parameters['Logotypes Banks']) {
HPay.POS.pos_parameters['Logotypes Banks'].split('\n').forEach(line => {
if (!line.trim()) return;
// format: "imageUrl:linkUrl" — colons in URLs are escaped before splitting
const t = line.replace(/https:/gi, '-PS-').replace(/http:/gi, '-P-')
.split(':').map(r => r.replace(/-P-/g, 'http:').replace(/-PS-/g, 'https:'));
banks_html += t.length > 1
? `<a href="${t[1]}" target="_blank"><img src="${t[0]}" alt="Bank" /></a>`
: `<img src="${t[0]}" alt="Bank" />`;
});
}
if (HPay.POS.pos_parameters['Logotypes 3DS']) {
HPay.POS.pos_parameters['Logotypes 3DS'].split('\n').forEach(line => {
if (!line.trim()) return;
const t = line.replace(/https:/gi, '-PS-').replace(/http:/gi, '-P-')
.split(':').map(r => r.replace(/-P-/g, 'http:').replace(/-PS-/g, 'https:'));
threes_html += t.length > 1
? `<a href="${t[1]}" target="_blank"><img src="${t[0]}" alt="3DS" /></a>`
: `<img src="${t[0]}" alt="3DS" />`;
});
}
const logotypesDiv = document.createElement('div');
logotypesDiv.className = 'hpay_footer_branding';
logotypesDiv.innerHTML =
`<div class="hpay-footer-branding-cards">${card_images_html}</div>` +
`<div class="hpay-footer-branding-bank">${banks_html}</div>` +
`<div class="hpay-footer-branding-3ds">${threes_html}</div>`;
const wrapper = document.createElement('div');
wrapper.className = 'hpay_footer_branding_wrapper';
wrapper.appendChild(logotypesDiv);
(document.querySelector('footer') || document.querySelector('main') || document.body)
.appendChild(wrapper);
}
// Call after HPayInit resolves:
// HPayInit().then(client => { renderHPayFooterLogotypes(); });
```
---
### Terms of Service Acceptance Checkbox
Almost all banks in the region require the customer to explicitly accept the site Terms of Service before payment — typically a checkbox with a link to the TOS content.
**HolestPay provides a ready-to-use Terms of Service / Purchase Conditions template page for each POS/site:**
```
https://sandbox.pay.holest.com/clientpay/tos/<merchant_site_uid>?lang=rs
https://pay.holest.com/clientpay/tos/<merchant_site_uid>?lang=en
```
Supported `lang` values: `en`, `rs`, `bs`, `hr`, `me`, `de`, `es`, `gr`, `tr`, `mk`, and others.
This URL returns HTML content (no `<html>` wrapper) and can be:
- Loaded in an `<iframe>`
- Fetched with `fetch()` / AJAX and injected into a modal
- Opened directly in the browser (use `target="_blank"`)
> ?? **Important:** This is **not** a separate "second HolestPay Terms" that replaces your site Terms. The `/clientpay/tos/<merchant_site_uid>` content is a merchant-specific **template/proposal of your own purchase Terms** (with your POS/merchant context), meant to be used as the same Terms of Service page your checkout checkbox points to. Keep one coherent TOS page for customers (your site TOS), and ensure it includes the required payment clauses.
**Implementation — TOS modal using HolestPay built-in dialog** (`hpay_dialog_open` becomes available after `client.loadHPayUI()` resolves):
```javascript
// Call client.loadHPayUI() first to make hpay_dialog_open available:
// HPayInit().then(client => client.loadHPayUI()).then(() => { /* hpay_dialog_open is ready */ });
function openTOS(merchant_site_uid, lang) {
const tos_url = `https://sandbox.pay.holest.com/clientpay/tos/${merchant_site_uid}?lang=${lang || 'en'}`;
// Replace sandbox host with pay.holest.com for production
hpay_dialog_open('tos', 'Terms of Service', tos_url, 'large', {
['I understand and accept these Terms of Service']: {
Run: function(dlg) {
dlg.close();
if (dlg.parentNode) dlg.parentNode.removeChild(dlg);
// Mark TOS as accepted — enable the Pay button or proceed with payment
},
action_position: 'center',
style: { 'min-width': '120px' }
}
});
}
```
**Minimum required UI — add this near the Pay button:**
```html
<label style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
<input type="checkbox" id="tos-accept" required />
<span>
I accept the
<a href="#" onclick="openTOS(MERCHANT_SITE_UID, 'en'); return false;">Terms of Service</a>
</span>
</label>
<!-- Disable Pay button until checkbox is checked -->
```
```javascript
document.getElementById('tos-accept').addEventListener('change', function() {
document.getElementById('do-pay').disabled = !this.checked;
});
```
**Checklist for bank approval:**
- [ ] Card brand logos visible in footer (from `HPay.POS.pos_parameters['Logotypes Card Images']`)
- [ ] Bank logos visible in footer, linked (from `HPay.POS.pos_parameters['Logotypes Banks']`)
- [ ] 3DS logos visible in footer, linked (from `HPay.POS.pos_parameters['Logotypes 3DS']`)
- [ ] All logos in a single horizontal line, max ~1 cm height
- [ ] TOS checkbox present near the Pay button, Pay button disabled until checked
- [ ] TOS content matches or includes HolestPay-provided TOS (`/clientpay/tos/<uid>`)
---
## Test Cards for Sandbox Testing
Test card numbers for almost all supported banks and payment methods can be found directly on the **dashboard page** of the HolestPay sandbox panel at https://sandbox.pay.holest.com — no need to search elsewhere. Log in and check the dashboard.
---
## Terms of Service Page — Required Content
The "Terms of Service" page that the customer checks before payment must be **comprehensive and self-contained**. Because the customer ticks a single "I accept the Terms of Service" checkbox that links to this one page, **everything required by the bank and by law must be covered on that exact page** — not spread across separate pages.
The following must be present in the Terms of Service content (either written directly or clearly summarized with a reference to the full document inline):
- **Purchase conditions** — what is being sold, pricing, order confirmation process
- **Delivery policy** — delivery methods, timeframes, costs, geographic coverage
- **Refund and return policy** — conditions, process, and timeframes for refunds and returns
- **PCI DSS statement** — explicit confirmation that card data transfer/processing is secured according to PCI DSS standards and that the merchant does not store raw card data (HolestPay handles card processing on the merchant's behalf)
- **Merchant contact information** — legal business name, address, email, and phone number for customer support
> The merchant may have separate dedicated pages for privacy policy, delivery conditions, refund policy, etc. — that is fine. But **all of the above topics must also appear on the single Terms of Service page** that the payment checkbox links to, because that is the only page the customer is asked to review and accept before paying.
> HolestPay provides a base TOS/purchase-conditions text via `/clientpay/tos/<merchant_site_uid>` that already includes payment-security wording (including PCI DSS transfer handling). Treat it as baseline content for the merchant's own single Terms page, then extend it with delivery, refund, and contact details — not as a separate second TOS document.
---
## Before Requesting Bank Production Approval — Site Readiness
Before the merchant contacts their bank to activate the POS for production, the site must be genuinely complete. A bank technician will review the site manually and will reject it if it does not look like a real, finished online store.
**The following will cause immediate rejection:**
- **Placeholder content** — any "Lorem ipsum", "Coming soon", "Test product", dummy images, or unfilled template text anywhere on the site
- **Mixed languages** — site content, product names, descriptions, and all pages must be consistently in one language (or properly localized if multilingual); a mix of languages on the same page signals an unfinished site
- **Missing or incomplete pages** — the site must have real products/services with actual descriptions and prices, a working checkout flow, and all required legal pages (Terms of Service, Privacy Policy, Contact/About)
- **Non-functional links or broken pages** — every linked page must load and contain real content
- **Test or sandbox data visible** — no test order UIDs, sandbox URLs, or debug output visible to visitors
> Tell the user: *"Before you ask your bank to approve the POS for production, make sure the site looks like a finished, real store. Bank technicians visit the site in person before approving. If they see Lorem ipsum text, empty product pages, mixed languages, or anything that looks unfinished, they will ask you to complete the site first and resubmit — which adds weeks to the process."*
---
## Bank Validation Testing Before Production Approval
Most banks require a **formal validation test** to be performed before activating the POS for production. This is separate from the developer's own sandbox testing.
What this typically involves:
- The bank provides a set of **specific test scenarios** that must be completed successfully (e.g. approved payment, declined payment, 3DS challenge flow, cancellation)
- Tests are performed using **test cards provided by the bank** (which may differ from the general sandbox test cards on the HPay dashboard)
- Results are reported back to the bank (sometimes automatically via their test monitoring system, sometimes manually by the merchant)
- **Whether validation testing is required, and exactly how it is done, depends on the bank and the specific payment method** — some banks require it for every new integration, others only for certain card brands or 3DS configurations
> Tell the user: *"Before your bank activates the production POS, they will likely ask you to run a set of validation test payments using specific test cards they provide. This is a standard bank requirement and is separate from the testing you did during development. Contact your bank's technical integration team to find out exactly what tests are required for your payment method — HolestPay sandbox will be used for these tests as well."*
---
## Shipping Method UI — Required `hpay-sm-options` Placeholder
In the UI element that displays a shipping method's description (the area shown to the buyer when they select a shipping method), you **must include an empty `<span>` with the class `hpay-sm-options` and attribute `hpay_shipping_method_id="<hpay_shipping_method.HPaySiteMethodId>"`**:
```html
<span class="hpay-sm-options" hpay_shipping_method_id="<hpay_shipping_method.HPaySiteMethodId>"></span>
```
HolestPay uses this element to inject additional shipping options and information (e.g. parcel locker selector, delivery time slots, carrier tracking info) for the selected shipping method. Without this placeholder, those features will silently fail to render.
Place it inside the shipping method description container, after any static description text:
```html
<div class="shipping-method-description">
<!-- your static description text here -->
<span class="hpay-sm-options" hpay_shipping_method_id="45"></span>
</div>
```
---
## Content Security Policy (CSP) and Site Configuration Requirements
For HolestPay to function correctly, the site must permit the following — ensure these are not blocked by Content Security Policy headers, server configuration, or any firewall/proxy:
### Allowed origins (iframes, scripts, XHR/fetch, content)
The site must allow iframes, scripts, and content loaded from:
```
https://pay.holest.com
https://sandbox.pay.holest.com
```
If the site sets a `Content-Security-Policy` header, include these in all relevant directives:
```
Content-Security-Policy:
script-src 'self' https://pay.holest.com https://sandbox.pay.holest.com ...;
frame-src 'self' https://pay.holest.com https://sandbox.pay.holest.com ...;
connect-src 'self' https://pay.holest.com https://sandbox.pay.holest.com ...;
img-src 'self' https://pay.holest.com https://sandbox.pay.holest.com data: ...;
```
### `eval()` must be permitted
HolestPay internally uses `eval()` to deserialize and execute certain POS method action functions returned from the server (`initActions`, `orderActions`). The site must **not** block `eval()`.
If a CSP header is set, `'unsafe-eval'` must be present in `script-src`:
```
Content-Security-Policy:
script-src 'self' 'unsafe-eval' https://pay.holest.com https://sandbox.pay.holest.com ...;
```
> ?? If the site uses a strict CSP that blocks `eval()` or restricts iframes/scripts to specific origins, HolestPay will fail silently or partially. This is one of the most common causes of "nothing happens when I click Pay" during integration.
---
## Dock Container Placement
For each payment method row, use this visual order:
1) method **name/label**
2) method **description**
3) method **dock container** (if that method supports docking)
The dock container must be below the description of the same method, and before the next method name is rendered. It must **not** be placed after the full list of all payment methods.
Each payment method in the list that supports docking (`pm.PayInputUrl` is set) needs its own dock container adjacent to it. Best practice is to wrap **description + dock** in one method-details wrapper that is shown only when that method is selected. When the buyer selects that method, `HPay.setPaymentMethodDock()` renders the embedded payment input directly inside that container.
**Correct structure:**
```html
<label>
<input type="radio" name="payment_method" value="179" />
Credit Card
</label>
<div class="method-details is-selected" data-method="179">
<div class="method-description">Card payment description...</div>
<div id="paymentMethodDock-179" class="hpay-dock-container"></div>
</div>
<label>
<input type="radio" name="payment_method" value="180" />
Bank Transfer
</label>
<div class="method-details" data-method="180">
<div class="method-description">Bank transfer description...</div>
<!-- no dock here — this method does not support docking -->
</div>
```
---
## Always Render Method Description When Selected
Whenever a payment method or shipping method is selected by the buyer, **always display its description**. Do not skip or hide descriptions.
Method descriptions sometimes contain **functionally important content** — instructions the buyer must read (e.g. bank account number for manual transfer, pickup location details, special conditions). Hiding or omitting descriptions can cause buyer confusion and failed orders.
For shipping methods, the description container must also include the `<span class="hpay-sm-options" hpay_shipping_method_id="<hpay_shipping_method.HPaySiteMethodId>"></span>` placeholder (see earlier section) so HolestPay can inject carrier-specific UI into it.
---
## HolestPay Language Codes
HolestPay uses its own language code convention — **do not use standard ISO/BCP-47 codes** for Serbian:
| Language | HolestPay code | ? Do NOT use |
|---|---|---|
| Serbian Latin | `rs` | `sr`, `sr-Latn`, `sr-YU`, `sr-lat` |
| Serbian Cyrillic | `rs-cyr` | `sr-Cyrl`, `sr-cyr`, `cyr` |
| Bosnian | `bs` | |
| Croatian | `hr` | |
| Slovenian | `si` | |
| Macedonian | `mk` | |
| English | `en` | |
| German | `de` | |
| Italian | `it` | |
| Spanish | `es` | |
| French | `fr` | |
| Portuguese | `pt` | |
| Dutch | `nl` | |
| Greek | `el` | `gr` |
| Turkish | `tr` | |
Pass this value as the `language` parameter to `HPayInit()` and as `hpaylang` in `pay_request`.









