2026-10-16 13:35:51 +02:00
2026-10-16 13:35:51 +02:00

vue-paymentgateway-layer

A Nuxt layer with the customer order screens of the SummerCMS payment gateway: the order page with checkout and every order state, and the logged-in customer's order list, over the customer API /_paymentgateway/api/v1. It also carries the subscription pieces (a plans table, subscribe and billing portal redirects, the customer's subscription with cancel) over /_paymentgatewaysubscriptions/api/v1.

export default defineNuxtConfig({ extends: ['vue-paymentgateway-layer'] })

Overview

The payment gateway plugin (golem15.paymentgateway, repository sm-paymentgateway-plugin) answers JSON for an order: its items and totals, the payment and delivery methods, and the actions a customer may take. This layer renders that API with neutral, token-driven components. A site mounts <PgOrderPage :hash> on its order route and <PgOrderList> on its account page, and gets checkout, payment and the order states without writing a request.

Payment defaults to the hosted redirect: Pay calls process, and when the API answers {redirect_url} (Stripe Checkout) the browser goes there, with the button kept busy so nothing is submitted twice. The layer ships no payment SDK and never handles card data. A site that runs an on-site card form (Stripe PaymentIntent mode) confirms the payment itself through the #payment-action slot.

Installation

Add the layer as a git dependency pinned to a tag, next to the Nuxt and Vue versions it is built for:

{
  "dependencies": {
    "nuxt": "4.4.8",
    "vue": "3.5.35",
    "vue-paymentgateway-layer": "git+ssh://git@git.golem15.com/golem15/vue-paymentgateway-layer.git#v0.2.0"
  }
}
// nuxt.config.ts
export default defineNuxtConfig({
  extends: ['vue-paymentgateway-layer'],
  i18n: {
    defaultLocale: 'pl',
    locales: [{ code: 'pl', language: 'pl-PL' }, { code: 'en', language: 'en-US' }],
  },
})

The layer declares @nuxtjs/i18n (10.4.0), so the app does not list it again. It registers its pg.* copy only for the locales the app enables (pl, en).

Runtime config

