@spring-payments/payments-js
v0.2.0
Published
Spring-managed web card saving and payment authentication
Readme
Spring Payments for web
Add a debit or credit card to your React, Vue or plain JavaScript app. Spring provides the secure card-entry form and handles any verification the customer's bank requires. Your app controls the surrounding design; your backend decides which customer can add a card or finish a payment.
Saving a card does not charge it. Your backend starts payments separately through Spring's API.
For a framework-native API, @spring-payments/payments-react (React 19 / Next.js) and @spring-payments/payments-vue (Vue 3.5 / Nuxt) provide typed SpringAddCardButton and inline SpringAddCard components over this SDK. This package remains the direct choice for plain JavaScript and other frameworks; all three use the same backend and styling contract.
Install
npm install @spring-payments/payments-jsimport { mountAddCardButton, addCard, mountAddCard, authenticatePayment, clearRecoveryParameters }
from '@spring-payments/payments-js';Install from npm and include the package in your app's build. This is the only supported way to add the components to your app, including plain JavaScript apps. You do not need access to Spring's repository. Do not import the SDK from a Gateway URL or copy its source into your project. Spring loads Stripe.js for you.
Before you add the UI
Your customer must be registered with Spring, have accepted the required documents, and be allowed to add cards. Your backend needs Spring API credentials. Keep those credentials on the server, never in the browser.
The component calls a function you provide, createSession. That function calls your backend, which checks the signed-in customer's access and asks Spring for a session: short-lived permission to add a card or verify one existing payment. Return Spring's session response to the component. See Connect your backend below for the endpoints and fields.
Ready-made card dialog and button
Add an element such as <div id="add-card"></div> to your page, then mount the button. partnerBackend and the result handlers below are functions you provide in your app; they are not part of the SDK.
const trigger = mountAddCardButton('#add-card', {
createSession: ({ origin, returnUrl }) => partnerBackend.createCardSession({ origin, returnUrl }),
labels: { button: 'Add debit or credit card', title: 'Add a card', confirm: 'Save card', close: 'Close' },
appearance: { theme: 'stripe', variables: { colorPrimary: '#17684a' } },
onResult: result => {
if (result.status === 'COMPLETED') refreshAccounts();
if (result.status === 'PENDING') checkStatusWithYourBackend();
},
});
// trigger.open() opens the dialog from your own code.
// Call trigger.destroy() when the owning page or component unmounts.Handle the result rather than assuming that closing the dialog saved a card:
| Result | What your app should do |
| --- | --- |
| COMPLETED | Spring confirmed the saved card and returned paymentAccountId. Refresh your account list. |
| PENDING | Spring has not confirmed the outcome. Ask your backend to check before trying to save again. |
| CANCELLED | The customer closed the dialog before a save could have been submitted. |
| FAILED | The flow could not start or Spring rejected it. Show an appropriate message. |
Closing the dialog after the customer presses Save does not undo the request; the result may be PENDING. Repeated calls while a dialog is open share that dialog instead of creating another one. Results do not contain session tokens or Stripe credentials.
The dialog uses the browser's <dialog> element. It keeps keyboard focus inside, supports Escape, blocks interaction with the page behind it and returns focus when closed. Your supported browsers must support this element. Before going live, test the complete flow, including bank verification (often called 3DS) and keyboard/screen-reader access.
Styling: no Spring theme by default
Spring injects no CSS, inline styles, Shadow DOM, or branded footer. Without your styles, the button and dialog use browser defaults; your site's existing CSS can also affect them. “Unstyled” does not remove browser defaults or Stripe's default field theme. The example app's green controls are its own styles, not package defaults.
Use your own CSS to style these classes:
| Selector | What you control |
| --- | --- |
| .spring-card-trigger | Launch button: typography, spacing, colors, borders, focus/hover/disabled presentation |
| .spring-card-dialog and ::backdrop | Dialog size, padding, background, borders, rounding, shadow, scrolling, backdrop |
| .spring-card-close | Close button |
| .spring-card-title, .spring-card-description | Heading and supporting text |
| .spring-card-content | Layout around the secure card-entry component |
| .spring-payment-component | Inline component layout, also used within the dialog |
| .spring-payment-component > button | Save/retry/status-check button |
| .spring-payment-component > [role="status"] | Status/error text |
The dialog mounts under document.body by default, outside your trigger's container. Supply dialogContainer: document.querySelector('#partner-theme') to inherit a scoped theme from a connected element. CSS-module/scoped-framework selectors must reach these classes (for example, a global selector nested under your theme). Do not style dialog with an unconditional display: block or remove focus indicators, keyboard access, readable contrast, or adequate touch targets.
/* Your app owns these styles. There is no Spring stylesheet to override. */
.spring-card-trigger, .spring-payment-component > button {
font: inherit;
background: #234db5;
color: white;
border: 0;
border-radius: 6px;
padding: 12px 20px;
}
.spring-card-dialog {
width: min(480px, calc(100vw - 32px));
max-height: calc(100dvh - 32px);
overflow: auto;
padding: 24px;
border-radius: 12px;
}
.spring-card-dialog::backdrop { background: rgb(0 0 0 / 50%); }
.spring-card-trigger:focus-visible, .spring-card-dialog button:focus-visible {
outline: 3px solid #234db5;
outline-offset: 3px;
}labels supports button, title, description, close, and confirm. For a completely custom launch button, call addCard(options) yourself. For your own dialog/layout, use mountAddCard inside it; you own that dialog's accessibility and lifecycle.
Style the card fields separately from the buttons and dialog. Pass appearance to use Stripe's Appearance API. Spring forwards those settings to Stripe's secure fields. Ordinary page CSS cannot reach those fields because Stripe puts them in an iframe. Leave appearance out to keep Stripe's defaults. You cannot freely rearrange the fields or redesign the bank's verification screen. Never replace secure fields with your own card-number inputs.
Partners must mount this component for card entry and payment authentication; do not load or call Stripe directly. Import mountAddCard, authenticatePayment, and clearRecoveryParameters from the installed @spring-payments/payments-js package.
clearRecoveryParameters(); // before reading/logging a processor return URL
const view = mountAddCard('#card', {
returnUrl: `${location.origin}/recovery?recover=add-card`,
createSession: ({origin, returnUrl}) => partnerBackend.createCardSession({origin, returnUrl}),
appearance: {theme: 'stripe', variables: {colorPrimary: '#17684a'}},
labels: {confirm: 'Save card'},
onStateChange: ({status, paymentAccountId, paymentId}) => {},
onSuccess: ({status, paymentAccountId, paymentId}) => refreshAccounts(),
onError: ({code}) => {},
});
await view.ready;
// view.retry() explicitly retries recovery/status; view.destroy() unmounts/aborts.authenticatePayment(container, options) uses the same options, but its createSession must request permission for the specific existing payment. Your app supplies the saved-card list, removal controls and payment-status display. The success callback means Spring confirmed completion, not just that the customer finished entering details. Error callbacks return ERROR or EXPIRED, without Stripe credentials or raw server errors.
Connect your backend
Your createSession function calls your own backend. After checking the signed-in customer's access, your backend calls one of these Spring endpoints with its API access token:
| Action | Endpoint |
| --- | --- |
| Add a card | POST /api/external/spg/v1/clients/{key}/card-sessions |
| Finish payment verification | POST /api/external/spg/v1/clients/{key}/payments/{paymentId}/authentication-sessions |
Send {origin, returnUrl} in the body and an Idempotency-Key header. That key identifies one attempt: reuse it when retrying a lost response so you do not start a duplicate action. The return URL must use the same origin as your app. Return {sessionId, sessionToken, expiresAt, componentUrl} from Spring to the component, without changing it.
Keep session credentials in memory only. Do not put them in URLs, logs, analytics or browser storage. Set session responses to Cache-Control: no-store. The component uses the session token to contact Spring; your frontend does not need to read or manage Stripe credentials. Spring must allow your exact web origin and the Authorization header in its CORS configuration. Use HTTPS outside local development.
Sessions last 30 minutes. Reusing a key with changed URLs returns HTTP 409; retrying an expired session returns 410. Check whether the original action completed before starting a new session with a new key. The component checks status up to 10 times, 1.5 seconds apart, then offers Check status if the result is still pending. You can adjust this with maxPolls (1–30) and pollIntervalMs (100–5000). The __mock option is for tests only; do not use it in production.
Spring-hosted payment recovery (preferred)
If a payment needs bank verification after the customer has left your app, ask them to sign in and finish it on Spring's hosted recovery page. This is the preferred recovery option. It opens a Spring page; it does not load an embedded component into your app or replace npm installation.
After sign-in, your backend checks that the customer owns the original payment. It creates a web authentication session using the Gateway origin and {gatewayOrigin}/payment-components/recover as returnUrl. Submit sessionId and sessionToken to that page in a browser form POST body, never in the URL. Spring checks the session and the payment's result. Do not log the form body, cache credentials or record payment pages with session-replay tools.
After a reload, expiry or full-page bank redirect, return to your application, check the original payment's status and authorize a fresh recovery session only if needed. A direct GET of the hosted page cannot recover a session. Never create a replacement debit to finish authentication.
Redirect recovery in your application (optional)
Host a recovery page on the same origin as your app (the demo uses /?recover=add-card or /?recover={paymentId}). Call clearRecoveryParameters() immediately to remove credentials from the return URL, then restore the customer's sign-in. Your backend should check the original action before your app calls createSession again. Keep only the key identifying that action, never a session token, for use after a redirect.
A recovery link may contain a payment ID, but that ID does not grant access: your backend must check that the signed-in customer owns the payment. Check its status with GET /api/external/spg/v1/clients/{key}/payments/{paymentId}. Neither a redirect nor its URL parameters prove that payment succeeded.
Build your recovery page with the same installed npm package. After sign-in, authorize the original payment and use authenticatePayment with its payment-scoped session. A page reload, expiry or full-page processor redirect requires checking Spring's payment status and authorizing a fresh launch only if needed. Do not log session responses, attach session replay to payment views or cache credentials.
Use your app's CSS for .spring-payment-component, its button and status text; use appearance for Stripe's secure fields. Your Content Security Policy (CSP) must allow js.stripe.com scripts, js.stripe.com/hooks.stripe.com frames, and connections to Gateway and Stripe. Do not collect card data in your own inputs. Before release, test bank verification, payment notifications and your browser security settings with the configured backend.
License
MIT; see LICENSE. This license covers the Spring code in this SDK package, not Spring's backend, other repository directories, trademarks or access to payment services. Stripe's hosted technology and services remain subject to their own terms. Preserve the license notice when redistributing this SDK, including browser-served copies. The source repository may remain private; recipients may reuse and redistribute this package under MIT.
Maintaining and publishing (Spring maintainers)
Source of truth: packages/spring-payments-js/ in the private ktechgit/spring-payments repository. Edit src/index.ts and this README here, not a demo copy. Version 0.2.0 adds TypeScript declarations and compiled package exports. Partner integrations must consume a published npm version. Local tarballs below are for maintainer release validation only, not an alternative partner installation route.
From this directory:
npm ci
npm run build
npm test
npm pack --dry-run
npm packStrict TypeScript compilation emits dist/index.js and dist/index.d.ts; tests and npm pack build automatically. Keep package-lock.json committed for reproducible maintainer installs. @stripe/stripe-js supplies types only: there is no runtime npm import, and Spring still loads the hosted Stripe script on demand. Importing the package without browser globals is safe; invoke its UI methods only in the browser. Inspect the actual tarball: only dist/index.js, dist/index.d.ts, README.md, LICENSE and package.json belong in it. The complete MIT notice must remain in browser JavaScript output. Install that tarball in a clean consumer and test its public exports before release. Never include credentials, internal configuration, tests or unrelated repository files.
The package exports ComponentOptions, AddCardOptions, ComponentSession, ComponentState, ComponentError, ComponentView, CardResult, CardPresentation, AddCardButtonOptions, AddCardButtonHandle, and Stripe's Appearance as TypeScript types. createSession is required and returns a promise of the complete session response. Framework wrappers should import these shared types rather than duplicate them. Test-only transport/processor hooks are intentionally excluded from the public declarations.
For subsequent releases, choose a semantic version and run npm version patch --no-git-tag-version (or minor / major) before packing. Never overwrite or reuse a published version. Review and commit the source/version changes through Spring's release workflow.
Authenticate interactively with npm login --registry=https://registry.npmjs.org/; confirm the account with npm whoami and its publish access to @spring-payments. Keep npm credentials in the maintainer/build environment only. With release authorization, publish the exact inspected tarball (replace the version in its filename):
npm publish ./spring-payments-payments-js-0.2.0.tgz --access public --registry=https://registry.npmjs.org/
npm view @spring-payments/[email protected] version license dist.integrity --registry=https://registry.npmjs.org/For a preview release, use a prerelease version and --tag next; do not move latest inadvertently. After registry verification, install the published version in the web demo, regenerate its lockfile and update the partner installation guide. Publishing npm does not deploy the Gateway or documentation site.
