--- url: https://simplepay.webmania.cc/en/ai/agent-skill.md description: >- Install the simplepay-js-sdk Agent Skill (npx skills add rrd108/simplepay-js-sdk) for Claude Code, Cursor and other AI coding agents. --- # Agent Skill The repo contains an [Agent Skill](https://skills.sh) (`skills/simplepay-js-sdk/SKILL.md`): a set of instructions for AI coding agents (Claude Code, Cursor, Codex and others) on wiring up SimplePay payments, IPN, recurring payments, Google Pay and Apple Pay with this package. ## Install In your project root: ```bash npx skills add rrd108/simplepay-js-sdk ``` The agent then loads the skill on its own when it works on a SimplePay integration. You can also ask for it, for example: “Add SimplePay payments using the simplepay-js-sdk skill”. ## What it covers * installation and environment variables * the three endpoints (start payment, back URL, IPN) * Google Pay and Apple Pay buttons and server side * recurring payments, token charges, card removal * security rules (secret key, raw IPN body, idempotency) ## If the agent gets it wrong These docs are written from the source code and are the reference. If the agent imports a function that doesn't exist (for example `getSimplePayConfig`), point it to this site or the [API reference](../reference/api). Full docs for agents: [llms.txt](./llms). --- --- url: https://simplepay.webmania.cc/en/reference/api.md description: >- Every exported simplepay-js-sdk function with parameters, return values and errors: startPayment, getPaymentResponse, handleIpnRequest, startRecurringPayment, startTokenPayment, cancelCard, getTransactionStatus, queryTransactions, refund, startGooglePay, startApplePay, doApplePay, renderGooglePayButton, renderApplePayButton. --- # Functions The package has three entry points: | Import | Runs in | Contents | |---|---|---| | `simplepay-js-sdk` | server (Node.js) | payments, IPN, recurring, Google Pay and Apple Pay server side, helpers | | `simplepay-js-sdk/google-pay` | browser | `renderGooglePayButton` | | `simplepay-js-sdk/apple-pay` | browser | `renderApplePayButton` | Server functions read the keys from [environment variables](./environment). Types: [Types](./types). ## Payments ### `startPayment` ```ts startPayment(paymentData: PaymentData, config?: StartPaymentConfig): Promise ``` Starts a one-time payment (`POST /start`). Redirect the customer to the returned `paymentUrl`. * `paymentData`: [`PaymentData`](./types#paymentdata) * `config.redirectUrl`: return URL for this payment (default: `SIMPLEPAY_REDIRECT_URL`) * `config.urls`: `{ success, fail, cancel, timeout }`, a separate URL per outcome; when given, it is sent instead of `url` * Defaults: `currency: 'HUF'`, `language: 'HU'`, `method: 'CARD'`, 30-minute timeout (override with the `timeout` field) * When `items` is sent, SimplePay ignores `total`. * Guide: [One-time payment](../guide/one-time-payment) ### `getPaymentResponse` ```ts getPaymentResponse(r: string, s: string): SimplePayResult ``` Verifies and decodes the back-URL `r` and `s` parameters. Synchronous. * Replaces spaces in `s` with `+`. * Picks the currency and key from the merchant ID. * Errors: `Merchant id not found in the environment: …`, `Missing SimplePay configuration for …`, `Invalid response signature` * Guide: [Back URL](../guide/back-url) ### `handleIpnRequest` ```ts handleIpnRequest(ipnBody: string, incomingSignature: string, merchantKey: string): { responseBody: string, signature: string } ``` Handles an IPN: verifies the signature, inserts `receiveDate`, signs the response. Synchronous. * `ipnBody`: the **raw** request body * `incomingSignature`: the `Signature` header * `merchantKey`: the account's secret key * Errors: `Invalid IPN request signature`, `Invalid IPN request body`, `Missing merchant key` * Guide: [IPN](../guide/ipn) ## Recurring payments ### `startRecurringPayment` ```ts startRecurringPayment(paymentData: RecurringPaymentData, config?: StartPaymentConfig): Promise ``` Payment with card registration (`POST /start`). The response's `tokens` array is needed for later charges. * `config`: `redirectUrl` or `urls`, as for `startPayment`. * Always `CARD`; `threeDSReqAuthMethod` defaults to `'02'`. * `recurring` defaults for falsy fields: `times: 3`, `until`: about 180 days, `maxAmount: 12000`. ### `startTokenPayment` ```ts startTokenPayment(paymentData: TokenPaymentData, config?: PaymentConfig): Promise ``` Charges a stored token without the customer (`POST /dorecurring`, `type: 'MIT'`). `method` must be `'CARD'`. `config.redirectUrl` overrides `SIMPLEPAY_REDIRECT_URL`. ### `cancelCard` ```ts cancelCard(cardId: string): Promise ``` Removes a registered card (`POST /cardcancel`). `cardId` is the SimplePay `transactionId` of the card registration. Always uses the **HUF** account keys. On success `status` is `'DISABLED'`. Guide: [Recurring payments](../guide/recurring-payments) ## Transactions ### `getTransactionStatus` ```ts getTransactionStatus(query: TransactionStatusQuery): Promise ``` Status of one transaction (`POST /status`). Exactly one identifier is required: `transactionId` or `orderRef`. * `query.currency`: currency of the merchant account (default: `HUF`) * The response `status` is a `TransactionStatus` ([types](./types)); `endState` is `true` when the status is final. * Errors: `Pass exactly one of transactionId or orderRef`, `Invalid transaction id: …`, `SimplePay API error: …` * Guide: [Refunds and queries](../guide/refunds-and-queries) ### `queryTransactions` ```ts queryTransactions(query: Q): Promise> ``` Looks up one or more transactions (`POST /query`) by `transactionIds` and/or `orderRefs`. * `query.detailed`: also return the order data * `query.refunds`: also return the refund status and the refunds * `query.currency`: currency of the merchant account (default: `HUF`) * The response type follows the `detailed` and `refunds` flags. * Errors: `Pass at least one transactionId or orderRef`, `Invalid transaction id: …`, `SimplePay API error: …` * Guide: [Refunds and queries](../guide/refunds-and-queries) ### `refund` ```ts refund(refundData: RefundData): Promise ``` Refunds a `FINISHED` transaction fully or partially (`POST /refund`), by `transactionId` or `orderRef`. * `refundData.refundTotal`: the amount to refund (in the transaction's currency) * `refundData.currency`: the transaction's currency, which also picks the merchant account (default: `HUF`) * Returns: `refundTransactionId`, `refundTotal`, `remainingTotal` * Errors: `Pass exactly one of transactionId or orderRef`, `Invalid transaction id: …`, `Invalid refund total: …`, `SimplePay API error: …` * Guide: [Refunds and queries](../guide/refunds-and-queries) ## Google Pay ### `startGooglePay` ```ts startGooglePay(paymentData: GooglePayPaymentData, config?: PaymentConfig): Promise ``` Google Pay charge (`POST /dogooglepay`, `type: 'CIT'`). * `HUF_SZEP` is not supported. * Error code `3004` with `redirectUrl` is not thrown: the response is returned and the browser redirects to 3DS. * Errors: `Missing Google Pay token`, `Google Pay does not support HUF_SZEP`, `SimplePay API error: …` ### `renderGooglePayButton` ```ts import { renderGooglePayButton } from 'simplepay-js-sdk/google-pay' renderGooglePayButton(config: GooglePayButtonConfig): Promise ``` Renders the Google Pay button in the browser if the browser can pay with Google Pay. On click it `POST`s `{ googlePayToken, orderRef }` to `authorizationEndpoint`. Config: [`GooglePayButtonConfig`](./types#googlepaybuttonconfig). Guide: [Google Pay](../guide/google-pay) ## Apple Pay ### `startApplePay` ```ts startApplePay(paymentData: ApplePayStartData): Promise ``` Apple Pay session for merchant validation (`POST /startapplepay`). `domain` is the registered FQDN. The response contains `transactionId` and `applePaySession`. ### `doApplePay` ```ts doApplePay(paymentData: ApplePayChargeData): Promise ``` Apple Pay charge (`POST /doapplepay`). Throws if `applePayStatus` is not `STATUS_SUCCESS`. ### `renderApplePayButton` ```ts import { renderApplePayButton } from 'simplepay-js-sdk/apple-pay' renderApplePayButton(config: ApplePayButtonConfig): Promise ``` Renders the Apple Pay button in the browser if available. Config: [`ApplePayButtonConfig`](./types#applepaybuttonconfig). Guide: [Apple Pay](../guide/apple-pay) ## Helpers ### `generateSignature` ```ts generateSignature(body: string, merchantKey: string): string ``` HMAC-SHA384 signature, Base64-encoded. Throws `Missing merchant key` for an empty key. ### `checkSignature` ```ts checkSignature(responseText: string, signature: string, merchantKey: string): boolean ``` Verifies a signature with a timing-safe comparison (`crypto.timingSafeEqual`). Returns `false` for a non-string or different-length signature. ### `toISO8601DateString` ```ts toISO8601DateString(date: Date): string ``` The date format SimplePay expects: `2026-12-31T18:00:00+00:00` (UTC, no milliseconds). Useful for `recurring.until`. ## Not exported `getSimplePayConfig` and `getCurrencyFromMerchantId` are internal and cannot be imported from the package. Read the key from `process.env.SIMPLEPAY_MERCHANT_KEY_`. --- --- url: https://simplepay.webmania.cc/en/guide/apple-pay.md description: >- An Apple Pay button on your own page with SimplePay: domain registration, renderApplePayButton in the browser, startApplePay and doApplePay on the server. --- # Apple Pay Merchant-hosted Apple Pay uses two SimplePay calls: `startapplepay` (a session for merchant validation), then `doapplepay` (the charge). The payment finishes inside the Apple Pay sheet; the customer stays on your page. * **browser**: `renderApplePayButton` from `simplepay-js-sdk/apple-pay` * **server**: `startApplePay` and `doApplePay` from `simplepay-js-sdk` Fulfil the order from the [IPN](./ipn) here too. Apple Pay does not support the `HUF_SZEP` currency. ## Setup 1. On the Apple Pay tab of the SimplePay merchant admin, register your checkout domain (FQDN, for example `shop.example.com`). 2. Host the downloaded association file at `https:///.well-known/apple-developer-merchantid-domain-association`. 3. `merchantIdentifier` is the Apple Pay merchant identifier shown in the SimplePay admin. 4. The button shows in Safari (and other browsers that support Apple Pay). ## Browser: the button ```ts import { renderApplePayButton } from 'simplepay-js-sdk/apple-pay' await renderApplePayButton({ container: '#apple-pay', merchantIdentifier: 'APPLE_PAY_MERCHANT_IDENTIFIER', merchantName: 'Shop Ltd.', // shown next to the amount validationEndpoint: '/api/apple-pay/validate', authorizationEndpoint: '/api/apple-pay/authorize', currency: 'HUF', // 3-letter code total: '1212', // positive, at most 2 decimals orderRef: 'order-12', countryCode: 'HU', // optional, default HU locale: 'en-US', // optional, default hu-HU buttonStyle: 'black', // optional: black | white | white-outline buttonType: 'plain', // optional: plain | buy | pay | check-out | book | donate | subscribe supportedNetworks: ['visa', 'masterCard'], // optional, default visa, masterCard, amex, discover onResult: (result) => { /* successful charge */ }, onError: (error) => { /* error */ }, }) ``` What it does: 1. If the browser can't pay with Apple Pay, it **renders no button**. 2. Loads the Apple Pay JS SDK and adds an `` element to the container. 3. On click it opens an Apple Pay session. For merchant validation it `POST`s `{ orderRef, domain }` to `validationEndpoint`, where `domain` is the browser's hostname. It expects `transactionId` and `applePaySession` in the response. 4. When the customer approves, it `POST`s `{ orderRef, transactionId, applePayToken }` to `authorizationEndpoint`. `applePayToken` is already Base64. 5. If the response has `applePayStatus: 'STATUS_SUCCESS'` and no error codes, it closes the sheet as successful and calls `onResult`; otherwise it closes it as failed. ## Server: validation ```ts import { startApplePay } from 'simplepay-js-sdk' // POST /api/apple-pay/validate body: { orderRef, domain } const REGISTERED_DOMAIN = 'shop.example.com' if (domain !== REGISTERED_DOMAIN) { throw new Error('Unregistered Apple Pay domain') } const order = await loadOrder(orderRef) const session = await startApplePay({ orderRef: order.orderRef, total: order.total, currency: 'HUF', customerEmail: order.email, language: 'EN', domain: REGISTERED_DOMAIN, // your own registered FQDN – not the value from the browser }) await saveApplePayTransaction(order.orderRef, session.transactionId) return session // contains transactionId, applePaySession ``` `startApplePay` throws when `domain` is not a valid FQDN (`Apple Pay domain must be the registered FQDN`), when SimplePay returns error codes, or when the response has no `applePaySession` (`Missing Apple Pay session`). ## Server: the charge ```ts import { doApplePay } from 'simplepay-js-sdk' // POST /api/apple-pay/authorize body: { orderRef, transactionId, applePayToken } const expected = await loadApplePayTransaction(orderRef) if (String(expected) !== String(transactionId)) { throw new Error('transactionId does not belong to this order') } const payment = await doApplePay({ transactionId, applePayToken, // unchanged currency: 'HUF', }) return payment // applePayStatus: 'STATUS_SUCCESS' ``` `doApplePay` throws when: * `transactionId` is not a positive integer: `Invalid Apple Pay transaction id` * the token is not valid Base64 or too long: `Missing Apple Pay token` * SimplePay returns error codes * `applePayStatus` is not `STATUS_SUCCESS`: `Apple Pay authorization failed` ::: warning The server decides the amount SimplePay charges the `total` passed to `startApplePay`. The button's `total` is only what the Apple Pay sheet shows. ::: --- --- url: https://simplepay.webmania.cc/en/guide/configuration.md description: >- Set the SimplePay merchant ID and secret key per currency (HUF, HUF_SZEP, EUR, USD) in environment variables; sandbox vs production, return URL and logging. --- # Configuration The SDK has no configuration object: it reads everything from **environment variables**, on every call. The same code runs in sandbox and production; only the `.env` differs. ## Keys per currency SimplePay gives you a separate merchant account per currency. The variable name contains the currency code: | Currency | Merchant ID | Secret key | |---|---|---| | `HUF` (default) | `SIMPLEPAY_MERCHANT_ID_HUF` | `SIMPLEPAY_MERCHANT_KEY_HUF` | | `HUF_SZEP` (SZÉP card) | `SIMPLEPAY_MERCHANT_ID_HUF_SZEP` | `SIMPLEPAY_MERCHANT_KEY_HUF_SZEP` | | `EUR` | `SIMPLEPAY_MERCHANT_ID_EUR` | `SIMPLEPAY_MERCHANT_KEY_EUR` | | `USD` | `SIMPLEPAY_MERCHANT_ID_USD` | `SIMPLEPAY_MERCHANT_KEY_USD` | Only set the currencies you use. If a payment starts in a currency with no keys, the SDK throws `Missing SimplePay configuration for `. `HUF_SZEP` is a separate account but is sent to SimplePay as `HUF`: the SDK strips the `_SZEP` suffix in the request and signs with the SZÉP account's key. ::: tip The back URL is matched by merchant ID `getPaymentResponse` looks up which `SIMPLEPAY_MERCHANT_ID_*` variable holds the returned merchant ID and verifies with that currency's key. Don't use the same merchant ID for two currencies. ::: ## Sandbox and production ```bash SIMPLEPAY_PRODUCTION=true ``` * If the value is exactly `true`, calls go to `https://secure.simplepay.hu/payment/v2`. * Anything else (unset, `false`, `1` …) uses the sandbox: `https://sandbox.simplepay.hu/payment/v2`. Sandbox and live accounts have different keys. Swap the keys when you go live. ## Return URL ```bash SIMPLEPAY_REDIRECT_URL=https://example.com/payment/back ``` SimplePay sends the customer back here with the `r` and `s` parameters. For one-time and recurring payments, token charges and Google Pay you can also pass a per-payment `redirectUrl` option, which overrides the variable. The `urls` option of `startPayment` and `startRecurringPayment` sets a separate address per outcome; then the variable is not needed. | Environment | When not set | When not `https` | |---|---|---| | Sandbox | uses the placeholder `http://url.to.redirect` | accepted | | Production (`SIMPLEPAY_PRODUCTION=true`) | throws | throws | In production the error is `SimplePay return url must be absolute https in production`. ## Logging ```bash SIMPLEPAY_LOGGER=true ``` Turns on the SDK's debug log (`console.log`): function name, API URL, order reference, HTTP status and error codes. It never logs the secret key or the customer's email. Turn it off in production. ## Timeouts Built in, not configurable: * Every SimplePay call is aborted after 30 seconds (`AbortSignal.timeout`). * The payment page (`timeout` field) is valid for 30 minutes from the start of the payment. ## Example `.env` ```bash # sandbox SIMPLEPAY_MERCHANT_ID_HUF=P123456 SIMPLEPAY_MERCHANT_KEY_HUF=sandbox-secret-key SIMPLEPAY_MERCHANT_ID_HUF_SZEP=P123457 SIMPLEPAY_MERCHANT_KEY_HUF_SZEP=sandbox-szep-key SIMPLEPAY_REDIRECT_URL=https://example.com/payment/back SIMPLEPAY_LOGGER=true ``` All variables in one table: [Environment variables](../reference/environment). --- --- url: https://simplepay.webmania.cc/en/reference/environment.md description: >- Every simplepay-js-sdk environment variable: SIMPLEPAY_MERCHANT_ID_*, SIMPLEPAY_MERCHANT_KEY_*, SIMPLEPAY_PRODUCTION, SIMPLEPAY_REDIRECT_URL, SIMPLEPAY_LOGGER. --- # Environment variables The SDK reads `process.env` on every call. There is no other configuration. | Variable | Required | Description | |---|---|---| | `SIMPLEPAY_MERCHANT_ID_HUF` | for HUF | HUF merchant ID | | `SIMPLEPAY_MERCHANT_KEY_HUF` | for HUF | HUF secret key. `cancelCard` uses it too. | | `SIMPLEPAY_MERCHANT_ID_HUF_SZEP` | for SZÉP card | SZÉP card account merchant ID | | `SIMPLEPAY_MERCHANT_KEY_HUF_SZEP` | for SZÉP card | SZÉP card account secret key | | `SIMPLEPAY_MERCHANT_ID_EUR` | for EUR | EUR merchant ID | | `SIMPLEPAY_MERCHANT_KEY_EUR` | for EUR | EUR secret key | | `SIMPLEPAY_MERCHANT_ID_USD` | for USD | USD merchant ID | | `SIMPLEPAY_MERCHANT_KEY_USD` | for USD | USD secret key | | `SIMPLEPAY_PRODUCTION` | no | Exactly `true` calls the live API; anything else uses the sandbox. | | `SIMPLEPAY_REDIRECT_URL` | in production | Return URL. Must be absolute `https` in production. Sandbox falls back to `http://url.to.redirect`. | | `SIMPLEPAY_LOGGER` | no | `true` logs debug output to the console. Never logs keys or email addresses. | ## API URLs | Environment | Base URL | |---|---| | Sandbox | `https://sandbox.simplepay.hu/payment/v2` | | Production | `https://secure.simplepay.hu/payment/v2` | Endpoints the SDK calls: `/start`, `/dorecurring`, `/cardcancel`, `/dogooglepay`, `/startapplepay`, `/doapplepay`. Details: [Configuration](../guide/configuration). --- --- url: https://simplepay.webmania.cc/en/guide/getting-started.md description: >- SimplePay Node.js integration step by step: install with npm, yarn or pnpm, set up merchant keys, run your first sandbox payment with simplepay-js-sdk. --- # Getting started `simplepay-js-sdk` is a small TypeScript package with no runtime dependencies. It starts SimplePay payments from a Node.js app and verifies the back-URL redirect and the IPN notification. ::: warning Unofficial SDK This package is a community project, not a SimplePay Zrt. product. SimplePay's rules and API behaviour are described in the [official documentation](https://docs.simplepay.hu/). ::: ## Requirements * Node.js 20 or newer (the package uses the built-in `fetch` and `AbortSignal.timeout`) * A SimplePay merchant account. A sandbox account is enough for testing. * An ESM project (`import`). The package ships as an ES module only. ## 1. Install ::: code-group ```bash [npm] npm install simplepay-js-sdk ``` ```bash [yarn] yarn add simplepay-js-sdk ``` ```bash [pnpm] pnpm add simplepay-js-sdk ``` ::: ## 2. Set up your keys In the SimplePay merchant admin each account (one per currency) has a **merchant ID** and a **secret key**. The SDK reads them from environment variables named after the currency: ```bash [.env] SIMPLEPAY_MERCHANT_ID_HUF=P123456 SIMPLEPAY_MERCHANT_KEY_HUF=your-secret-key SIMPLEPAY_REDIRECT_URL=https://example.com/payment/back # SIMPLEPAY_PRODUCTION=true # live only! ``` Until `SIMPLEPAY_PRODUCTION` is `true`, every call goes to the sandbox (`https://sandbox.simplepay.hu/payment/v2`). All variables: [Configuration](./configuration). ::: danger Keep the secret key on the server Anyone with a `SIMPLEPAY_MERCHANT_KEY_*` value can send signed requests in your name. Keep it out of the browser, git and logs. ::: ## 3. First sandbox payment ```ts import { startPayment } from 'simplepay-js-sdk' const response = await startPayment({ orderRef: `order-${Date.now()}`, // unique order reference total: 1212, customerEmail: 'customer@example.com', invoice: { name: 'Test Customer', country: 'HU', state: 'Budapest', city: 'Budapest', zip: '1111', address: 'Fő utca 1.', }, }) console.log(response.paymentUrl) ``` Open `paymentUrl` and pay with a [sandbox test card](./testing), for example `4908 3660 9990 0425`, expiry `12/28`, CVC `123`. ## 4. The three endpoints A complete SimplePay integration needs three server endpoints: | Endpoint | What it does | Guide | |---|---|---| | Start payment | `startPayment()`, then redirect to `paymentUrl` | [One-time payment](./one-time-payment) | | Back URL | `getPaymentResponse(r, s)` when the customer returns | [Back URL](./back-url) | | IPN | `handleIpnRequest()` for SimplePay's server-to-server notification | [IPN](./ipn) | Mark the order as paid **from the IPN**, not from the back URL: the customer may close the browser before returning. ## Next * [Framework recipes](../recipes/nuxt): Nuxt / Nitro, Express, Next.js * [API reference](../reference/api) * [Go-live checklist](./go-live) --- --- url: https://simplepay.webmania.cc/en/guide/google-pay.md description: >- A Google Pay button on your own page with SimplePay: renderGooglePayButton in the browser, startGooglePay on the server, 3DS (3004) handling, Google Pay & Wallet Console setup. --- # Google Pay With merchant-hosted Google Pay the customer never leaves for SimplePay's payment page: the Google Pay button is on your page, and the payment goes through SimplePay's `dogooglepay` endpoint. Two parts: * **browser**: `renderGooglePayButton` from `simplepay-js-sdk/google-pay` * **server**: `startGooglePay` from `simplepay-js-sdk` Fulfil the order from the [IPN](./ipn) here too. ## Setup 1. Create a merchant profile in the [Google Pay & Wallet Console](https://pay.google.com/business/console) and get your checkout domain approved. 2. Send the Google merchant ID to SimplePay. 3. Use your **SimplePay** merchant ID as `gatewayMerchantId`. 4. In the sandbox use Google Pay's `TEST` environment. Google Pay does not support the `HUF_SZEP` currency. ## Browser: the button ```ts import { renderGooglePayButton } from 'simplepay-js-sdk/google-pay' await renderGooglePayButton({ container: '#google-pay', // CSS selector or HTMLElement merchantId: 'GOOGLE_MERCHANT_ID', merchantName: 'Shop Ltd.', environment: 'TEST', // TEST | PRODUCTION gatewayMerchantId: 'SIMPLEPAY_MERCHANT_ID', authorizationEndpoint: '/api/google-pay', currency: 'HUF', total: '1212', // shown in the Google Pay sheet orderRef: 'order-12', countryCode: 'HU', // optional, default HU allowedCardNetworks: ['VISA', 'MASTERCARD'], // optional, default VISA, MASTERCARD, AMEX onResult: (result) => { /* successful response from your server */ }, onError: (error) => { /* error */ }, }) ``` What it does: 1. Loads `https://pay.google.com/gp/p/js/pay.js` (unless already loaded). 2. Asks Google Pay (`isReadyToPay`) whether the browser can pay. If not, it **renders no button** and returns without an error. 3. On click it opens the Google Pay sheet, then `POST`s `{ googlePayToken, orderRef }` to `authorizationEndpoint`. `googlePayToken` is already Base64. 4. `onResult` receives your server's response. If it contains error code `3004` and a `redirectUrl`, the button sends the customer to the 3DS page (`https` only). Without `onError`, errors are thrown. ## Server: the charge ```ts import { startGooglePay } from 'simplepay-js-sdk' // POST /api/google-pay body: { googlePayToken, orderRef } const order = await loadOrder(orderRef) // read the amount on the server! const response = await startGooglePay({ orderRef: order.orderRef, total: order.total, currency: 'HUF', customerEmail: order.email, language: 'EN', googlePayToken, // unchanged invoice: order.invoice, // optional }, { redirectUrl: 'https://example.com/payment/back', // the customer returns here after 3DS }) return response // return it to the browser ``` ::: warning The server decides the amount SimplePay charges the `total` your server passes to `startGooglePay`. The button's `total` is only what the Google Pay sheet shows. They should match, but always compute from the order on the server. ::: ### 3DS When the card issuer asks for strong customer authentication, SimplePay returns error code `3004` with a `redirectUrl`. `startGooglePay` then **does not throw**; it returns the response and the button redirects. After 3DS the customer comes back to `redirectUrl` with `r` and `s`, which [`getPaymentResponse`](./back-url) verifies. Without 3DS the customer stays on the page. ### Errors `startGooglePay` throws when: * the token is missing: `Missing Google Pay token` * the currency is `HUF_SZEP`: `Google Pay does not support HUF_SZEP` * in production the return URL is not `https` * the response signature is wrong or missing * SimplePay returns any error code other than `3004` with `redirectUrl`, or `3004` without `redirectUrl`: `SimplePay API error: …` --- --- url: https://simplepay.webmania.cc/en/ai/llms.md description: >- simplepay-js-sdk documentation for AI agents and LLMs: llms.txt, llms-full.txt, Markdown per page and Context7. --- # llms.txt and Context7 The docs are also available in machine-readable form, so AI assistants and coding agents use the real API instead of inventing functions. | File | Contents | |---|---| | [`/llms.txt`](https://simplepay.webmania.cc/llms.txt) | List of pages with short descriptions ([llmstxt.org](https://llmstxt.org/) format) | | [`/llms-full.txt`](https://simplepay.webmania.cc/llms-full.txt) | The full documentation in one Markdown file | | `.md` | Raw Markdown of every page, for example [`/en/guide/ipn.md`](https://simplepay.webmania.cc/en/guide/ipn.md) | `llms.txt` and `llms-full.txt` are built from the English pages, so agents don't get everything twice. The Hungarian pages have Markdown versions too. Each page has a **Copy as Markdown** button at the top for pasting the page into a chat. ## Context7 The docs are also on [Context7](https://context7.com/rrd108/simplepay-js-sdk). With the Context7 MCP server an agent can fetch them like this: ``` use context7 simplepay-js-sdk ``` ## Agent Skill An installable instruction set for agents: [Agent Skill](./agent-skill). --- --- url: https://simplepay.webmania.cc/en/guide/one-time-payment.md description: >- Start a SimplePay one-time card or wire payment from Node.js with startPayment. Parameters, SZÉP card, currency, language, invoice, items, delivery, timeout, response and error handling. --- # One-time payment ## The flow 1. The customer clicks “Pay” on your site. 2. Your server calls `startPayment()`. The SDK sends a signed request to SimplePay's `/start` endpoint. 3. You redirect the customer to the returned `paymentUrl`. 4. The customer pays on SimplePay's page. 5. SimplePay redirects the customer to your [back URL](./back-url) and sends your server a separate [IPN](./ipn). ## Start a payment ```ts import { startPayment } from 'simplepay-js-sdk' const response = await startPayment({ orderRef: 'order-12', // required, unique total: 1212, // required, number or string customerEmail: 'customer@example.com', // required currency: 'HUF', // optional: HUF | HUF_SZEP | EUR | USD, default HUF language: 'EN', // optional, default HU method: 'CARD', // optional: CARD | WIRE, default CARD invoice: { // optional name: 'Test Customer', country: 'HU', state: 'Budapest', city: 'Budapest', zip: '1111', address: 'Fő utca 1.', address2: '2nd floor', // optional phone: '+36301234567', // optional }, }, { redirectUrl: 'https://example.com/payment/back', // optional, overrides SIMPLEPAY_REDIRECT_URL }) // redirect return Response.redirect(response.paymentUrl, 303) ``` ### Parameters | Field | Type | Required | Description | |---|---|---|---| | `orderRef` | `string` | yes | Your order reference. Must be unique within the merchant account. | | `total` | `number \| string` | yes | Amount to charge. The SDK converts it to a string. | | `customerEmail` | `string` | yes | Customer's email address. | | `currency` | `Currency` | no | `HUF`, `HUF_SZEP`, `EUR` or `USD`. Default `HUF`. | | `language` | `Language` | no | Payment page language. Default `HU`. | | `method` | `'CARD' \| 'WIRE'` | no | Card or wire transfer. Default `CARD`. | | `invoice` | object | no | Billing data, see [Types](../reference/types#paymentdata). | | `items` | `PaymentItem[]` | no | Line items: `ref`, `title`, `desc`, `amount` (quantity), `price` (unit price), `tax` (VAT %). When sent, SimplePay **ignores `total`** and computes the amount from the items. | | `shippingCost` | `number` | no | Shipping cost. | | `discount` | `number` | no | Discount amount. | | `delivery` | object | no | Delivery address (`name`, `company`, `country`, `state`, `city`, `zip`, `address`, `address2`, `phone`). | | `customer` | `string` | no | Customer name, if it differs from `invoice.name`. | | `extra` | object | no | Your own extra data. | | `maySelectEmail` | `boolean` | no | The customer may change the email address on the payment page. | | `maySelectInvoice` | `boolean` | no | The customer may enter the billing data on the payment page. | | `maySelectDelivery` | `string[]` | no | Country codes the customer may pick a delivery address in on the payment page, e.g. `['HU', 'AT']`. | | `timeout` | `Date \| string` | no | Payment deadline (`Date` or ISO 8601). Default: now + 30 minutes. | | `threeDSReqAuthMethod` | `'01' \| '02' \| '05'` | no | How you identified the customer: `01` guest, `02` registered with you, `05` registered with a third-party identifier. For one-time payments it is sent only when set. | `invoice` fields: `name`, `company`, `fiscalCode` (tax number), `country`, `state`, `city`, `zip`, `address`, `address2`, `phone`. Set at least one of `name` or `company`. Second argument (`StartPaymentConfig`, optional): | Field | Type | Description | |---|---|---| | `redirectUrl` | `string` | Return URL for this payment. Must be absolute `https` in production. | | `urls` | `{ success, fail, cancel, timeout }` | A separate return URL per outcome. When given, it is sent instead of `url`, and neither `redirectUrl` nor `SIMPLEPAY_REDIRECT_URL` is needed. In production all four must be absolute `https`. | ```ts await startPayment(paymentData, { urls: { success: 'https://example.com/payment/success', fail: 'https://example.com/payment/fail', cancel: 'https://example.com/payment/cancel', timeout: 'https://example.com/payment/timeout', }, }) ``` The customer arrives at each of them with the same `r` and `s` parameters, which [`getPaymentResponse`](./back-url) verifies. Supported languages: `AR`, `BG`, `CS`, `DE`, `EN`, `ES`, `FR`, `IT`, `HR`, `HU`, `PL`, `RO`, `RU`, `SK`, `TR`, `ZH`. ### Filled in by the SDK * `salt`: 16 random bytes, hex * `merchant`: the currency's `SIMPLEPAY_MERCHANT_ID_*` * `timeout`: the given `timeout`, or now + 30 minutes, ISO 8601 * `url`: `redirectUrl` or `SIMPLEPAY_REDIRECT_URL` (when there is no `urls`) * `sdkVersion`, `methods` * `Signature` HTTP header: HMAC-SHA384, Base64, over the request body ## The response `startPayment` resolves to a `SimplePayResponse`: ```ts { salt: '...', merchant: 'P123456', orderRef: 'order-12', currency: 'HUF', transactionId: '504233881', timeout: '2026-12-02T10:30:00+00:00', total: '1212', paymentUrl: 'https://sandbox.simplepay.hu/pay/pay/pspHU/...', } ``` Store `transactionId` with the order: SimplePay's admin and the IPN identify the payment by it. ## SZÉP card ```ts await startPayment({ orderRef: 'order-13', total: 5000, currency: 'HUF_SZEP', customerEmail: 'customer@example.com', }) ``` Needs `SIMPLEPAY_MERCHANT_ID_HUF_SZEP` and `SIMPLEPAY_MERCHANT_KEY_HUF_SZEP`. The request currency is `HUF`. ## Error handling `startPayment` throws when: * the currency has no keys: `Missing SimplePay configuration for HUF` * the currency is unknown: `Unsupported currency: XYZ` * in production the return URL is missing or not `https` * SimplePay answers with a non-2xx status: `SimplePay API error: 500` * the response signature is missing or wrong: `Missing response signature`, `Invalid response signature` * SimplePay returns error codes: `SimplePay API error: 5321` (several codes are comma-separated) * no answer within 30 seconds (`TimeoutError`) ```ts try { const { paymentUrl } = await startPayment(data) return redirect(paymentUrl) } catch (error) { console.error('SimplePay payment start failed', error) // show an error page; the order stays unpaid } ``` What the codes mean: [Error codes](../reference/errors). ::: tip Always compute the amount on the server Read `total` from the order on the server, not from data the browser sent. ::: ## Next * [Handle the back URL](./back-url) * [Receive the IPN](./ipn) --- --- url: https://simplepay.webmania.cc/en/guide/back-url.md description: >- Verify the SimplePay back URL r and s parameters in Node.js with getPaymentResponse. Handle the SUCCESS, FAIL, TIMEOUT and CANCEL events. --- # Back URL handling After the payment (or when the customer cancels, or time runs out) SimplePay redirects the customer to `redirectUrl` / `SIMPLEPAY_REDIRECT_URL` (or the matching `urls` entry) with two query parameters: ``` https://example.com/payment/back?r=eyJyIjowLCJ0Ijo1MDQy...&s=El%2Bq... ``` * `r`: Base64-encoded JSON with the result * `s`: the signature of that JSON ## Verify it ```ts import { getPaymentResponse } from 'simplepay-js-sdk' const url = new URL(request.url) const r = url.searchParams.get('r') ?? '' const s = url.searchParams.get('s') ?? '' const result = getPaymentResponse(r, s) ``` `getPaymentResponse`: 1. decodes `r`, 2. finds the `SIMPLEPAY_MERCHANT_ID_*` variable holding its merchant ID, and that currency's key, 3. checks the `s` signature (timing-safe comparison), 4. returns the result. It is synchronous and makes no network call. ## The result ```ts { responseCode: 0, transactionId: '504233881', event: 'SUCCESS', merchantId: 'P123456', orderRef: 'order-12', tokens: undefined, // card registration tokens for recurring payments } ``` | `event` | Meaning | What to show | |---|---|---| | `SUCCESS` | Successful payment (card authorised) | “Thank you, your payment is being processed / succeeded” | | `FAIL` | Failed payment | Error message, retry option, the `transactionId` | | `TIMEOUT` | Payment time ran out | “Time ran out”, start a new payment | | `CANCEL` | The customer cancelled | “You cancelled the payment” | `event` values are **uppercase**. ::: warning The IPN closes the order The back URL is feedback for the customer only. The customer may close the browser before returning, or open an old back URL by hand. Set the order to paid from the [IPN](./ipn). If the IPN has not arrived yet, say on the `SUCCESS` page that the payment is being processed. ::: ::: tip On failed payments SimplePay expects you to show the customer the SimplePay transaction ID on a failed payment and tell them they can ask their bank. Exact wording: [SimplePay documentation](https://docs.simplepay.hu/). ::: ## Errors `getPaymentResponse` throws when: * `r` is not valid Base64 / JSON (`SyntaxError`) * the merchant ID is in no `SIMPLEPAY_MERCHANT_ID_*` variable: `Merchant id not found in the environment: P123456` * the currency has no key: `Missing SimplePay configuration for HUF` * the signature is wrong: `Invalid response signature` Answer these with a 400 or a generic error page, and leave the order alone. ## Space instead of `+` If your framework decodes the query string with `application/x-www-form-urlencoded` rules, the `+` signs in the `s` signature become spaces. `getPaymentResponse` handles this: it turns every space back into `+` before checking. ## Recurring payments For card registration (`startRecurringPayment`) the result's `tokens` field may hold tokens if SimplePay sends them. You can also save the tokens from the response of the payment start, see [Recurring payments](./recurring-payments). --- --- url: https://simplepay.webmania.cc/en/reference/errors.md description: >- What SimplePay error codes mean and how to fix them (5100 invalid signature, 5321 format error, 5013 transaction exists, 3004 3DS, 2063 declined), plus the simplepay-js-sdk error messages. --- # Error codes You will meet two kinds of errors: 1. **SDK error messages**: thrown by the SDK before or after it calls SimplePay. 2. **SimplePay error codes**: in the `errorCodes` array of SimplePay's response. The SDK turns them into a `SimplePay API error: ` exception (several codes comma-separated, for example `SimplePay API error: 5100,5302`). ```ts try { await startPayment(data) } catch (error) { const match = /SimplePay API error: ([\d,]+)/.exec((error as Error).message) const codes = match ? match[1].split(',') : [] if (codes.includes('5013')) { // this orderRef already exists } } ``` ## SDK error messages | Message | Cause | Fix | |---|---|---| | `Missing SimplePay configuration for HUF` | The currency's `SIMPLEPAY_MERCHANT_ID_*` or `SIMPLEPAY_MERCHANT_KEY_*` is not set | Set both ([Configuration](../guide/configuration)) | | `Unsupported currency: XYZ` | `currency` is not `HUF`, `HUF_SZEP`, `EUR` or `USD` | Use a supported currency | | `Missing merchant key` | An empty secret key was used for signing | Check the key variable; for the IPN, the `merchantKey` argument | | `SimplePay return url must be absolute https in production` | In production the return URL is missing or not `https` | Set `SIMPLEPAY_REDIRECT_URL` or `redirectUrl` to `https://…` | | `SimplePay return urls must be absolute https in production` | In production an `urls` entry is missing or not `https` | Make all four `urls` entries `https://…` | | `SimplePay API error: 401` (or another HTTP status) | SimplePay answered with a non-2xx status | Check the keys and the sandbox/production setting | | `Missing response signature` | SimplePay's response has no `Signature` header | Often a wrong endpoint or a proxy; turn on `SIMPLEPAY_LOGGER` | | `Invalid response signature` | The response or back-URL signature doesn't match | Wrong key (sandbox/live mix-up, another currency), or tampered `r`/`s` | | `Merchant id not found in the environment: …` | The back URL's merchant ID is in no `SIMPLEPAY_MERCHANT_ID_*` variable | Set that account's merchant ID | | `Invalid IPN request signature` | The IPN signature doesn't match | Read the raw body, pass the right key ([IPN](../guide/ipn#common-mistakes)) | | `Invalid IPN request body` | The IPN body is not a JSON object | Don't transform the body | | `Missing Google Pay token` | Empty `googlePayToken` | Pass the token from the browser | | `Google Pay does not support HUF_SZEP` / `Apple Pay does not support HUF_SZEP` | Google/Apple Pay started with the SZÉP currency | Use another currency | | `Apple Pay domain must be the registered FQDN` | `domain` is not a valid domain name | Pass the registered FQDN, with no protocol or path | | `Missing Apple Pay session` | The `startapplepay` response has no `applePaySession` | Check the domain registration in the SimplePay admin | | `Invalid Apple Pay transaction id` | `transactionId` is not a positive integer | Pass the ID from the `startApplePay` response | | `Missing Apple Pay token` | The token is not valid Base64 | Pass the browser's token unchanged | | `Apple Pay authorization failed` | `applePayStatus` is not `STATUS_SUCCESS` | The customer retries, or uses another card | | `TimeoutError` | SimplePay did not answer within 30 seconds | Retry later | ::: info 3004 with Google Pay Google Pay `3004` with a `redirectUrl` is **not** an error: `startGooglePay` returns the response and the button redirects to the 3DS page. ::: ## Common SimplePay error codes Source: [SimplePay – error codes](https://docs.simplepay.hu/hu/developer-tools/api/error-codes) (Hungarian). The descriptions below are short English summaries; the full official list is on that page. ### Signature and format | Code | Meaning | Typical cause with the SDK | |---|---|---| | `5100` | Invalid signature | Wrong key (sandbox key on live or the other way round, another currency's key) | | `5302`, `5303` | Invalid signature on the incoming request | Same as above | | `5321` | Format error / invalid JSON | A badly formatted field in the request. For dates (such as `recurring.until`) use `toISO8601DateString`. | ### Merchant | Code | Meaning | What to do | |---|---|---| | `2006` | Merchant not found | Check the merchant ID | | `5010` | Merchant account not found | Sandbox ID on the live API or the other way round | | `5201` | Merchant ID missing | Set `SIMPLEPAY_MERCHANT_ID_*` | ### Order | Code | Meaning | What to do | |---|---|---| | `5013` | Transaction already exists | Every payment attempt needs a new, unique `orderRef` | | `5101`, `5213` | Order reference missing | Pass `orderRef` | | `5102` | Amount missing | Pass `total` | | `5065` | Invalid amount | Check the `total` value | | `5066` | Invalid currency | Use the account's currency | | `5011` | Transaction not found | Check the `transactionId` (for example with `cancelCard`) | | `5333` | Transaction ID missing | | | `5304` | Call failed because of a timeout | Retry | ### Card and 3DS These concern the customer's card. They show up as a `FAIL` event on the back URL, or as an exception for token charges. | Code | Meaning | What to tell the customer | |---|---|---| | `2063`, `2066`, `2004` | Declined by the issuing bank | Ask your bank, or pay with another card | | `2013` | Balance or daily limit | Check your balance and limits | | `2070` | Card type not enabled or not recognised | Use another card | | `2071` | Wrong card number | Check the card number | | `2072` | Wrong expiry date | Check the expiry date | | `2073` | Wrong CVC | Check the code on the back | | `3004` | The bank asks for strong customer authentication (3DS) | Retry and follow your bank's authentication steps | ### Recurring payments | Code | Meaning | What to do | |---|---|---| | `5044` | Recurring payments not enabled | Ask SimplePay to enable them for the account | | `5040` | Stored card not found | The card was removed; a new registration is needed | | `5041` | Stored card expired | A new card registration is needed | | `5081` | Recurring token not found | Wrong or already deleted token | ### General | Code | Meaning | |---|---| | `0` | Success | | `999`, `5000` | General error – retry; if it persists, contact SimplePay support | --- --- url: https://simplepay.webmania.cc/en/recipes/express.md description: >- SimplePay integration in an Express app: start a payment, handle the back URL, receive the IPN with the express.text() raw body. Full example code. --- # Express The package ships as an ES module only, so the project needs `"type": "module"` (or `.mjs` files). ## Full example ```ts [server.ts] import express from 'express' import { startPayment, getPaymentResponse, handleIpnRequest } from 'simplepay-js-sdk' const app = express() // Start a payment – the JSON parser is fine here app.post('/api/simplepay/start', express.json(), async (req, res) => { const order = await getOrder(req.body.orderId) try { const { paymentUrl } = await startPayment({ orderRef: order.ref, total: order.total, customerEmail: order.email, }) res.json({ paymentUrl }) } catch (error) { console.error('SimplePay start', error) res.status(502).json({ error: 'Could not start the payment' }) } }) // Back URL (SIMPLEPAY_REDIRECT_URL = https://example.com/payment/back) app.get('/payment/back', (req, res) => { try { const result = getPaymentResponse(String(req.query.r ?? ''), String(req.query.s ?? '')) res.render('payment-result', result) // event: SUCCESS | FAIL | TIMEOUT | CANCEL } catch { res.status(400).send('Invalid redirect') } }) // IPN – needs RAW text, NOT express.json() app.post('/api/simplepay/ipn', express.text({ type: 'application/json' }), async (req, res) => { const ipnBody = typeof req.body === 'string' ? req.body : '' const incomingSignature = req.get('Signature') ?? '' let result try { result = handleIpnRequest(ipnBody, incomingSignature, process.env.SIMPLEPAY_MERCHANT_KEY_HUF!) } catch (error) { console.error('SimplePay IPN', error) res.status(400).send('Invalid signature') return } const ipn = JSON.parse(ipnBody) as { orderRef: string, transactionId: number, status: string } if (ipn.status === 'FINISHED') { await markOrderPaid(ipn.orderRef, ipn.transactionId) // make it idempotent } res .status(200) .set('Signature', result.signature) .type('application/json') .send(result.responseBody) // as a string, unchanged }) app.listen(3000) ``` ## IPN ::: danger A global `app.use(express.json())` If the app has a global `app.use(express.json())` at the top, it **consumes** the IPN body before `express.text()` sees it, and `req.body` is already an object. Either register the IPN route **before** the global parser, or keep it out of the parser: ```ts app.post('/api/simplepay/ipn', express.text({ type: 'application/json' }), ipnHandler) app.use(express.json()) // now only runs for the other routes ``` ::: * `res.json(result.responseBody)` is **wrong**: it wraps the text in quotes. * `res.send(JSON.parse(...))` is **wrong**: it serializes again. * Correct: `res.type('application/json').send(result.responseBody)`. Several currencies: [IPN – Multiple currencies](../guide/ipn#multiple-currencies). --- --- url: https://simplepay.webmania.cc/en/guide/go-live.md description: >- What to check before switching your SimplePay Node.js integration to production: keys, SIMPLEPAY_PRODUCTION, https return URL, IPN URL, logging, Google Pay and Apple Pay. --- # Go-live checklist ## Environment * \[ ] `SIMPLEPAY_PRODUCTION=true` (exactly this text) * \[ ] The **live** `SIMPLEPAY_MERCHANT_ID_*` and `SIMPLEPAY_MERCHANT_KEY_*` values are set, not the sandbox ones * \[ ] `SIMPLEPAY_REDIRECT_URL` is an absolute `https` URL (the SDK throws in production if not) * \[ ] Every per-payment `redirectUrl` and `urls` entry is `https` too * \[ ] `SIMPLEPAY_LOGGER` is off * \[ ] The secret keys are not in the repo, the client bundle or the logs ## IPN * \[ ] The IPN URL is set in the live merchant admin * \[ ] The IPN endpoint reads the raw body and sends `responseBody` back unchanged ([IPN](./ipn)) * \[ ] A bad signature does not change the order * \[ ] Order fulfilment is idempotent * \[ ] The IPN route is not behind login, CSRF tokens or a WAF rule that blocks SimplePay ## Payment flow * \[ ] The server computes the amount from the order * \[ ] `orderRef` is unique (a retry uses a new `orderRef`, or restarts according to SimplePay's rules) * \[ ] The back-URL page handles `SUCCESS`, `FAIL`, `TIMEOUT` and `CANCEL` * \[ ] On a failed payment the customer sees the SimplePay transaction ID * \[ ] The IPN sets the order status, not the back URL ## SimplePay requirements Before going live SimplePay reviews your site (for example logo, data transfer notice, terms). The list is in the [SimplePay documentation](https://docs.simplepay.hu/) and your contract; the SDK doesn't cover these. ## Recurring payments * \[ ] SimplePay enabled recurring payments on the live account * \[ ] Tokens are stored securely, per customer * \[ ] There is a card removal feature (`cancelCard`) that also deletes the tokens ## Google Pay * \[ ] `environment: 'PRODUCTION'` * \[ ] The domain is approved in the Google Pay & Wallet Console and SimplePay has your Google merchant ID * \[ ] `gatewayMerchantId` is the live SimplePay merchant ID ## Apple Pay * \[ ] The domain is registered on the Apple Pay tab of the live SimplePay admin * \[ ] The association file is served at `https:///.well-known/apple-developer-merchantid-domain-association` * \[ ] The server sends its own registered domain to `startApplePay` * \[ ] Before `doApplePay` you check that `transactionId` belongs to this order ## After the first live payment * \[ ] A small real payment goes through, the IPN arrives, the order is paid * \[ ] The transaction shows as completed in the SimplePay admin --- --- url: https://simplepay.webmania.cc/en/guide/ipn.md description: >- SimplePay IPN endpoint in Node.js with handleIpnRequest: raw body, Signature header, receiveDate, signing the response, common mistakes (5100 invalid signature), multiple currencies, idempotency. --- # IPN and signature verification The **IPN** (Instant Payment Notification) is SimplePay's server-to-server notification of a payment's final result. It is the only reliable signal that an order is paid. This is the part people get wrong most often, so this page goes through it in detail. ## How it works 1. When a payment completes, SimplePay sends a `POST` to your IPN URL (set in the SimplePay merchant admin). 2. The body is compact JSON. The `Signature` header holds an HMAC-SHA384 of the body, Base64-encoded, made with the account's secret key. 3. You must verify the signature, add a `receiveDate` field to the JSON, sign the new JSON, and send it back with HTTP 200 and the new signature in the `Signature` header. 4. If your answer is wrong, SimplePay sends the IPN again and the transaction does not close properly in the merchant admin. `handleIpnRequest` does step 3. ## An incoming IPN ```http POST /api/simplepay/ipn HTTP/1.1 Content-Type: application/json Signature: 0mI0u6CmGhPsQ0dU3vQh2iX5... {"salt":"223G0O8HqBUlXjZ0Ix9u4V4hnkJwPgDx","orderRef":"order-12","method":"CARD","merchant":"P123456","finishDate":"2026-12-02T10:12:43+01:00","paymentDate":"2026-12-02T10:12:16+01:00","transactionId":504233881,"status":"FINISHED"} ``` For a recurring card registration the JSON also contains `cardMask` and `expiry`. ## The complete endpoint Framework-agnostic example with web-standard `Request` / `Response` (Next.js route handlers, Nitro, Bun, Deno, Hono, Cloudflare Workers): ```ts import { handleIpnRequest } from 'simplepay-js-sdk' export async function POST(request: Request) { // 1. RAW text – not request.json()! const ipnBody = await request.text() // 2. the signature comes in a header const incomingSignature = request.headers.get('Signature') ?? '' let result try { // 3. verify + receiveDate + new signature result = handleIpnRequest(ipnBody, incomingSignature, process.env.SIMPLEPAY_MERCHANT_KEY_HUF!) } catch (error) { // bad signature or not a JSON object: don't touch the order console.error('Invalid SimplePay IPN', error) return new Response('Invalid signature', { status: 400 }) } // 4. close the order – only after a valid signature const ipn = JSON.parse(ipnBody) as { orderRef: string, transactionId: number, status: string } if (ipn.status === 'FINISHED') { await markOrderPaid(ipn.orderRef, ipn.transactionId) // your function, make it idempotent } // 5. send the response back UNCHANGED return new Response(result.responseBody, { status: 200, headers: { 'Content-Type': 'application/json', 'Signature': result.signature, }, }) } ``` Framework versions: [Nuxt / Nitro](../recipes/nuxt#ipn), [Express](../recipes/express#ipn), [Next.js](../recipes/nextjs#ipn). ## What `handleIpnRequest` does ```ts handleIpnRequest(ipnBody: string, incomingSignature: string, merchantKey: string) : { responseBody: string, signature: string } ``` 1. `checkSignature(ipnBody, incomingSignature, merchantKey)` – if wrong, throws `Invalid IPN request signature`. 2. Checks that the body is a JSON object – if not, throws `Invalid IPN request body`. 3. Inserts `receiveDate` **as text** before the last `}` of the original body. It does not parse and re-stringify, so field order, number vs string types and formatting stay byte-identical. 4. Signs the resulting text (HMAC-SHA384, Base64). The result, for example: ```json {"salt":"223G0O8HqBUlXjZ0Ix9u4V4hnkJwPgDx","orderRef":"order-12","method":"CARD","merchant":"P123456","finishDate":"2026-12-02T10:12:43+01:00","paymentDate":"2026-12-02T10:12:16+01:00","transactionId":504233881,"status":"FINISHED","receiveDate":"2026-12-02T09:12:44+00:00"} ``` ## Common mistakes ### 1. Reading the body as JSON ```ts const body = await request.json() // ❌ const ipnBody = JSON.stringify(body) // ❌ no longer the same text ``` The signature covers the **exact bytes**. If the framework parses the body and you stringify it again, whitespace, `\/` escapes, number formatting or field order may differ, and the signature will not match. Always read the raw text: | Framework | Correct | |---|---| | Web `Request` (Next.js, Nitro web handler, Hono, Bun) | `await request.text()` | | Nuxt / Nitro (h3) | `await readRawBody(event, 'utf8')` | | Express | `express.text({ type: 'application/json' })` on the IPN route, then `req.body` | | Fastify | `addContentTypeParser('application/json', { parseAs: 'string' }, …)` for the IPN route | ### 2. Changing the response ```ts return Response.json(JSON.parse(responseBody)) // ❌ res.json(responseBody) // ❌ wraps it in quotes ``` `responseBody` is finished, signed text. Send it exactly as is: don't format it, parse it or add to it. In Express: `res.type('application/json').send(responseBody)`. ### 3. Putting the signature in the body The response signature goes in the **`Signature` HTTP header**, not in the JSON. ### 4. Wrong key Use the secret key of the merchant account the IPN belongs to. With several currencies, pick it from the JSON's `merchant` field (see below). For SZÉP cards use `SIMPLEPAY_MERCHANT_KEY_HUF_SZEP`. ### 5. Missing header `request.headers.get('Signature')` returns `null` when the header is missing. In TypeScript pass a string with `?? ''`: `checkSignature` returns `false` for an empty signature, and `handleIpnRequest` throws. ### 6. Processing the order twice SimplePay may send the same IPN more than once (for example if your answer was slow). Make `markOrderPaid` **idempotent**: if the order is already paid, don't send the confirmation email again or reserve stock again. ### 7. A proxy that rewrites the body Some reverse proxies, WAFs or body-parser middleware compress, re-encode or reshape JSON. If every signature fails in the sandbox, log the raw body and header and compare with `generateSignature(ipnBody, key)`. ## Multiple currencies `handleIpnRequest` doesn't know which currency an IPN belongs to – you pass the key. The body's `merchant` field tells you which account sent it. Use the parsed object **only for reading**; `handleIpnRequest` gets the raw text: ```ts const CURRENCIES = ['HUF', 'HUF_SZEP', 'EUR', 'USD'] as const const merchantKeyFor = (merchantId: string) => { const currency = CURRENCIES.find((c) => process.env[`SIMPLEPAY_MERCHANT_ID_${c}`] === merchantId) const key = currency && process.env[`SIMPLEPAY_MERCHANT_KEY_${currency}`] if (!key) { throw new Error(`Unknown SimplePay merchant: ${merchantId}`) } return key } const ipnBody = await request.text() const { merchant } = JSON.parse(ipnBody) as { merchant: string } const { responseBody, signature } = handleIpnRequest( ipnBody, request.headers.get('Signature') ?? '', merchantKeyFor(merchant), ) ``` ## IPN `status` values | `status` | Meaning | |---|---| | `FINISHED` | Successful, completed payment. Fulfil the order now. | | `AUTHORIZED` | Authorised but not yet captured (two-step payments) | | `NOTAUTHORIZED` | Authorisation failed | | `CANCELLED` | Cancelled | | `TIMEOUT` | Timed out | | `REVERSED` | Reversed | ## Doing it by hand Without `handleIpnRequest`, the steps with the exported helpers: ```ts import { checkSignature, generateSignature, toISO8601DateString } from 'simplepay-js-sdk' if (!checkSignature(ipnBody, incomingSignature, merchantKey)) { throw new Error('Invalid signature') } // insert receiveDate as text, not with JSON.parse + JSON.stringify const body = ipnBody.trimEnd() const responseBody = `${body.slice(0, -1)},"receiveDate":"${toISO8601DateString(new Date())}"}` const signature = generateSignature(responseBody, merchantKey) ``` ## Testing locally The SimplePay sandbox can only send IPNs to a public URL. For local development use a tunnel (for example `cloudflared tunnel` or `ngrok`) and set the resulting `https` address as the IPN URL in the sandbox merchant admin. You can sign your own test request with `generateSignature(body, key)` and send it with `curl` to your local endpoint in the `Signature` header. --- --- url: https://simplepay.webmania.cc/en/recipes/nextjs.md description: >- SimplePay integration with the Next.js App Router: start a payment in a route handler, verify the back URL in a server component, receive the IPN with request.text(). --- # Next.js App Router, route handlers. The SDK uses Node.js `crypto`, so the route handlers must run on the **Node.js runtime** (the default; it does not work on the Edge runtime). ## Environment variables ```bash [.env.local] SIMPLEPAY_MERCHANT_ID_HUF=P123456 SIMPLEPAY_MERCHANT_KEY_HUF=secret-key SIMPLEPAY_REDIRECT_URL=https://example.com/payment/back ``` Don't give them a `NEXT_PUBLIC_` prefix, or they end up in the browser. ## Start a payment ```ts [app/api/simplepay/start/route.ts] import { startPayment } from 'simplepay-js-sdk' export const runtime = 'nodejs' export async function POST(request: Request) { const { orderId } = await request.json() const order = await getOrder(orderId) try { const { paymentUrl } = await startPayment({ orderRef: order.ref, total: order.total, customerEmail: order.email, }) return Response.json({ paymentUrl }) } catch (error) { console.error('SimplePay start', error) return Response.json({ error: 'Could not start the payment' }, { status: 502 }) } } ``` ## Back URL ```tsx [app/payment/back/page.tsx] import { getPaymentResponse } from 'simplepay-js-sdk' export default async function PaymentReturn({ searchParams }: { searchParams: Promise<{ r?: string, s?: string }> }) { const { r = '', s = '' } = await searchParams let result try { result = getPaymentResponse(r, s) } catch { return