Key Default Purpose
paymentgateway.apiBase (NUXT_PAYMENTGATEWAY_API_BASE) http://127.0.0.1:8096/_paymentgateway/api/v1 Server-only base of the API for server rendering. The visitor's x-forwarded-for and the peer address are forwarded, so the API's rate limit counts visitors, not the Nuxt server.
public.paymentgateway.apiBase (NUXT_PUBLIC_PAYMENTGATEWAY_API_BASE) /_paymentgateway/api/v1 Browser base. Same origin by default (proxy the path to the SummerCMS application); a cross-origin API needs the host's http.cors.paths to list _paymentgateway/api/*.
paymentgatewaysubscriptions.apiBase (NUXT_PAYMENTGATEWAYSUBSCRIPTIONS_API_BASE) http://127.0.0.1:8096/_paymentgatewaysubscriptions/api/v1 Server-only base of the subscriptions API for server rendering, with the same forwarding.
public.paymentgatewaysubscriptions.apiBase (NUXT_PUBLIC_PAYMENTGATEWAYSUBSCRIPTIONS_API_BASE) /_paymentgatewaysubscriptions/api/v1 Browser base of the subscriptions API. Same origin by default; a cross-origin API needs _paymentgatewaysubscriptions/api/* in the host's http.cors.paths.

Usage

<!-- pages/orders/[hash].vue -->
<script setup lang="ts">
const route = useRoute()
</script>

<template>
  <PgOrderPage
    :hash="String(route.params.hash)"
    :guest-code="route.query.guest_code as string | undefined"
    :guest-token="route.query.guest_token as string | undefined"
    home-to="/"
  />
</template>
<!-- pages/account/orders.vue -->
<template>
  <PgOrderList :to="(o) => `/orders/${o.hash_id}`" />
</template>

A guest opens the order with the code or token from the order mail (?guest_code= or ?guest_token=), forwarded as query parameters. A logged-in owner is recognized by the auth hook.

The auth hook

Logged-in customers need their frontend JWT on the API requests (GET /orders requires it; on the order routes it identifies the owner). The app provides paymentGatewayAuth, a function answering the token or null, from a Nuxt plugin:

// plugins/payment-gateway-auth.ts
export default defineNuxtPlugin(() => ({
  provide: { paymentGatewayAuth: () => useCookie<string | null>('token').value ?? null },
}))

The token is sent as Authorization: Bearer, during server rendering and in the browser. Without the hook every request is anonymous: guests still reach their orders through the code or token, and PgOrderList shows its error.

On-site card payments (#payment-action)

When the payment operator answers a PaymentIntent ({requires_action: true, client_secret, payment_intent_id, payment_uuid, publishable_key}), PgCheckout renders the scoped slot #payment-action="{ action, done }" under the payment methods. The app confirms the payment with its own Stripe.js code and calls done(), which reloads the order (the payment's webhook moves it on). Pass the slot through PgOrderPage:

<PgOrderPage :hash="hash">
  <template #payment-action="{ action, done }">
    <MyCardForm :client-secret="action.client_secret" :publishable-key="action.publishable_key" @confirmed="done" />
  </template>
</PgOrderPage>

Without the slot, a PaymentIntent answer shows pg.error.payment_action ("choose another payment method"). The hosted redirect (D-17) needs nothing.

Components

Component Props What it renders
PgOrderPage hash (required), guestCode, guestToken, headingLevel (1 to 3, default 1), homeTo Fetches the order during SSR (pg:order:<hash>). Placed: PgCheckout. Every other state: PgOrderStatus. 404 (also a forbidden order): the not-found panel with a link to homeTo. Any other failure: pg.error.load with Retry. An AwaitingPayment order paid online is polled every 3 s for 20 attempts, paused while the page is hidden, then shows pg.awaiting.slow with a Refresh button. Slot #payment-action.
PgCheckout order, refresh, guestCode, guestToken, headingLevel The cart (editable), the delivery methods (when the API lists any), the payment methods (those accepting the order currency), the bank transfer details, Cancel order and Pay. Pay saves changed methods, then processes.
PgOrderStatus order, refresh, guestCode, guestToken, headingLevel, polling, slow The status panel: tone bar, title and body of the state, code and total, the bank transfer details while a transfer is awaited, the read-only cart, Cancel order (AwaitingPayment) and Request a refund (when refundable). Emits refresh-status.
PgCart order, editable, busy, busyItem, dimmed The items, delivery line and totals. Editable: a stepper whose decrease stops at 1, and Remove (confirmed) on every item except the last. Emits add, subtract, remove.
PgPaymentMethods methods, error, disabled, v-model (code) Radio cards of the payment methods; the no-methods copy without any.
PgShippingMethods shippings, error, disabled, v-model (id) Radio cards of the delivery methods with their gross cost or free delivery.
PgBankTransfer bank, code Recipient, address, account number and SWIFT (empty ones omitted), the server-sanitized bank details, and the transfer title with the order code.
PgOrderList to (order to route), page The user's orders with pagination, empty copy, skeleton rows and the load error with Retry.
PgConfirm open, title, body, confirmLabel, dismissLabel, danger, busy A native <dialog> (focus on dismiss, Esc closes, focus returns to the opener). Emits confirm, close.

The composables are usePaymentGatewayApi() (the typed client), useOrder(hash, query) and useOrders({ page }); the utilities createPaymentGatewayClient, formatMoney, stateTone, createCheckout and createAwaitingPoller are importable from vue-paymentgateway-layer/app/utils/*.

Overriding a component

Every component is replaced by a file with the same name in the app (app/components/Pg/Cart.vue replaces PgCart), the usual Nuxt layer rule. Prefer tokens and copy overrides for visual changes; replace a component only when its markup must change.

Subscriptions

The subscription pieces render the customer API of the subscriptions plugin (golem15.paymentgatewaysubscriptions, repository sm-paymentgatewaysubscriptions-plugin) with a subscription gateway installed (for Stripe, golem15.pgstripesubscriptions). The application must serve that API under /_paymentgatewaysubscriptions/api/v1, and the runtime config keys paymentgatewaysubscriptions.apiBase and public.paymentgatewaysubscriptions.apiBase point the layer at it (see Runtime config). A site that only takes orders mounts none of these components, and nothing is fetched for it.

<!-- pages/pricing.vue -->
<template>
  <PgPlans currency="PLN" />
</template>
<!-- pages/account/subscription.vue -->
<template>
  <PgMySubscription plans-to="/pricing" />
</template>

Auth. The subscription routes need the logged-in user's frontend JWT. The layer reuses the paymentGatewayAuth hook (see The auth hook) and sends the token as Authorization: Bearer only. GET /plans is public. The subscriber is always the user of the token: the layer never sends a subscriber id, a subscription id or a redirect URL. Checkout's success and cancel pages and the portal's return page are the plugin's configuration.

Redirects. Subscribe and Manage billing send the browser to the checkout_url or portal_url the API answered, with location.assign exactly once. The button stays busy until the browser leaves, so a second click opens no second session. When the user comes back with the browser's Back button and the page is restored from the back/forward cache (a pageshow event with persisted true), the Subscribe and Manage billing buttons and PgMySubscription's cancel are enabled again, and PgMySubscription refreshes to show what the portal changed. A navigation that throws enables the button again with the generic error. A URL that is not absolute http(s) is never followed.

Client and composables

createSubscriptionsClient(fetch) (in app/utils/subscriptionsClient.ts) wraps the same injected fetcher type as the order client (PaymentGatewayFetcher). Its methods:

Method Request Answer
plans() GET /plans PgPlan[] (the {data} envelope unwrapped): code, name, description, billing_interval, prices (PgMoney[], one per currency), features (strings)
subscription() GET /subscription PgSubscription: status, plan (PgPlanSummary), the period, cancel and trial dates, cancel_at_period_end, days_until_renewal, has_access, in_grace_period. A user without a subscription gets 404 (hasNoSubscription(err)).
checkout(planCode, currency?) POST /subscription/checkout {plan_code, currency?} PgCheckoutAnswer {checkout_url, session_id}
portal() POST /subscription/portal PgPortalAnswer {portal_url}
cancel() POST /subscription/cancel PgSubscription with cancel_at_period_end: true (cancel at the period end)

The helpers planPrice(plan, currency) (the matching money object, else the plan's first price), subscriptionStatusKey, billingIntervalKey, SUBSCRIPTION_STATUSES and BILLING_INTERVALS live in the same file. The flows createSubscribeFlow and createManageFlow (app/utils/subscribe.ts) take {client, location}. They keep a SubscribeState (busy, redirecting, error), and subscriptionErrorKey maps a refused request to its copy. Each flow has restore(), which sets busy and redirecting to false and clears the error. watchPageRestore(target, handler) registers a pageshow listener on a PageRestoreTarget (in a component, window in onMounted) that calls handler only on a back/forward-cache restore, and returns its remover (call it in onBeforeUnmount); an undefined target, as during server rendering, returns a no-op remover. The three subscription components wire it to their flow's restore().

The composables:

  • useSubscriptionsApi(): the client on the server base during SSR (forwarding x-forwarded-for like usePaymentGatewayApi) and on the public base in the browser.
  • usePlans(): useAsyncData keyed pg:subscriptions:plans.
  • useSubscription(): useAsyncData keyed pg:subscriptions:current, with the 404 turned into null.

Subscription components

Component Props What it renders
PgPlans currency (ISO code, default each plan's first price), planCodes (only these codes, in the API's order) One card per active plan: name, description, the price for the chosen currency (the exact server amount, formatted for the locale) with its interval, the features as a text list, and PgSubscribeButton for a paid plan. A free plan shows the free label. Skeleton cards while loading, pg.subscriptions.error.load with Retry, the empty copy. Slot #plan-actions="{ plan, price }" replaces the subscribe button (for example with a login link for guests).
PgSubscribeButton planCode (required), currency, label Posts the checkout and redirects to checkout_url once. A refusal shows its error line; on 409 (already subscribed) it also offers PgManageSubscriptionButton.
PgMySubscription plansTo (route of the plans page) The latest subscription: plan name, the localized status with a tone bar (success for active and trialing; warning for past_due, unpaid, incomplete and paused; danger for canceled and incomplete_expired), the current period end, the days until renewal, the trial end, the will-cancel notice, the grace notice, the access line, PgManageSubscriptionButton, and Cancel subscription through PgConfirm (active or trialing, no cancel scheduled; a confirmed cancel takes effect at the period end and the panel refreshes). Without a subscription: pg.subscriptions.none and a link to plansTo. A 401: the login copy. Slot #none replaces the no-subscription panel.
PgManageSubscriptionButton label Posts the portal request and redirects to portal_url once. A user who never checked out sees pg.subscriptions.error.no_billing_account.

Error copy by status: 401 pg.subscriptions.error.login, 409 pg.subscriptions.error.already_subscribed (the API answers 409 for any open subscription, past_due and unpaid included, so the copy and the offered PgManageSubscriptionButton fit those users too), 422 pg.subscriptions.error.unavailable (a free plan or a currency without a price), 429 pg.error.throttled, 502 and 503 pg.subscriptions.error.provider, a 404 on the portal pg.subscriptions.error.no_billing_account, anything else pg.subscriptions.error.generic.

The subscription components follow the same rules as the order components: they use the pg-* classes on the tokens below, render every plan and subscription text through interpolation (never as HTML), and are replaced by a same-name file in the app (app/components/Pg/Plans.vue replaces PgPlans).

Changes in 0.2.1

  • Back from Stripe's Checkout or billing portal no longer leaves PgSubscribeButton, PgManageSubscriptionButton or the Cancel action of PgMySubscription disabled. When the browser restores the page from its back/forward cache (pageshow with persisted true), the component calls its flow's restore(); PgMySubscription also reloads the subscription. The listener is registered on mount and removed on unmount (watchPageRestore, PageRestoreTarget). A navigation that throws enables the button again with pg.subscriptions.error.generic.
  • The already_subscribed copy (en and pl) no longer says "active", because the API answers 409 for any open subscription.
  • No dependency change.

Tokens

app/assets/css/pg-tokens.css declares every visual value on :root; pg-base.css uses only these. Override any of them after the layer's CSS (for example on :root:root):

  • colour: --pg-color-text, --pg-color-muted, --pg-color-bg, --pg-color-surface, --pg-color-border, --pg-color-accent, --pg-color-on-accent, --pg-color-danger, --pg-color-success, --pg-color-warning, --pg-color-backdrop;
  • type: --pg-font, --pg-font-size-sm, --pg-font-size, --pg-font-size-lg, --pg-font-size-xl, --pg-line-height;
  • spacing: --pg-space-1 to --pg-space-5;
  • radii: --pg-radius, --pg-radius-card;
  • layout: --pg-width (the checkout column), --pg-target (minimum button and card height);
  • shadow: --pg-shadow (the dialog).

The status bar tones: success for Paid, Underway, Shipped and Finished; warning for AwaitingPayment, RequestedRefund, AwaitingReturn and Quote; danger for Canceled and Rejected; neutral otherwise. The title text always accompanies the tone.

Copy

The copy lives in i18n/locales/{en,pl}.json under pg.*: pg.state.<state>.title and .body for every order state (the lower-cased state, plus awaitingpayment_polling), pg.checkout.*, pg.cart.*, pg.bank.*, pg.orders.*, pg.action.*, pg.cancel.*, pg.refund.*, pg.item.*, pg.error.*, pg.not_found.* and pg.awaiting.slow; the subscription copy is under pg.subscriptions.* (status.<status> for the eight statuses, interval.month and interval.year, cancel.*, error.*). An app overrides any key in its own i18n messages. Placeholders use vue-i18n's {name} form.

Amounts

The API sends every amount as {amount: "2999.9700", amount_minor: 299997, currency: "PLN"}. formatMoney hands the exact string to Intl.NumberFormat with the ISO code and two to four fraction digits (PLN 39.84, 39,84 PLN, 85.4193 kept), never a floating-point number. The layer never computes or sends an amount: totals always come from the server.

Development

pnpm install
pnpm test               # node --test (TAP): every file under tests/
pnpm run dev:prepare    # types for the playground
pnpm run dev            # the playground (.playground) against an API on 127.0.0.1:8096
pnpm run check:git-install v0.2.0   # installs the tag from git into a scratch app and builds it

The tests run under Node 22.18 or later with type stripping; components are compiled with Vue's SFC compiler and rendered on the server with stubbed Nuxt globals (testing/load.ts).

Testing

pnpm test runs node --test over tests/*.test.ts and reports TAP. No test reaches the network: the client gets a stubbed fetcher, and the composables and components get stubbed Nuxt globals.

File What it pins
tests/client.test.ts API paths, methods and bodies; the guest query; the composable's base URL and bearer token
tests/money.test.ts amounts formatted from the exact string, never a number
tests/checkout.test.ts the redirect contract of PgCheckout (one location.assign, busy until the browser leaves, no second request), PaymentIntent and error answers, field errors, 409 and 429
tests/orderPage.test.ts polling every 3 s until Paid, the 20-attempt limit, pausing while hidden; PgOrderPage routing, not-found and load error
tests/states.test.ts the state tone map and the polling rule
tests/i18n.test.ts identical en and pl key sets and placeholders; every pg.* key used in app/ exists; the pg.subscriptions.* keys, every status and interval label
tests/cart.test.ts PgCart: the stepper floor at 1, no Remove on the last item, the danger confirm, the busy row, re-rendering from the API answer
tests/orderList.test.ts PgOrderList: empty copy, skeleton rows, load error with Retry, rows and totals, pagination
tests/confirm.test.ts PgConfirm through a minimal custom renderer: modal open with focus on Dismiss, focus back to the opener, Esc and Dismiss as close, confirm, buttons disabled and Esc refused while busy
tests/subscriptions.test.ts the subscriptions client's paths, methods and bodies, the {data} unwrap, no redirect URL or id sent, refusals passed through unchanged, hasNoSubscription, the price, status and interval helpers; useSubscriptionsApi's bases, forwarding and bearer token; usePlans' key
tests/subscribe.test.ts the subscribe redirect contract (one location.assign, busy until the browser leaves, no second request), every refused status's copy, a retry after a refusal, non-http(s) answers never followed; PgPlans with the real PgSubscribeButton; both buttons' copy before a click; the back/forward-cache restore (0.2.1): a persisted pageshow restores the subscribe and manage flows, a non-persisted one changes nothing, watchPageRestore's remover and its no-op without a target, a throwing navigation re-enabling the button with the generic error
tests/subscriptionComponents.test.ts PgPlans prices in the chosen currency, features, free plans, plan filter, markup as text and its states; PgMySubscription none (the API's 404 end to end), active, trialing, scheduled cancel, past_due and 401 states, and Cancel only for an active or trialing subscription with no cancel scheduled; useSubscription's 404 as null; the manage and cancel flows with every refused status and the busy guard; the three components' watchPageRestore wiring on mount and unmount (from their sources, since the specs render on the server); the already_subscribed copy in en and pl
tests/methods.test.ts method preselection, the currency filter, Pay disabled without methods, the delivery fieldset only when methods are listed, the bank transfer block, the pickers' checked card, free delivery and field error

The framework repository's scripts/check-phase18.sh layers requires these files and their test names, and scripts/check-phase18.1.sh layers requires the three subscription files and a minimum number of passing tests named subscriptions: .... Both fail on a not ok, a skip, a todo or zero passes.

Description
No description provided
Readme 318 KiB
Languages
TypeScript 71.4%
Vue 22.5%
CSS 4.6%
Shell 1.5%