import {z} from 'zod' export type ExtraData = {[key: string]: string}; export type PspPassthroughData = {[key: string]: string}; export type Amount = string; export type Currency = string; 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 Items = Array<{identification?: string | undefined, name?: string | undefined, description?: string | undefined, quantity?: (number | string) | undefined, price?: (number | string) | undefined, currency?: Currency | undefined, l2l3Data?: ({type?: string | undefined, unit?: string | undefined, unitPrice?: Amount | undefined, discount?: Amount | undefined, discountRate?: Amount | undefined, shippingAmount?: Amount | undefined, taxAmount?: Amount | undefined, taxRate?: Amount | undefined, commodityCode?: string | undefined, taxDetails?: TaxDetails | undefined}) | undefined, extraData?: ExtraData | undefined}>; export type Splits = Array<{identification?: string | undefined, amount?: Amount | undefined, currency?: Currency | undefined, sellerMerchantGuid?: string | undefined, sellerMerchantExternalId?: string | undefined, commissionFee?: ({amount?: Amount | undefined, currency?: Currency | undefined}) | undefined}>; 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 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 DccData = {remoteIdentifier?: string | undefined, originalAmount?: Amount | undefined, originalCurrency?: Currency | undefined, convertedAmount?: Amount | undefined, convertedCurrency?: Currency | undefined, conversionRate?: number | undefined, selectedCurrency?: string | undefined, markUp?: number | 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 Preauthorize = {merchantTransactionId: string, additionalId1?: string | undefined, additionalId2?: string | undefined, captureInMinutes?: number | undefined, extraData?: ExtraData | undefined, pspPassthroughData?: PspPassthroughData | undefined, merchantMetaData?: string | undefined, referenceUuid?: string | undefined, amount: Amount, surchargeAmount?: Amount | undefined, currency: Currency, successUrl?: string | undefined, cancelUrl?: string | undefined, errorUrl?: string | undefined, callbackUrl?: string | undefined, transactionToken?: string | undefined, description?: string | undefined, items?: Items | undefined, splits?: Splits | undefined, withRegister?: boolean | 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, requestDcc?: boolean | undefined, dccData?: DccData | undefined, l2l3Data?: L2L3Data | undefined, referenceSchemeTransactionIdentifier?: string | undefined, includeTracing?: boolean | undefined, requestPartialAuthorization?: boolean | undefined}; export type CreateApiTransactionApiKeyPreauthorizeArgs = {apiKey: string, body: Preauthorize}; export type CreateApiTransactionApiKeyPreauthorizeOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const amount = z.string(); export const gstAmount = z.string(); export const country = z.string(); export const returnCardData = z.object({_TYPE: z.literal("cardData").optional(), type: z.string().optional(), firstName: z.string().optional(), lastName: z.string().optional(), country: country.optional(), cardHolder: z.string().optional(), expiryMonth: z.string().optional(), expiryYear: z.string().optional(), binDigits: z.string().optional(), firstSixDigits: z.string().optional(), lastFourDigits: z.string().optional(), fingerprint: z.string().optional(), binBrand: z.string().optional(), binBank: z.string().optional(), binType: z.string().optional(), binLevel: z.string().optional(), binCountry: z.string().optional(), binSegment: z.enum(["Consumer", "Business", "Commercial", "Government", "Unknown"]).optional(), binRawData: z.object({type: z.string().optional(), data: z.record(z.string(), z.unknown()).optional()}).optional(), threeDSecure: z.string().optional(), eci: z.string().optional(), merchantAdviceCode: z.string().optional(), parsedMerchantAdviceCode: z.string().optional(), schemeTransactionIdentifier: z.string().optional(), schemeLifecycleIdentifier: z.string().optional(), referenceSchemeLifecycleIdentifier: z.string().optional(), cardUpdateStatus: z.enum(["updated", "contact", "new-expiry", "closed"]).optional(), cardUpdatedAt: z.string().optional(), cardUpdatePausedUntil: z.string().optional()}); export const returnPhoneData = z.object({_TYPE: z.literal("phoneData").optional(), phoneNumber: z.string().optional(), country: country.optional(), operator: z.string().optional()}); export const date = z.string(); export const returnIbanData = z.object({_TYPE: z.literal("ibanData").optional(), accountOwner: z.string().optional(), iban: z.string().optional(), bic: z.string().optional(), mandateId: z.string().optional(), mandateDate: date.optional(), bankName: z.string().optional(), bankBranchName: z.string().optional(), country: country.optional()}); export const returnWalletData = z.object({_TYPE: z.literal("walletData").optional(), walletReferenceId: z.string().optional(), walletOwner: z.string().optional(), walletType: z.string().optional()}); export const returnData = z.discriminatedUnion("_TYPE", [returnCardData, returnPhoneData, returnIbanData, returnWalletData]); export const scheduleStatus = z.enum(["ACTIVE", "PAUSED", "CANCELLED", "ERROR", "CREATE-PENDING"]); export const dateTimeZone = z.string(); export const scheduleData = z.object({scheduleId: z.string().optional(), scheduleStatus: scheduleStatus.optional(), scheduledAt: dateTimeZone.optional(), merchantMetaData: z.string().optional()}); export const customerProfileData = z.object({profileGuid: z.string().optional(), customerIdentification: z.string().max(36).optional(), paymentToken: z.string().optional(), markAsPreferred: z.boolean().optional()}); export const extraData = z.record(z.string(), z.string()); export const currency = z.string(); export const transactionResponse = z.object({success: z.boolean().optional(), uuid: z.string().optional(), purchaseId: z.string().optional(), returnType: z.enum(["FINISHED", "REDIRECT", "HTML", "PENDING", "ERROR", "PENDING_DCC"]).optional(), redirectType: z.enum(["iframe", "fullpage", "3ds"]).optional(), redirectUrl: z.string().max(255).optional(), redirectQRCode: z.string().optional(), htmlContent: z.string().optional(), paymentDescriptor: z.string().optional(), paymentMethod: z.string().optional(), adapterMerchantTransactionId: z.string().min(1).max(64).optional(), amount: amount.optional(), surchargeAmount: amount.optional(), gstAmount: gstAmount.optional(), totalAmount: amount.optional(), returnData: returnData.optional(), scheduleData: scheduleData.optional(), customerProfileData: customerProfileData.optional(), riskCheckData: z.object({riskCheckResult: z.enum(["APPROVED", "DECLINED", "REVIEW"]).optional(), riskScore: z.number().optional(), threeDSecureRequired: z.boolean().optional()}).optional(), errors: z.array(z.object({errorMessage: z.string().optional(), errorCode: z.number().int().optional(), adapterMessage: z.string().optional(), adapterCode: z.string().optional()})).optional(), adapterMessage: z.string().optional(), adapterCode: z.string().optional(), extraData: extraData.optional(), dccData: z.object({uuid: z.string().optional(), originalAmount: amount.optional(), originalCurrency: currency.optional(), convertedAmount: amount.optional(), convertedCurrency: currency.optional(), conversionRate: z.number().optional(), disclaimer: z.string().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 }; /** * Process a preauthorize: reserves the payment amount on the customer's payment instrument * * POST /transaction/{apiKey}/preauthorize */ export const createApiTransactionApiKeyPreauthorize = async (args: CreateApiTransactionApiKeyPreauthorizeArgs, options?: CreateApiTransactionApiKeyPreauthorizeOptions) => { 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))}/preauthorize${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(transactionResponse, await res.json()) };