Invalid redirect.

} switch (result.event) { case 'SUCCESS': return

Thank you! We are processing your payment. (SimplePay ID: {result.transactionId})

case 'FAIL': return

Payment failed. SimplePay transaction ID: {result.transactionId}.

case 'CANCEL': return

You cancelled the payment.

case 'TIMEOUT': return

The payment timed out.

} } ``` In Next.js 14 `searchParams` is not a Promise yet: use `{ searchParams }: { searchParams: { r?: string, s?: string } }` without `await`. ## IPN ```ts [app/api/simplepay/ipn/route.ts] import { handleIpnRequest } from 'simplepay-js-sdk' export const runtime = 'nodejs' export async function POST(request: Request) { const ipnBody = await request.text() // NOT request.json() const incomingSignature = request.headers.get('Signature') ?? '' let result try { result = handleIpnRequest(ipnBody, incomingSignature, process.env.SIMPLEPAY_MERCHANT_KEY_HUF!) } catch (error) { console.error('SimplePay IPN', error) return new Response('Invalid signature', { status: 400 }) } const ipn = JSON.parse(ipnBody) as { orderRef: string, transactionId: number, status: string } if (ipn.status === 'FINISHED') { await markOrderPaid(ipn.orderRef, ipn.transactionId) // make it idempotent } return new Response(result.responseBody, { status: 200, headers: { 'Content-Type': 'application/json', 'Signature': result.signature }, }) } ``` Don't use `Response.json(...)` for the IPN answer: it would serialize the text again. If you use middleware (for example for login checks), exclude the IPN route from it. Several currencies: [IPN – Multiple currencies](../guide/ipn#multiple-currencies). --- --- url: https://simplepay.webmania.cc/en/recipes/nuxt.md description: >- SimplePay integration in Nuxt 3 / Nuxt 4 with Nitro server routes: start a payment, handle the back URL, receive the IPN with readRawBody. Full example code. --- # Nuxt / Nitro This recipe works with Nuxt 3 and Nuxt 4 using Nitro server routes. The SDK uses Node.js `crypto` and `Buffer`, so it needs a Node.js runtime (the `node-server` preset, or `nodejs_compat` on Cloudflare). The h3 helpers (`defineEventHandler`, `readBody`, `readRawBody`, `getHeader`, `setResponseHeader`, `createError`, `getQuery`) are auto-imported in Nuxt's server directory. ## Environment variables ```bash [.env] SIMPLEPAY_MERCHANT_ID_HUF=P123456 SIMPLEPAY_MERCHANT_KEY_HUF=secret-key SIMPLEPAY_REDIRECT_URL=https://example.com/payment/back ``` The SDK reads `process.env` directly; you don't need `runtimeConfig`. In production set the variables in the server environment (Nuxt only loads `.env` in development). ## Start a payment ```ts [server/api/simplepay/start.post.ts] import { startPayment } from 'simplepay-js-sdk' export default defineEventHandler(async (event) => { const { orderId } = await readBody<{ orderId: string }>(event) const order = await getOrder(orderId) // from your database try { const response = await startPayment({ orderRef: order.ref, total: order.total, customerEmail: order.email, invoice: order.invoice, }) return { paymentUrl: response.paymentUrl } } catch (error) { console.error('SimplePay start', error) throw createError({ statusCode: 502, statusMessage: 'Could not start the payment' }) } }) ``` On the client: ```vue ``` ## Back URL `SIMPLEPAY_REDIRECT_URL` points to a Nuxt page (`/payment/back`). Verification runs on the server because it needs the secret key. ```ts [server/api/simplepay/result.get.ts] import { getPaymentResponse } from 'simplepay-js-sdk' export default defineEventHandler((event) => { const { r, s } = getQuery(event) if (typeof r !== 'string' || typeof s !== 'string') { throw createError({ statusCode: 400 }) } try { const result = getPaymentResponse(r, s) return { event: result.event, orderRef: result.orderRef, transactionId: result.transactionId } } catch { throw createError({ statusCode: 400, statusMessage: 'Invalid redirect' }) } }) ``` ```vue [pages/payment/back.vue] ``` ## IPN The key point: **`readRawBody`**, not `readBody`. `readBody` parses the JSON and the signature won't match. ```ts [server/api/simplepay/ipn.post.ts] import { handleIpnRequest } from 'simplepay-js-sdk' export default defineEventHandler(async (event) => { const ipnBody = (await readRawBody(event, 'utf8')) ?? '' const incomingSignature = getHeader(event, 'signature') ?? '' let result try { result = handleIpnRequest(ipnBody, incomingSignature, process.env.SIMPLEPAY_MERCHANT_KEY_HUF!) } catch (error) { console.error('SimplePay IPN', error) throw createError({ statusCode: 400, statusMessage: 'Invalid signature' }) } const ipn = JSON.parse(ipnBody) as { orderRef: string, transactionId: number, status: string } if (ipn.status === 'FINISHED') { await markOrderPaid(ipn.orderRef, ipn.transactionId) // make it idempotent } setResponseHeader(event, 'Content-Type', 'application/json') setResponseHeader(event, 'Signature', result.signature) return result.responseBody // as a string, unchanged }) ``` IPN URL in the SimplePay admin: `https://example.com/api/simplepay/ipn`. ::: tip Why does `return result.responseBody` work? When an h3 handler returns a string, Nitro sends it unchanged. Don't return an object: Nitro would serialize it again. ::: Choosing the key for several currencies: [IPN – Multiple currencies](../guide/ipn#multiple-currencies). ## Scheduled recurring charges Call `startTokenPayment` from a Nitro scheduled task (experimental, `nitro.experimental.tasks`) or an external cron. See [Recurring payments](../guide/recurring-payments#_3-charging-a-token). --- --- url: https://simplepay.webmania.cc/en/guide/recurring-payments.md description: >- SimplePay recurring payments in Node.js: card registration with startRecurringPayment, storing tokens, charging a token with startTokenPayment, removing a card with cancelCard. --- # Recurring payments (card storage and tokens) With recurring payments the customer registers their card during the first payment. SimplePay then issues **tokens**: each token can be used for one later charge without the customer (MIT – merchant initiated transaction). ::: info Prerequisite Recurring payments must be enabled for your merchant account by SimplePay. Otherwise SimplePay answers with an error code (for example `5044`, see [Error codes](../reference/errors)). ::: ## 1. Card registration `startRecurringPayment` works like [`startPayment`](./one-time-payment), with two extra fields: `customer` and `recurring`. ```ts import { startRecurringPayment, toISO8601DateString } from 'simplepay-js-sdk' const sixMonths = new Date(Date.now() + 182 * 24 * 60 * 60 * 1000) const response = await startRecurringPayment({ orderRef: 'sub-2026-0001', total: 4990, currency: 'HUF', customerEmail: 'customer@example.com', customer: 'Test Customer', // customer's name recurring: { times: 6, // number of tokens = number of later charges until: toISO8601DateString(sixMonths), // tokens are valid until this date maxAmount: 10000, // maximum amount of one charge }, invoice: { name: 'Test Customer', country: 'HU', state: 'Budapest', city: 'Budapest', zip: '1111', address: 'Fő utca 1.' }, }) // response.paymentUrl – redirect the customer here // response.tokens – save these for the customer await saveTokens(customerId, response.tokens, response.transactionId) ``` Differences from `startPayment`: * Card (`CARD`) only; the `method` field is ignored. * The second (`config`) argument is the same as for `startPayment`: `redirectUrl` or `urls`. `startTokenPayment` also accepts a `{ redirectUrl }` config. * The request sends `threeDSReqAuthMethod: '02'` (registered user) by default. Set the `threeDSReqAuthMethod` field to send `'01'` (guest) or `'05'` (registered with a third-party identifier) instead. * The other `startPayment` order fields (`items`, `delivery`, `timeout`, `maySelect*` and so on) work here too. * If a `recurring` field is falsy (`0`, `''`), the SDK uses a default: `times: 3`, `until`: about 180 days from now, `maxAmount: 12000`. The type marks all three fields as required. The response (`SimplePayRecurringResponse`) contains the usual fields plus a `tokens: string[]` array. ::: warning Tokens are your responsibility You must store the tokens securely (per customer, together with the registration `transactionId`). The SDK stores nothing. ::: ## 2. Back URL and IPN Same endpoints as one-time payments: [back URL](./back-url) and [IPN](./ipn). The card registration IPN has two extra fields: * `cardMask`: the masked card number, for example `xxxx-xxxx-xxxx-1234` * `expiry`: the card's expiry, for example `2028-12-31T00:00:00+01:00` Save them so the customer can see which card is registered. ## 3. Charging a token When the next charge is due (for example in a daily `cron` job), call `startTokenPayment`: ```ts import { startTokenPayment } from 'simplepay-js-sdk' const response = await startTokenPayment({ orderRef: `sub-2026-0001-${Date.now()}`, // new orderRef for every charge token: nextUnusedToken, // a token not used yet total: 4990, // at most maxAmount currency: 'HUF', method: 'CARD', // required, must be CARD customer: 'Test Customer', customerEmail: 'customer@example.com', language: 'EN', }) // response.transactionId identifies the charge await markTokenUsed(nextUnusedToken) ``` * The call goes to SimplePay's `/dorecurring` endpoint with `type: 'MIT'` and `threeDSReqAuthMethod` (default `'02'`, overridable with the `threeDSReqAuthMethod` field). * No redirect is needed; the response (`SimplePayTokenResponse`) has no `paymentUrl`. * An IPN reports the result, just like a one-time payment. * Use each token once. When the tokens run out or `until` has passed, the customer must register the card again. ## 4. Removing a card Let customers remove their registered card. `cardId` is the **SimplePay transaction ID of the card registration** (the `transactionId` of the `startRecurringPayment` response). ```ts import { cancelCard } from 'simplepay-js-sdk' const response = await cancelCard(registrationTransactionId) if (response.status === 'DISABLED') { await deleteTokensAndCard(customerId) // the remaining tokens can go too } ``` ::: warning HUF account only `cancelCard` always uses `SIMPLEPAY_MERCHANT_ID_HUF` / `SIMPLEPAY_MERCHANT_KEY_HUF`. Cards registered on other currency accounts cannot be removed with it yet. ::: Response (`SimplePayCancelCardResponse`): `salt`, `merchant`, `cardId`, `status: 'DISABLED'`, `expiry`. ## Sandbox test cards for recurring payments | Card number | Result | |---|---| | `4908 3660 9990 0425` | Successful payment | | `5437 5884 9903 4193` | Registration succeeds, payment fails | | `6757 6192 9705 7001` | Registration fails, payment succeeds | Details: [Testing](./testing). --- --- url: https://simplepay.webmania.cc/en/guide/refunds-and-queries.md description: >- Full and partial refunds, transaction status and queries with the simplepay-js-sdk refund, getTransactionStatus and queryTransactions functions. --- # Refunds and transaction queries ## Refunds `refund` refunds a `FINISHED` transaction fully or partially (`/refund` endpoint). Pass exactly one identifier: `transactionId` or `orderRef`. ```ts import { refund } from 'simplepay-js-sdk' const { refundTransactionId, refundTotal, remainingTotal } = await refund({ orderRef: 'ORDER-1001', refundTotal: 2500, }) ``` * The refund is in the transaction's currency. `currency` must be that currency, and it also picks the merchant account (default: `HUF`). For a SZÉP card transaction: `currency: 'HUF_SZEP'`. * Partial refunds can be repeated until the original amount is used up. `remainingTotal` shows how much can still be refunded. * Each refund is a separate transaction; its id is `refundTransactionId`. * For a full refund, pass the whole remaining amount (the `remainingTotal` from `queryTransactions`). * A zero, negative or non-numeric `refundTotal` throws before any request is sent. ## Transaction status `getTransactionStatus` looks up one transaction on SimplePay's lightweight `/status` endpoint. Pass exactly one identifier: the SimplePay `transactionId` or your own `orderRef`. Passing both or neither throws before any request is sent. ```ts import { getTransactionStatus } from 'simplepay-js-sdk' const { status, endState } = await getTransactionStatus({ orderRef: 'ORDER-1001' }) // or: await getTransactionStatus({ transactionId: 501234567 }) if (endState) { // final status: FINISHED, CANCELLED, NOTAUTHORIZED, TIMEOUT or REVERSED } ``` * `currency` picks the merchant account (default: `HUF`). For a SZÉP card transaction pass `currency: 'HUF_SZEP'`. * `transactionId` can be a number or a numeric string. * Possible `status` values: `INIT`, `INPAYMENT`, `INFRAUD`, `AUTHORIZED`, `FINISHED`, `CANCELLED`, `NOTAUTHORIZED`, `TIMEOUT`, `REVERSED`. * `endState` is `true` when the status will not change any more. The [IPN](./ipn) also reports the final result. The status lookup helps when an IPN did not arrive, or when you want the status right away as the customer returns. ## Transaction query `queryTransactions` looks up one or more transactions on the `/query` endpoint by `transactionIds` and/or `orderRefs`. At least one identifier is required. ```ts import { queryTransactions } from 'simplepay-js-sdk' const { transactions, totalCount } = await queryTransactions({ orderRefs: ['ORDER-1001', 'ORDER-1002'], transactionIds: [501234567], detailed: true, // order data: customer, invoice and delivery address, ... refunds: true, // refund status and the list of refunds }) for (const t of transactions) { console.log(t.orderRef, t.status, t.remainingTotal, t.customerEmail, t.refundStatus, t.refunds) } ``` * Every transaction has: `orderRef`, `transactionId`, `status`, `total`, `remainingTotal`, `method`, `paymentDate`, `finishDate`. * With `detailed: true`: `currency`, `customer`, `customerEmail`, `language`, `twoStep`, `shippingCost`, `discount`, `invoice`, `delivery`. * With `refunds: true`: `refundStatus` and `refunds` (`transactionId`, `refundTotal`, `refundDate`, `status`). * The response type follows the flags: with `detailed: true`, for example, `customerEmail` is not optional. This works only when you write the flag as literal `true`; with a `boolean` variable the fields stay optional. * `currency` picks the merchant account here too (default: `HUF`). --- --- url: https://simplepay.webmania.cc/en/guide/testing.md description: >- SimplePay sandbox test cards (successful, failed, 3DS, SZÉP, card registration), testing the IPN locally, and using simplepay-js-sdk in unit tests. --- # Testing (sandbox) Until `SIMPLEPAY_PRODUCTION` is `true`, the SDK calls the SimplePay sandbox (`https://sandbox.simplepay.hu/payment/v2`). The sandbox has its own merchant account and keys. ## Test cards Source: [SimplePay – test card numbers](https://docs.simplepay.hu/hu/developer-tools/testing/test-card-numbers). Every card uses expiry **12/28** and CVC **123**; any cardholder name works. | Card number | Type | Result | |---|---|---| | `4908 3660 9990 0425` | Visa | Successful payment | | `5587 4020 0001 2011` | Mastercard | Successful payment | | `4111 1111 1111 1111` | Visa | Failed payment | | `4000 0010 0000 0042` | Visa | 3DS challenge | | `6101 3242 9669 0851` | SZÉP | Successful SZÉP card payment | | `6101 3242 1723 7212` | SZÉP | Failed SZÉP card payment | | `5437 5884 9903 4193` | Mastercard | Card registration succeeds, payment fails | | `6757 6192 9705 7001` | Maestro | Card registration fails, payment succeeds | The 3DS card shows a simulated challenge page: code `000` succeeds, anything else fails. No real SMS or push notification is sent. ::: tip Check the source SimplePay can change the test cards at any time. If one stops working, check the official page. ::: ## What to try * \[ ] Successful payment → `SUCCESS` on the back URL, `FINISHED` IPN, order paid * \[ ] Failed payment → `FAIL`, the customer sees the transaction ID * \[ ] Cancel on the payment page → `CANCEL` * \[ ] 3DS card with `000` and with a wrong code * \[ ] SZÉP card (if you use it) * \[ ] Same IPN twice → the order is fulfilled once * \[ ] IPN with a bad `Signature` header → 400, order unchanged * \[ ] Recurring: registration, token charge, card removal ## IPN locally The sandbox only sends IPNs to a public address. For local development use a tunnel (`cloudflared`, `ngrok` or similar) and set the resulting `https` address as the IPN URL in the sandbox merchant admin. ## Unit tests The SDK uses the global `fetch`, so replace that in tests. The SDK's own tests do the same (Vitest): ```ts import { vi, it, expect } from 'vitest' import { startPayment, generateSignature } from 'simplepay-js-sdk' it('starts a payment', async () => { process.env.SIMPLEPAY_MERCHANT_ID_HUF = 'testId' process.env.SIMPLEPAY_MERCHANT_KEY_HUF = 'testKey' const body = JSON.stringify({ transactionId: '123', paymentUrl: 'https://sandbox.simplepay.hu/pay/x' }) global.fetch = vi.fn().mockResolvedValue({ ok: true, headers: { get: () => generateSignature(body, 'testKey') }, // validly signed response text: async () => body, }) as unknown as typeof fetch const response = await startPayment({ orderRef: 'T1', total: 100, customerEmail: 'a@b.com' }) expect(response.paymentUrl).toContain('sandbox') }) ``` To test an IPN endpoint, put `generateSignature(ipnBody, key)` in the `Signature` header. --- --- url: https://simplepay.webmania.cc/en/reference/types.md description: >- simplepay-js-sdk TypeScript types from the source: PaymentData, RecurringPaymentData, TokenPaymentData, SimplePayResponse, SimplePayResult, SimplePayIPNResponse, TransactionStatus, Google Pay and Apple Pay types. --- # Types `simplepay-js-sdk` exports these types: ```ts import type { Currency, Language, PaymentMethod, PaymentConfig, StartPaymentConfig, SimplePayUrls, PaymentData, RecurringPaymentData, TokenPaymentData, PaymentItem, DeliveryAddress, InvoiceAddress, ThreeDSReqAuthMethod, GooglePayPaymentData, SimplePayGooglePayResponse, ApplePayStartData, ApplePayChargeData, SimplePayApplePayStartResponse, SimplePayApplePayChargeResponse, SimplePayResponse, SimplePayRecurringResponse, SimplePayTokenResponse, SimplePayCancelCardResponse, SimplePayResult, SimplePayIPNResponse, TransactionStatus, TransactionId, TransactionStatusQuery, SimplePayTransactionStatusResponse, TransactionQuery, SimplePayQueryResponse, QueriedTransaction, QueriedTransactionDetails, QueriedTransactionRefunds, TransactionRefund, RefundData, SimplePayRefundResponse, } from 'simplepay-js-sdk' ``` ## Basic types ```ts type Currency = 'HUF' | 'HUF_SZEP' | 'EUR' | 'USD' type PaymentMethod = 'CARD' | 'WIRE' type Language = 'AR' | 'BG' | 'CS' | 'DE' | 'EN' | 'ES' | 'FR' | 'IT' | 'HR' | 'HU' | 'PL' | 'RO' | 'RU' | 'SK' | 'TR' | 'ZH' type TransactionStatus = 'INIT' | 'INPAYMENT' | 'INFRAUD' | 'AUTHORIZED' | 'FINISHED' | 'CANCELLED' | 'NOTAUTHORIZED' | 'TIMEOUT' | 'REVERSED' ``` ## Input ### PaymentData ```ts interface PaymentData { orderRef: string total: number | string customerEmail: string currency?: Currency // default: 'HUF' language?: Language // default: 'HU' method?: PaymentMethod // default: 'CARD' invoice?: InvoiceAddress items?: PaymentItem[] // when sent, SimplePay ignores total shippingCost?: number discount?: number delivery?: DeliveryAddress customer?: string // if it differs from invoice.name extra?: Record maySelectEmail?: boolean maySelectInvoice?: boolean maySelectDelivery?: string[] // country codes, ['HU', 'AT'] timeout?: Date | string // default: now + 30 minutes threeDSReqAuthMethod?: ThreeDSReqAuthMethod } type ThreeDSReqAuthMethod = '01' | '02' | '05' // guest, registered, registered with a third-party identifier interface PaymentItem { ref?: string title?: string desc?: string amount: number // quantity price: number // unit price tax?: number // VAT %, e.g. 27 } interface DeliveryAddress { name?: string company?: string country: string state: string city: string zip: string address: string address2?: string phone?: string } interface InvoiceAddress extends DeliveryAddress { fiscalCode?: string // tax number } ``` ### PaymentConfig ```ts interface PaymentConfig { redirectUrl?: string } ``` ### StartPaymentConfig The second argument of `startPayment` and `startRecurringPayment`. When `urls` is given, it is sent instead of `url`. ```ts interface StartPaymentConfig extends PaymentConfig { urls?: SimplePayUrls } interface SimplePayUrls { success: string fail: string cancel: string timeout: string } ``` ### RecurringPaymentData ```ts interface RecurringPaymentData extends PaymentData { customer: string recurring: { times: number until: string // ISO 8601, see toISO8601DateString maxAmount: number } } ``` ### TokenPaymentData ```ts interface TokenPaymentData extends Omit { method: 'CARD' customer: string token: string } ``` ### GooglePayPaymentData ```ts interface GooglePayPaymentData { orderRef: string total: number | string customerEmail: string googlePayToken: string // Base64, unchanged from the browser currency?: Currency // not HUF_SZEP language?: Language invoice?: PaymentData['invoice'] } ``` ### ApplePayStartData ```ts interface ApplePayStartData { orderRef: string total: number | string customerEmail: string domain: string // the registered FQDN currency?: Currency // not HUF_SZEP language?: Language invoice?: PaymentData['invoice'] } ``` ### ApplePayChargeData ```ts interface ApplePayChargeData { transactionId: string | number applePayToken: string // Base64 currency?: Currency } ``` ### TransactionStatusQuery The `getTransactionStatus` parameter. Exactly one identifier is required. ```ts type TransactionId = string | number type TransactionStatusQuery = { currency?: Currency } & ( | { transactionId: TransactionId } | { orderRef: string } ) ``` ### TransactionQuery The `queryTransactions` parameter. At least one identifier is required. ```ts interface TransactionQuery { transactionIds?: TransactionId[] orderRefs?: string[] detailed?: boolean refunds?: boolean currency?: Currency } ``` ### RefundData The `refund` parameter. Exactly one identifier is required. ```ts type RefundData = { refundTotal: number | string currency?: Currency } & ( | { transactionId: TransactionId } | { orderRef: string } ) ``` ## Responses ### SimplePayResponse Returned by `startPayment`. ```ts interface SimplePayResponse { salt: string merchant: string orderRef: string currency: Currency transactionId: string timeout: string total: string paymentUrl: string errorCodes?: string[] } ``` ### SimplePayRecurringResponse ```ts interface SimplePayRecurringResponse extends SimplePayResponse { tokens: string[] } ``` ### SimplePayTokenResponse ```ts type SimplePayTokenResponse = Omit ``` ### SimplePayCancelCardResponse ```ts interface SimplePayCancelCardResponse { salt: string merchant: string cardId: string status: 'DISABLED' expiry: string } ``` ### SimplePayResult Returned by `getPaymentResponse`. ```ts interface SimplePayResult { responseCode: number transactionId: string event: 'SUCCESS' | 'FAIL' | 'TIMEOUT' | 'CANCEL' merchantId: string orderRef: string tokens?: string[] } ``` ### SimplePayIPNResponse The shape of an IPN body (`handleIpnRequest` adds `receiveDate`). ```ts interface SimplePayIPNResponse { salt: string orderRef: string method: string merchant: string finishDate: string paymentDate: string transactionId: number status: 'FINISHED' | 'AUTHORIZED' | 'NOTAUTHORIZED' | 'REVERSED' | 'CANCELLED' | 'TIMEOUT' receiveDate: string expiry?: string // card registration only cardMask?: string // card registration only } ``` ### SimplePayTransactionStatusResponse What `getTransactionStatus` returns. ```ts interface SimplePayTransactionStatusResponse { salt: string merchant: string orderRef: string transactionId: number status: TransactionStatus endState: boolean // true: FINISHED, CANCELLED, NOTAUTHORIZED, TIMEOUT, REVERSED } ``` ### SimplePayQueryResponse What `queryTransactions` returns. The type of each `transactions` item follows the `detailed` and `refunds` flags. ```ts interface SimplePayQueryResponse { salt: string merchant: string transactions: QueriedTransactionOf[] totalCount: number } interface QueriedTransaction { salt: string merchant: string orderRef: string transactionId: number status: TransactionStatus resultCode?: string total: number remainingTotal: number method: string paymentDate: string finishDate?: string } // detailed: true interface QueriedTransactionDetails { currency: Currency customer?: string customerEmail: string language: Language twoStep?: boolean shippingCost?: number discount?: number invoice?: QueriedAddress delivery?: QueriedAddress } // refunds: true interface QueriedTransactionRefunds { refundStatus: string refunds: TransactionRefund[] } interface TransactionRefund { transactionId: number refundTotal: number refundDate: string status: TransactionStatus } ``` ### SimplePayRefundResponse What `refund` returns. ```ts interface SimplePayRefundResponse { salt: string merchant: string orderRef: string currency: Currency transactionId: number // the original transaction refundTransactionId: number // the refund transaction refundTotal: number remainingTotal: number // still refundable } ``` ### SimplePayGooglePayResponse ```ts interface SimplePayGooglePayResponse { salt?: string merchant: string orderRef: string currency: Currency transactionId: string | number total: string | number timeout?: string paymentUrl?: string redirectUrl?: string // on 3DS errorCodes?: Array // on 3DS ['3004'] } ``` ### SimplePayApplePayStartResponse ```ts interface SimplePayApplePayStartResponse { salt?: string merchant: string orderRef?: string currency?: Currency transactionId: string | number total?: string | number timeout?: string applePaySession?: ApplePayMerchantSession // merchantSessionIdentifier, nonce, signature … errorCodes?: Array } ``` ### SimplePayApplePayChargeResponse ```ts interface SimplePayApplePayChargeResponse { salt?: string merchant: string orderRef?: string currency?: Currency transactionId: string | number total?: string | number applePayStatus?: string // 'STATUS_SUCCESS' errorCodes?: Array } ``` ## Browser config ### GooglePayButtonConfig `simplepay-js-sdk/google-pay` | Field | Type | Required | Description | |---|---|---|---| | `container` | `HTMLElement \| string` | yes | Where the button goes | | `merchantId` | `string` | yes | Google merchant ID | | `merchantName` | `string` | yes | Display name | | `environment` | `'TEST' \| 'PRODUCTION'` | yes | Google Pay environment | | `gatewayMerchantId` | `string` | yes | SimplePay merchant ID | | `authorizationEndpoint` | `string` | yes | Your server endpoint | | `currency` | `string` | yes | Currency | | `total` | `string` | yes | Displayed amount | | `orderRef` | `string` | yes | Order reference | | `countryCode` | `string` | no | Default: `HU` | | `allowedCardNetworks` | `('VISA' \| 'MASTERCARD' \| 'AMEX')[]` | no | Default: all | | `onResult` | `(response: unknown) => void` | no | Your server's response | | `onError` | `(error: unknown) => void` | no | Error | ### ApplePayButtonConfig `simplepay-js-sdk/apple-pay` | Field | Type | Required | Description | |---|---|---|---| | `container` | `HTMLElement \| string` | yes | Where the button goes | | `merchantIdentifier` | `string` | yes | Apple Pay merchant identifier | | `merchantName` | `string` | yes | Display name | | `validationEndpoint` | `string` | yes | Endpoint that calls `startApplePay` | | `authorizationEndpoint` | `string` | yes | Endpoint that calls `doApplePay` | | `currency` | `string` | yes | 3-letter currency code | | `total` | `string` | yes | Positive amount, at most 2 decimals | | `orderRef` | `string` | yes | Order reference | | `countryCode` | `string` | no | Default: `HU` | | `locale` | `string` | no | Default: `hu-HU` | | `buttonStyle` | `'black' \| 'white' \| 'white-outline'` | no | Default: `black` | | `buttonType` | `'plain' \| 'buy' \| 'pay' \| 'check-out' \| 'book' \| 'donate' \| 'subscribe'` | no | Default: `plain` | | `supportedNetworks` | `('visa' \| 'masterCard' \| 'amex' \| 'discover')[]` | no | Default: all | | `onResult` | `(response: unknown) => void` | no | Successful charge | | `onError` | `(error: unknown) => void` | no | Error |