import {z} from 'zod' export type CaptureMode = 'Auto' | 'Manual'; export type Money = {value: number, currencyCode: string}; export type PaymentCustomerDetails = {id?: (string | null) | undefined, name?: (string | null) | undefined, emailAddress?: (string | null) | undefined, phoneNumber?: (string | null) | undefined, secret?: (string | null) | undefined, savedCardId?: (string | null) | undefined}; export type Address = {address1?: (string | null) | undefined, address2?: (string | null) | undefined, address3?: (string | null) | undefined, address4?: (string | null) | undefined, city?: (string | null) | undefined, state?: (string | null) | undefined, postcode?: (string | null) | undefined, countryCode: string, locality?: (string | null) | undefined, county?: (string | null) | undefined}; export type ShippingDetails = {name?: (string | null) | undefined, deliveryNotes?: (string | null) | undefined, address?: (Address | null) | undefined}; export type CardHolderNotPresent = boolean | null; export type PaymentIntentConfigCustomerEmail = {collectionRequired?: boolean | undefined}; export type PaymentIntentConfigDetails = {showTotal?: boolean | undefined, showReference?: boolean | undefined}; export type PaymentIntentConfigBillingAddress = {collectionRequired?: boolean | undefined}; export type PaymentIntentConfigShippingDetails = {collectionRequired?: boolean | undefined}; export type PaymentConfigDetails = {customAmountAllowed?: boolean | undefined, tipsAllowed?: boolean | undefined}; export type PaymentIntentConfigRequest = {title?: (string | null) | undefined, redirectUrl?: (string | null) | undefined, cancelUrl?: (string | null) | undefined, customerEmail?: (PaymentIntentConfigCustomerEmail | null) | undefined, details?: (PaymentIntentConfigDetails | null) | undefined, billingAddress?: (PaymentIntentConfigBillingAddress | null) | undefined, shippingDetails?: (PaymentIntentConfigShippingDetails | null) | undefined, payment?: (PaymentConfigDetails | null) | undefined}; export type RequestSecurity = {userAgent?: (string | null) | undefined, ipAddress?: (string | null) | undefined, device?: (string | null) | undefined}; export type Modifier = {name: string, amountPerModifier: Money, quantity: number, id: string}; export type ItemLine = {id?: string | undefined, quantity?: number | undefined, name?: string | undefined, category?: string | undefined, modifiers?: Array | undefined, amountTotal: Money | null, plu?: string | undefined}; export type TaxLine = {id?: string | undefined, caption?: string | undefined, subCaption?: (string | null) | undefined, amountTotal: Money, affectedPlu?: string | undefined}; export type PaymentMethod = string; export type ActionType = 'OpenLink' | 'DownloadFile'; export type ActionLink = {url: string, action?: ActionType | undefined, label: string, fileName?: (string | null) | undefined}; export type AutoExpireAction = 'Release' | 'Capture'; export type OrderDetails = {availabilityDate?: (string | null) | undefined, isUpdate?: (boolean | null) | undefined, id?: (string | null) | undefined, externalId?: (string | null) | undefined}; export type CreatePaymentIntentRequest = {captureMode?: CaptureMode | undefined, amount: Money, tipsAmount?: (Money | null) | undefined, reference: string, description?: (string | null) | undefined, customer?: (PaymentCustomerDetails | null) | undefined, billingAddress?: (Address | null) | undefined, shippingDetails?: (ShippingDetails | null) | undefined, cardHolderNotPresent?: CardHolderNotPresent | undefined, config?: (PaymentIntentConfigRequest | null) | undefined, requestSecurity?: (RequestSecurity | null) | undefined, itemLines?: (Array | null) | undefined, taxLines?: (Array | null) | undefined, paymentMethods?: (Array | null) | undefined, actionLink?: (ActionLink | null) | undefined, expireAt?: (string | null) | undefined, autoExpireIn?: (unknown | null) | undefined, autoExpireAction?: (AutoExpireAction | null) | undefined, metadata?: ({[key: string]: string} | null) | undefined, setupIntentId?: (string | null) | undefined, orderDetails?: (OrderDetails | null) | undefined, cashbackAmount?: (Money | null) | undefined, serviceChargeAmount?: (Money | null) | undefined, generateRemoteToken?: boolean | undefined, isNotOnlineCheckout?: boolean | undefined}; export type CreateApiPaymentIntentsArgs = {version: string, body: CreatePaymentIntentRequest}; export type CreateApiPaymentIntentsOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const captureMode = z.enum(["Auto", "Manual"]); export const cardFundingType = z.string(); export const terminalSessionPaymentEntryMode = z.string(); export const terminalSessionPaymentVerificationMode = z.string(); export const card = z.object({cardNumber: z.string().nullable().optional(), cardName: z.string().nullable().optional(), expiryDate: z.string().nullable().optional(), cardType: z.string().nullable().optional(), cardFundingType: cardFundingType.optional(), last4PAN: z.string().nullable().optional(), entryMode: terminalSessionPaymentEntryMode.optional(), verificationMethod: terminalSessionPaymentVerificationMode.optional()}); export const paymentDetails = z.object({transactionId: z.string().nullable().optional(), transactionDateTime: z.string().nullable().optional(), message: z.string().nullable().optional(), paymentMethodId: z.string().nullable().optional(), authCode: z.string().nullable().optional(), card: card.nullable().optional(), avsResult: z.string().nullable().optional()}); export const paymentIntentStatus = z.enum(["Created", "Authorized", "Captured", "Reversed", "Refunded", "Canceled"]); export const paymentMethod = z.string(); export const money = z.object({value: z.number().int(), currencyCode: z.string().min(1).max(10)}); export const customer = z.object({id: z.string().nullable().optional(), name: z.string().max(256).nullable().optional(), emailAddress: z.string().max(254).nullable().optional(), phoneNumber: z.string().max(50).nullable().optional()}); export const requestSecurity = z.object({userAgent: z.string().max(300).nullable().optional(), ipAddress: z.string().max(70).nullable().optional(), device: z.string().max(120).nullable().optional()}); export const address = z.object({address1: z.string().max(100).nullable().optional(), address2: z.string().max(100).nullable().optional(), address3: z.string().max(100).nullable().optional(), address4: z.string().max(100).nullable().optional(), city: z.string().max(100).nullable().optional(), state: z.string().max(100).nullable().optional(), postcode: z.string().max(50).nullable().optional(), countryCode: z.string().max(10), locality: z.string().max(100).nullable().optional(), county: z.string().max(100).nullable().optional()}); export const shippingDetails = z.object({name: z.string().max(100).nullable().optional(), deliveryNotes: z.string().max(1024).nullable().optional(), address: address.nullable().optional()}); export const modifier = z.object({name: z.string(), amountPerModifier: money, quantity: z.number().int(), id: z.string()}); export const itemLine = z.object({id: z.string().max(60).optional(), quantity: z.number().int().optional(), name: z.string().max(100).optional(), category: z.string().optional(), modifiers: z.array(modifier).optional(), amountTotal: money.nullable(), plu: z.string().max(200).optional()}); export const taxLine = z.object({id: z.string().max(60).optional(), caption: z.string().max(100).optional(), subCaption: z.string().max(100).nullable().optional(), amountTotal: money, affectedPlu: z.string().max(200).optional()}); export const actionType = z.enum(["OpenLink", "DownloadFile"]); export const actionLink = z.object({url: z.string().min(1), action: actionType.optional(), label: z.string().min(1).max(60), fileName: z.string().max(256).nullable().optional()}); export const cardScheme = z.string(); export const walletPaymentOption = z.string(); export const supportedPaymentMethods = z.object({cardSchemes: z.array(cardScheme).nullable().optional(), wallets: z.array(walletPaymentOption).nullable().optional()}); export const merchantConfig = z.object({supportedPaymentMethods: supportedPaymentMethods.nullable().optional()}); export const paymentIntentConfigCustomerEmail = z.object({collectionRequired: z.boolean().optional()}); export const paymentIntentConfigDetails = z.object({showTotal: z.boolean().optional(), showReference: z.boolean().optional()}); export const paymentIntentConfigBillingAddress = z.object({collectionRequired: z.boolean().optional()}); export const paymentIntentConfigShippingDetails = z.object({collectionRequired: z.boolean().optional()}); export const paymentConfigDetails = z.object({customAmountAllowed: z.boolean().optional(), tipsAllowed: z.boolean().optional()}); export const paymentIntentConfigResponse = z.object({title: z.string().max(100).nullable().optional(), redirectUrl: z.string().nullable().optional(), cancelUrl: z.string().nullable().optional(), customerEmail: paymentIntentConfigCustomerEmail.nullable().optional(), details: paymentIntentConfigDetails.nullable().optional(), billingAddress: paymentIntentConfigBillingAddress.nullable().optional(), shippingDetails: paymentIntentConfigShippingDetails.nullable().optional(), payment: paymentConfigDetails.nullable().optional()}); export const autoExpireAction = z.enum(["Release", "Capture"]); export const orderDetails = z.object({availabilityDate: z.string().nullable().optional(), isUpdate: z.boolean().nullable().optional(), id: z.string().nullable().optional(), externalId: z.string().nullable().optional()}); export const terminalSessionStatus = z.enum(["InitiateRequested", "Initiated", "Authorized", "Captured", "CancelRequested", "Canceled", "SignatureVerificationAccepted", "SignatureVerificationRejected", "SignatureVerificationRequired", "Expired", "Declined"]); export const terminalSessionNotificationType = z.string(); export const terminalSessionNotification = z.object({notificationType: terminalSessionNotificationType.optional(), createdAt: z.string().optional()}); export const terminalSessionStatusEvent = z.object({status: terminalSessionStatus, createdAt: z.string(), debugMessage: z.string()}); export const terminalSessionUnlinkedRefundDetails = z.object({amount: money, cardholderNotPresent: z.boolean().optional()}); export const terminalSessionMatchedRefundDetails = z.object({paymentIntentId: z.string(), amount: money.optional()}); export const terminalSessionSaleDetails = z.object({paymentIntentId: z.string()}); export const terminalSessionType = z.enum(["Sale", "MatchedRefund", "UnlinkedRefund"]); export const terminalSessionDetails = z.union([z.object({unlinkedRefund: terminalSessionUnlinkedRefundDetails.optional(), matchedRefund: terminalSessionMatchedRefundDetails.optional(), sale: terminalSessionSaleDetails, sessionType: terminalSessionType}), z.object({unlinkedRefund: terminalSessionUnlinkedRefundDetails, matchedRefund: terminalSessionMatchedRefundDetails.optional(), sale: terminalSessionSaleDetails.optional(), sessionType: terminalSessionType}), z.object({unlinkedRefund: terminalSessionUnlinkedRefundDetails.optional(), matchedRefund: terminalSessionMatchedRefundDetails, sale: terminalSessionSaleDetails.optional(), sessionType: terminalSessionType})]); export const terminalSessionResponse = z.object({terminalId: z.string().nullable().optional(), id: z.string().nullable().optional(), status: terminalSessionStatus.optional(), expireAt: z.string().optional(), createdAt: z.string().optional(), updatedAt: z.string().optional(), notificationEvents: z.array(terminalSessionNotification).nullable().optional(), statusEvents: z.array(terminalSessionStatusEvent).nullable().optional(), details: terminalSessionDetails.nullable().optional()}); export const terminalSessionPaymentResponse = z.object({transactionDateTime: z.string().nullable().optional(), cardNumber: z.string().nullable().optional(), expiryDate: z.string().nullable().optional(), cardType: z.string().nullable().optional(), authGatewayTransactionId: z.string().nullable().optional(), cardHolderName: z.string().nullable().optional(), entryMode: terminalSessionPaymentEntryMode.optional(), verificationMode: terminalSessionPaymentVerificationMode.optional()}); export const terminalSessionHistoryResponse = z.object({terminalSession: terminalSessionResponse.nullable().optional(), payment: terminalSessionPaymentResponse.nullable().optional()}); export const captureStatus = z.enum(["Created", "Successful", "Declined", "Failed"]); export const captureDetails = z.object({id: z.string().nullable().optional(), amount: z.number().int().optional(), tipsAmount: z.number().int().nullable().optional(), status: captureStatus.optional(), createdAt: z.string().optional()}); export const paymentIntent = z.object({id: z.string().nullable().optional(), captureMode: captureMode.optional(), cardHolderNotPresent: z.boolean().optional(), clientSessionSecret: z.string().nullable().optional(), clientSessionSecretExpirationDate: z.string().optional(), paymentDetails: paymentDetails.nullable().optional(), status: paymentIntentStatus.optional(), paymentMethods: z.array(paymentMethod).nullable().optional(), amount: money.nullable().optional(), tipsAmount: money.nullable().optional(), requestedAmount: money.nullable().optional(), totalAmount: money.nullable().optional(), refundedAmount: z.number().int().nullable().optional(), customer: customer.nullable().optional(), requestSecurity: requestSecurity.nullable().optional(), billingAddress: address.nullable().optional(), shippingDetails: shippingDetails.nullable().optional(), createdAt: z.string().optional(), updatedAt: z.string().optional(), reference: z.string().nullable().optional(), description: z.string().nullable().optional(), subtotalLineItems: money.nullable().optional(), itemLines: z.array(itemLine).nullable().optional(), taxLines: z.array(taxLine).nullable().optional(), actionLink: actionLink.nullable().optional(), merchantConfig: merchantConfig.nullable().optional(), config: paymentIntentConfigResponse.nullable().optional(), autoExpireAction: autoExpireAction.nullable().optional(), expireAt: z.string().nullable().optional(), autoExpireIn: z.string().nullable().optional(), metadata: z.record(z.string(), z.string()).nullable().optional(), orderDetails: orderDetails.nullable().optional(), setupIntentId: z.string().nullable().optional(), cashbackAmount: money.nullable().optional(), serviceChargeAmount: money.nullable().optional(), paymentLink: z.string().nullable().optional(), terminalSessionHistory: z.array(terminalSessionHistoryResponse).nullable().optional(), captures: z.array(captureDetails).nullable().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 }; /** * Create a payment intent * * POST /payment-intents */ export const createApiPaymentIntents = async (args: CreateApiPaymentIntentsArgs, options?: CreateApiPaymentIntentsOptions) => { const {baseUrl = "https://api.dojo.tech", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.version != null) headers.set("version", String(args.version)) if (ApiKeyAuth !== undefined) headers.set("Authorization", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/payment-intents${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(paymentIntent, await res.json()) };