import {z} from 'zod' export type OrderReference = string; export type TransactionReference = string; export type Merchant = {entity: string, overrideName?: string | undefined, acquirerId?: string | undefined}; export type Value = {amount: number, currency: string}; export type CardHolderName = string; export type BillingAddress = {address1: string, address2?: string | undefined, address3?: string | undefined, city: string, state?: string | undefined, postalCode: string, countryCode: string}; export type CardFront = {type: unknown, cardHolderName?: CardHolderName | undefined, expiryDate: {month: number, year: number}, cardNumber: string, billingAddress?: BillingAddress | undefined}; export type CardTokenized = {type: unknown, href: string}; export type CardNetworktoken = {type: unknown, expiryDate: {month: number, year: number}, tokenNumber: string, cardHolderName?: CardHolderName | undefined, billingAddress?: BillingAddress | undefined}; export type GooglepayEncrypted = {type: 'googlepay/encrypted', walletToken: string, billingAddress?: BillingAddress | undefined}; export type DeviceData = {acceptHeader: string, userAgentHeader: string, browserLanguage?: string | undefined, ipAddress?: string | undefined, browserJavaEnabled?: boolean | undefined, browserColorDepth?: number | undefined, browserScreenHeight?: number | undefined, browserScreenWidth?: number | undefined, timeZone?: string | undefined, browserJavascriptEnabled?: boolean | undefined, channel?: ('browser' | 'native' | 'ucpBrowser') | undefined}; export type Customer = {firstName?: string | undefined, lastName?: string | undefined, phone?: string | undefined, email?: string | undefined}; export type Challenge = {preference?: ('noPreference' | 'noChallengeRequested' | 'challengeRequested' | 'challengeMandated' | 'noChallengeRequestedTRAPerformed') | undefined}; export type AccountHistory = {createdAt?: string | undefined, modifiedAt?: string | undefined, passwordModifiedAt?: string | undefined, paymentAccountEnrolledAt?: string | undefined}; export type TransactionHistory = {attemptsLastDay?: number | undefined, attemptsLastYear?: number | undefined, completedLastSixMonths?: number | undefined, addCardsLastDay?: number | undefined, shippingAddressFirstUsedAt?: string | undefined}; export type PaymentsGiftCardsPurchase = {totalValue?: Value | undefined, quantity?: number | undefined}; export type PaymentsShippingAddress = {address1: string, address2?: string | undefined, address3?: string | undefined, postalCode: string, city: string, stateCode?: string | undefined, countryCode: unknown}; export type Shipping = {nameMatchesAccountName?: boolean | undefined, method?: ('billingAddress' | 'verifiedAddress' | 'otherAddress' | 'store' | 'digital' | 'unshippedTickets' | 'other') | undefined, timeFrame?: ('electronic' | 'sameDay' | 'nextDay' | 'twoDaysPlus') | undefined, email?: string | undefined, phone?: string | undefined, firstName?: string | undefined, lastName?: string | undefined, address?: PaymentsShippingAddress | undefined}; export type Type3DSAuthenticateRequest = {orderReference: OrderReference, transactionReference: TransactionReference, merchant: Merchant, instruction: {value: Value, paymentInstrument: CardFront | CardTokenized | CardNetworktoken | GooglepayEncrypted}, deviceData: DeviceData, customer?: Customer | undefined, challenge?: Challenge | undefined, previousSuspiciousActivity?: boolean | undefined, userType?: ('guestUser' | 'registeredUser' | 'federatedAccount' | 'issuerCredentials' | 'thirdPartyAuthentication' | 'fidoAuthenticator') | undefined, accountHistory?: AccountHistory | undefined, reorder?: boolean | undefined, preOrderDate?: string | undefined, transactionHistory?: TransactionHistory | undefined, giftCardsPurchase?: PaymentsGiftCardsPurchase | undefined, shipping?: Shipping | undefined}; export type CreateApiAuthenticationsArgs = {'WP-Api-Version': '2026-10-01', body: Type3DSAuthenticateRequest}; export type CreateApiAuthenticationsOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const selfLink = z.object({href: z.string().optional()}); export const queryAuthenticationLink = z.object({href: z.string().optional()}); export const schema3DSAuthenticate200ResponseRedirect = z.object({outcome: z.literal("3dsRedirect").optional(), authenticationId: z.string().optional(), redirect: z.string().optional(), _links: z.object({self: selfLink.optional(), queryAuthentication: queryAuthenticationLink.optional()}).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Authentication * * POST /authentications */ export const createApiAuthentications = async (args: CreateApiAuthenticationsArgs, options?: CreateApiAuthenticationsOptions) => { const {baseUrl = "https://try.access.worldpay.com/3ds", fetch: fetchFn = fetch, BasicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['WP-Api-Version'] != null) headers.set("WP-Api-Version", String(args['WP-Api-Version'])) if (BasicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${BasicAuth.username}:${BasicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/authentications${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(schema3DSAuthenticate200ResponseRedirect, await res.json()) };