Skip to content

API reference

Every export, option, method, type, state and error code of @wajub/js.

The complete surface of @wajub/js@1.4.0. The guide pages explain when to use each piece. This one lists all of them.

Two ways to reach the same API

The runtime is one object. You either import helpers that load it for you, or you hold it yourself.

Helpers, or the runtime
import { mount, open, checkout, components, confirmPayment } from '@wajub/js';

import { loadWajub } from '@wajub/js/pure';
const rt = await loadWajub();
rt?.wajub.mount('#checkout', { sessionId });
Export from @wajub/jsReturnsNotes
mount(container, config)Promise<CheckoutInstance | null>null on the server
open(config)Promise<PopupInstance | null>null on the server
checkout(config)Promise<void | null>Redirects the page
components(sessionId, options?)Promise<ComponentsFactory | null>null on the server
confirmPayment(options)Promise<{ status, transaction? }>Rejects with WajubError
fetchSession(sessionId)Promise<SessionPreview>Works before anything is mounted
preload(sessionId, options?)Promise<void | null>{ iframe?: boolean }
getVersion()Promise<string | null>The loaded runtime version
getCheckoutOrigin()Promise<string | null>Where the checkout is served from
loadWajub(options?)Promise<WajubRuntime | null>{ jsOrigin?, jsUrl? }
WajubErrorClassEvery rejection is an instance of it

loadWajub.setLoadParameters({ jsOrigin }) sets the origin once, before the first call.

WajubRuntime

What loadWajub() resolves to, and what the CDN script puts on window.

MemberWhat it is
wajubThe SDK object, the table below
WajubThe client factory
WajubErrorThe error class

wajub

MemberSignature
mount(container, config) => CheckoutInstance
open(config) => PopupInstance
checkout(config) => void
components(sessionId, options?) => ComponentsFactory
confirmPayment(options) => Promise<{ status }>
fetchSession(sessionId) => Promise<SessionPreview>
preload(sessionId, options?) => void
createThe Wajub factory, same object
versionThe runtime version string
sdkMajorThe major version
checkoutOriginThe origin the iframes come from
createHeadlessRemoved in 2.1, throws when called

These are synchronous, because the runtime is already loaded by the time you hold it.

Wajub() client

A client holds a publishable key, a session, or both, so you stop repeating them.

CallWhat you get
Wajub('pk_test.…')A client that can createPayment()
Wajub.session(token)A client bound to an existing session
Wajub({ publishableKey, sessionId })Both at once
OptionWhat it does
sessionIdThe authorization_token from your server
publishableKeyYour pk. or pk_test. key
apiKeyDeprecated alias for publishableKey
apiBaseAPI origin override, defaults to https://api.wajub.com
paymentsUrlFull POST /payments URL override
useCheckoutProxyRoute through the checkout's own /api/payments
componentOriginCanonical origin for payment fields

Client members

MemberWhat it does
publishableKey, sessionId, environmentWhat the client currently holds
apiBase, checkoutOriginWhere it talks
useSession(sessionId)Binds another session, returns the client
createPayment(params)POST /payments with the publishable key
initCheckout(options)Creates the payment and shows it in one call
fetchSession(sessionId?)Session preview
preload(sessionId?, options?)Warms the runtime
mount, open, checkoutThe three hosted modes, session already bound
components(sessionIdOrConfig?, config?)The fields factory
confirmPayment(options?)Submits a mounted component

Factory statics

MemberWhat it does
Wajub.session(sessionId, options?)A session bound client
Wajub.parsePublishableKey(key){ key, environment }, throws on a secret key
Wajub.createPayment(key, params, options?)One shot, no client to keep

EmbeddedConfig

Used by mount(), by CheckoutEmbed in every framework, and as the base of PopupConfig.

OptionTypeDefault
sessionIdstringRequired
localestringSession default
layoutCheckoutLayoutSession default
appearanceAppearanceConfigSession branding
embedOriginstringThe current page origin
loadingTextstringEmpty
showLoadingbooleantrue
themeEmbedThemeDerived from appearance, deprecated
CallbackReceives
onReadyCheckoutInstance
onSuccessRecord<string, unknown>, the transaction
onErrorWajubError
onLoadErrorWajubError
onCancelNothing
onExpiredNothing
onStateChange{ state?: CheckoutState, method?: string }
onMethodChange{ methodId?, method_id? }
onBreakdownEmbedBreakdown
onResizeheight: number, inline only
onCloseNothing, overlay only

PopupConfig

Everything in EmbeddedConfig, plus the modal.

OptionTypeDefault
widthnumber920
heightnumber680
closeOnOverlaybooleanfalse
closeOnEscapebooleantrue
closeOnSuccessbooleantrue
closeOnCancelbooleantrue
closeOnExpiredbooleantrue

The three closeOn outcome flags run after your callback, never before it.

CheckoutInstance and PopupInstance

MethodWhat it does
mount()Re-attaches after unmount()
unmount()Removes from the DOM, keeps the instance
destroy()Full teardown
update(partial)locale, appearance, currency, layout, deprecated theme
getState()The current CheckoutState
submit()Submits the form
cancel()Cancels the payment in progress
retry()Retries after a failure
selectMethod(methodId)Switches payment method
close()Closes the overlay
isOpen()Overlay only, whether the modal is visible

ComponentConfig

Passed to wajub.components(sessionId, options) as defaults, and to factory.create(type, config) per component.

OptionTypeApplies to
sessionIdstringRequired
localestringAll
appearanceAppearanceConfigAll
layoutCheckoutLayoutpayment
componentOriginstringAll, defaults to the page origin
collectAddressshipping or billingpayment
addressModeshipping or billingaddress
collectNamebooleanpayment, address
fields.phonealways, auto, neverpayment, address
CallbackReceives
onReadyComponentInstance
onChangeComponentChangeEvent
onFocus, onBlurNothing
onLoadErrorWajubError
onSuccessThe transaction
onErrorWajubError
onMethodChange{ methodId? }

