import {z} from 'zod' export type ExtraData = {[key: string]: string}; export type PspPassthroughData = {[key: string]: string}; export type Date = string; export type Country = string; export type IbanData = {ibanData?: ({iban?: string | undefined, bic?: string | undefined, mandateId?: string | undefined, mandateDate?: Date | undefined}) | undefined}; export type WalletData = {walletData?: ({walletReferenceId?: string | undefined, walletOwner?: string | undefined, walletType?: string | undefined}) | undefined}; export type PaymentData = IbanData | WalletData; export type Customer = {identification?: string | undefined, firstName?: string | undefined, lastName?: string | undefined, birthDate?: Date | undefined, gender?: ('M' | 'F') | undefined, billingAddress1?: string | undefined, billingAddress2?: string | undefined, billingCity?: string | undefined, billingPostcode?: string | undefined, billingState?: string | undefined, billingCountry?: Country | undefined, billingPhone?: string | undefined, shippingFirstName?: string | undefined, shippingLastName?: string | undefined, shippingCompany?: string | undefined, shippingAddress1?: string | undefined, shippingAddress2?: string | undefined, shippingCity?: string | undefined, shippingPostcode?: string | undefined, shippingState?: string | undefined, shippingCountry?: Country | undefined, shippingPhone?: string | undefined, company?: string | undefined, email?: string | undefined, emailVerified?: boolean | undefined, ipAddress?: string | undefined, nationalId?: string | undefined, extraData?: ExtraData | undefined, paymentData?: PaymentData | undefined}; export type Amount = string; export type Currency = string; export type DateTimeZone = string; export type Schedule = {amount: Amount, currency: Currency, periodLength: number, periodUnit: 'DAY' | 'WEEK' | 'MONTH' | 'YEAR', startDateTime?: DateTimeZone | undefined, merchantMetaData?: string | undefined, callbackUrl?: string | undefined}; export type CustomerProfileData = {profileGuid?: string | undefined, customerIdentification?: string | undefined, paymentToken?: string | undefined, markAsPreferred?: boolean | undefined}; export type DateTime = string; export type ThreeDSecureData = {'3dsecure'?: ('OFF' | 'OPTIONAL' | 'MANDATORY') | undefined, schemeId?: ('CB' | 'Eftpos') | undefined, channel?: ('01' | '02' | '03') | undefined, authenticationIndicator?: ('01' | '02' | '03' | '04' | '05' | '06') | undefined, cardholderAuthenticationMethod?: ('01' | '02' | '03' | '04' | '05' | '06') | undefined, cardholderAuthenticationDateTime?: DateTime | undefined, cardHolderAuthenticationData?: string | undefined, challengeIndicator?: ('01' | '02' | '03' | '04' | '05' | '06' | '07' | '08' | '09') | undefined, priorReference?: string | undefined, priorAuthenticationMethod?: ('01' | '02' | '03' | '04') | undefined, priorAuthenticationDateTime?: DateTime | undefined, priorAuthenticationData?: string | undefined, cardholderAccountType?: ('01' | '02' | '03' | '04') | undefined, cardholderAccountAgeIndicator?: ('01' | '02' | '03' | '04' | '05') | undefined, cardholderAccountDate?: Date | undefined, cardholderAccountChangeIndicator?: ('01' | '02' | '03' | '04') | undefined, cardholderAccountLastChange?: Date | undefined, cardholderAccountPasswordChangeIndicator?: ('01' | '02' | '03' | '04' | '05') | undefined, cardholderAccountLastPasswordChange?: Date | undefined, shippingAddressUsageIndicator?: ('01' | '02' | '03' | '04') | undefined, shippingAddressFirstUsage?: Date | undefined, transactionActivityDay?: number | undefined, transactionActivityYear?: number | undefined, addCardAttemptsDay?: number | undefined, purchaseCountSixMonths?: number | undefined, suspiciousAccountActivityIndicator?: ('01' | '02') | undefined, shippingNameEqualIndicator?: ('01' | '02') | undefined, paymentAccountAgeIndicator?: ('01' | '02' | '03' | '04' | '05') | undefined, paymentAccountAgeDate?: Date | undefined, billingAddressLine3?: string | undefined, shippingAddressLine3?: string | undefined, billingShippingAddressMatch?: ('Y' | 'N') | undefined, homePhoneCountryPrefix?: string | undefined, homePhoneNumber?: string | undefined, mobilePhoneCountryPrefix?: string | undefined, mobilePhoneNumber?: string | undefined, workPhoneCountryPrefix?: string | undefined, workPhoneNumber?: string | undefined, purchaseInstalData?: number | undefined, shipIndicator?: ('01' | '02' | '03' | '04' | '05' | '06' | '07') | undefined, deliveryTimeframe?: ('01' | '02' | '03' | '04') | undefined, deliveryEmailAddress?: string | undefined, reorderItemsIndicator?: ('01' | '02') | undefined, preOrderPurchaseIndicator?: ('01' | '02') | undefined, preOrderDate?: Date | undefined, giftCardAmount?: number | undefined, giftCardCurrency?: Currency | undefined, giftCardCount?: number | undefined, purchaseDate?: DateTime | undefined, recurringExpiry?: Date | undefined, recurringFrequency?: number | undefined, transType?: ('01' | '03' | '10' | '11' | '28') | undefined, exemptionIndicator?: ('01' | '02' | '03' | '04' | '05' | '06' | '07') | undefined, threeRIIndicator?: ('01' | '02' | '03' | '04' | '05' | '06' | '07' | '08' | '09' | '10' | '11' | '12') | undefined, browserChallengeWindowSize?: ('01' | '02' | '03' | '04' | '05') | undefined, browserAcceptHeader?: string | undefined, browserIpAddress?: string | undefined, browserJavaEnabled?: boolean | undefined, browserLanguage?: string | undefined, browserColorDepth?: (number | '1' | '4' | '8' | '15' | '16' | '24' | '30' | '32' | '48') | undefined, browserScreenHeight?: (number | string) | undefined, browserScreenWidth?: (number | string) | undefined, browserTimezone?: (number | string) | undefined, browserUserAgent?: string | undefined, browserPlatform?: string | undefined, sdkInterface?: ('01' | '02' | '03') | undefined, sdkUiType?: string | undefined, sdkAppID?: string | undefined, sdkEncData?: string | undefined, sdkEphemPubKey?: string | undefined, sdkMaxTimeout?: number | undefined, sdkReferenceNumber?: string | undefined, sdkTransID?: string | undefined}; export type PayByLink = {sendByEmail?: boolean | undefined, expirationInMinute?: number | undefined}; export type TaxDetails = Array<{type?: string | undefined, amount?: Amount | undefined, rate?: Amount | undefined, code?: string | undefined, taxId?: string | undefined, applied?: string | undefined, exemptionCode?: string | undefined}>; export type L2L3Data = {taxAmount?: Amount | undefined, vatRegistrationNumber?: string | undefined, nationalTaxIncluded?: string | undefined, discountAmount?: Amount | undefined, commodityCode?: string | undefined, freightAmount?: Amount | undefined, freightTaxAmount?: Amount | undefined, dutyAmount?: Amount | undefined, taxDetails?: TaxDetails | undefined}; export type PrepareRegisterRequest = {merchantTransactionId?: string | undefined, additionalId1?: string | undefined, additionalId2?: string | undefined, extraData?: ExtraData | undefined, pspPassthroughData?: PspPassthroughData | undefined, merchantMetaData?: string | undefined, successUrl?: string | undefined, cancelUrl?: string | undefined, errorUrl?: string | undefined, callbackUrl?: string | undefined, transactionToken?: string | undefined, description?: string | undefined, transactionIndicator?: ('SINGLE' | 'INITIAL' | 'RECURRING' | 'FIRST-CARDONFILE' | 'CARDONFILE' | 'CARDONFILE-MERCHANT-INITIATED' | 'MOTO') | undefined, customer?: Customer | undefined, schedule?: Schedule | undefined, customerProfileData?: CustomerProfileData | undefined, threeDSecureData?: ThreeDSecureData | undefined, payByLink?: PayByLink | undefined, language?: string | undefined, l2l3Data?: L2L3Data | undefined}; export type CreateApiTransactionApiKeyPrepareRegisterArgs = {apiKey: string, body: PrepareRegisterRequest}; export type CreateApiTransactionApiKeyPrepareRegisterOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const prepareRegisterResponse = z.object({success: z.boolean().optional(), error: z.string().optional()}).and(z.record(z.string(), z.unknown())); 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 }; /** * Process a prepare Register * * POST /transaction/{apiKey}/prepare-register */ export const createApiTransactionApiKeyPrepareRegister = async (args: CreateApiTransactionApiKeyPrepareRegisterArgs, options?: CreateApiTransactionApiKeyPrepareRegisterOptions) => { const {baseUrl = "https://gateway.tillpayments.com/api/v3", 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 (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/transaction/${encodeURIComponent(String(args.apiKey))}/prepare-register${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(prepareRegisterResponse, await res.json()) };