ComponentsFactory

MemberWhat it is
sessionIdThe session every component inherits
create(type, config?)A new ComponentInstance

Types. card, mobileMoney, wallet, payment, address.

ComponentInstance

Every method except the readers returns the instance, so calls chain.

MethodReturns
mount(container)The instance
unmount(), destroy()Nothing
on(event, fn), off(event, fn)The instance
update({ locale, appearance, layout })The instance
focus(), blur(), submit()The instance
selectMethod(methodId)The instance
getState()CheckoutState
isComplete()boolean
getError()WajubError or null
getValue()ComponentAddressValue or null

Events

EventPayload
readyComponentInstance
changeComponentChangeEvent
focus, blurNothing
loaderrorWajubError
resize{ height }
successThe transaction
errorWajubError
statechange{ state, method }
methodchange{ methodId }

ConfirmPaymentOptions

OptionTypeDefault
sessionIdstringRequired
componentsComponentInstanceRequired, one mounted component
timeoutnumber60000 milliseconds, 0 waits forever
callbackstringDeprecated, never read

Resolves with { status, transaction }. Rejects with a WajubError carrying missing_component, wallet_not_supported, address_not_payment or confirmation_timeout.

CreatePaymentParams

What client.createPayment() sends. The same fields as POST /payments, narrowed to what a browser may set.

FieldType
amountnumber, required
currencystring, required
referencestring
descriptionstring
customer{ email?, name?, phone?, country? }
bearermerchant or customer, who pays the fee
callbackHTTPS URL, redirect flow only
metadataRecord<string, string>

CreatePaymentResult

FieldWhat it is
sessionIdPass this to mount, open or components
authorizationTokenThe same value, under the API's name
authorizationUrlThe hosted page, or null
transactionThe transaction object, or null
rawThe untouched API response

InitCheckoutOptions

Creates the payment and shows it in one call. Everything in EmbeddedConfig applies too.

OptionTypeWhat it does
modeinline, overlay, redirectHow the checkout appears
containerstring or HTMLElementRequired for inline
sessionIdstringSkips createPayment()
paymentCreatePaymentParamsUsed when there is no sessionId
checkoutPartial<EmbeddedConfig>Options for the embed itself

It resolves with { session, instance }, and throws missing_container when inline has nowhere to go.

SessionPreview

What fetchSession(sessionId) resolves to. Read it before mounting to show an amount, a merchant name, or a sandbox banner.

FieldType
session_idstring
statusstring
environmentsandbox or live
amountnumber
currencystring
merchant_namestring
payment_methodsArray<{ id, type, label }>
saved_methodsArray<{ id, type, label }>, returning customers
featuresRecord<string, boolean>

AppearanceConfig

The full key list, the presets and the filtering rules are on Appearance.

GroupKeys
Presettheme: stripe, night, flat, none
ColourprimaryColor, secondaryColor, backgroundColor, buttonTextColor, inputBackgroundColor, inputBorderColor, textMutedColor, successColor, errorColor
ShapefontFamily, borderRadius, shadow
BehaviourcolorScheme, labels, disableAnimations
Tokensvariables, sixteen keys mapped to --wj-*
Selectorsrules, .Input and .Label only

States

getState() and onStateChange both speak this vocabulary.

CheckoutState
INITIATED → COLLECTING_DETAILS → PROCESSING → SUCCESS
                                ↘ OTP_REQUIRED, 3DS_REQUIRED, USSD_REQUIRED
                                ↘ APPROVAL_REQUIRED, VERIFYING, PENDING
                                ↘ FAILED, CANCELLED, EXPIRED

A new instance reports INITIATED until the checkout says otherwise.

WajubError

Every rejection and every error callback receives one.

FieldType
messagestring, written for a human
typeapi_error, authentication_error, invalid_request_error, payment_error, rate_limit_error
codestring, the machine name
decline_codestring or null, from the provider
retryableboolean
paramstring or null, the field at fault

WajubError.fromPayload(payload) builds one from a raw object, and toJSON() gives it back.

Codes raised by the SDK itself

These never reach the network. They are integration mistakes.

CodeCause
secret_key_in_browserA sk. key passed to Wajub()
invalid_publishable_keyA key that is not a publishable key
invalid_initA secret key passed to the client constructor
missing_publishable_keycreatePayment() without a key
missing_session_tokenA call that needs a session and has none
missing_sessionNo sessionId on the client
missing_containerinitCheckout in inline mode with nowhere to mount
missing_componentconfirmPayment without a submittable component
wallet_not_supportedconfirmPayment on a wallet component
address_not_paymentconfirmPayment on an address component
confirmation_timeoutNo outcome within timeout
components_unavailableThe components runtime did not load
load_errorThe checkout iframe failed to load

Framework packages

The three wrappers export the same set, with the idioms of each framework.

ExportWhat it is
WajubProviderLoads the runtime once for a subtree
CheckoutEmbedThe hosted checkout, inline
CardComponent, MobileMoneyComponent, WalletComponent, PaymentComponent, AddressComponentOne field group each
ComponentEmbedThe same, with type as a prop
useWajub, useWajubOptional, useLoadWajubReach the runtime
useConfirmPaymentSubmit a field component
Wrapper propApplies toDefault
className in React and Svelte, class in VueBothnone
styleBothnone
minHeightCheckoutEmbed480
minHeightField components200
onInstanceField componentsnone, fires with null on unmount

Each package has its own page, because the differences are real: React, Vue, Svelte.

What did you think of this content?