import {z} from 'zod' export type Reference = string; export type AmountMinor = number; export type Currency = unknown; export type CheckoutDescription = string; export type TimeSpan = unknown; export type PaymentMethodType = 'card' | 'sepa_direct_debit'; export type PaymentMethodBase = {type: PaymentMethodType}; export type CardScheme = 'visa' | 'mastercard'; export type CardPaymentMethodDescriptor = {type: PaymentMethodType, scheme: CardScheme}; export type PaymentMethodDescriptor = PaymentMethodBase | CardPaymentMethodDescriptor; export type CardDynamicDescriptor = string; export type CheckoutCardPaymentMethodOptions = {dynamic_descriptor: CardDynamicDescriptor}; export type SddRemittanceInfo = string; export type CheckoutSepaDirectDebitPaymentMethodOptions = {remittance_info: SddRemittanceInfo}; export type CheckoutPaymentMethodsOptions = {cards?: CheckoutCardPaymentMethodOptions | undefined, sepa_direct_debit?: CheckoutSepaDirectDebitPaymentMethodOptions | undefined}; export type CheckoutExplicitPaymentMethodsRequest = {type: string, available: Array, options?: CheckoutPaymentMethodsOptions | undefined}; export type CheckoutDefaultPaymentMethodsRequest = {type: string, options?: CheckoutPaymentMethodsOptions | undefined}; export type CheckoutPaymentMethodsRequest = CheckoutExplicitPaymentMethodsRequest | CheckoutDefaultPaymentMethodsRequest; export type SplitsType = 'per_transaction'; export type SplitsAccountType = 'platform' | 'seller' | 'other'; export type AccountId = string; export type SplitAmountMinor = number; export type SplitFixedAmount = {type: 'fixed' | 'percentage' | 'remaining', amount: SplitAmountMinor}; export type SplitPercentageAmountRequest = {type: 'fixed' | 'percentage' | 'remaining', percentage: number}; export type SplitRemainingAmountRequest = {type: 'fixed' | 'percentage' | 'remaining'}; export type ProcessingFeeRequest = {percentage: number}; export type SplitsRequest = {type: SplitsType, accounts: Array<{type: SplitsAccountType, id: AccountId, split: SplitFixedAmount | SplitPercentageAmountRequest | SplitRemainingAmountRequest, processing_fee?: ProcessingFeeRequest | undefined}>}; export type CheckoutBuyerAddress = {line1?: string | undefined, line2?: string | undefined, street_number?: string | undefined, city?: string | undefined, region?: string | undefined, postal_code?: string | undefined, country?: unknown | undefined}; export type BaseRegistrationNumber = {type: string, value: string}; export type GermanRegistrationNumber = {type: string, value: string, registry: string}; export type RegistrationNumber = BaseRegistrationNumber | GermanRegistrationNumber; export type CheckoutBuyerRequest = {first_name?: string | undefined, last_name?: string | undefined, email?: string | undefined, address?: CheckoutBuyerAddress | undefined, birth?: ({date?: string | undefined, place?: string | undefined}) | undefined, nationality?: unknown | undefined, business?: ({legal_name?: string | undefined, country?: unknown | undefined, registration_number?: RegistrationNumber | undefined}) | undefined}; export type StandingInstructionTerms = {type: 'recurring' | 'unscheduled'}; export type InitialStandingInstructionRequest = {terms: StandingInstructionTerms}; export type PaymentWebhooksRequest = {url: string}; export type CreateCheckoutRequest = {reference: Reference, amount: AmountMinor, currency: Currency, description: CheckoutDescription, expires_in?: TimeSpan | undefined, payment_methods?: CheckoutPaymentMethodsRequest | undefined, splits: SplitsRequest, buyer?: CheckoutBuyerRequest | undefined, standing_instruction?: InitialStandingInstructionRequest | undefined, redirect: {default: string, completed?: string | undefined, failed?: string | undefined}, integration?: {type: 'hosted', site_url: string} | undefined, webhooks?: PaymentWebhooksRequest | undefined}; export type CreateApiV2CheckoutsArgs = {'Getpaid-Idempotency-Key': string, body: CreateCheckoutRequest}; export type CreateApiV2CheckoutsOptions = {baseUrl?: string | undefined, OAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const checkoutId = z.string().min(30).max(50); export const checkoutStatus = z.enum(["initiated", "started", "in_progress", "completed", "failed", "unattempted"]); export const reference = z.string().min(1).max(50); export const createdAt = z.string().min(24).max(24); export const updatedAt = z.string().min(24).max(24); export const checkoutExpiresAt = z.string().min(24).max(24); export const checkoutFlow = z.object({next_step: z.object({type: z.literal("redirect"), url: z.string().max(1024)})}); export const paymentMethodType = z.enum(["card", "sepa_direct_debit"]); export const paymentMethodBase = z.object({type: paymentMethodType}); export const cardScheme = z.enum(["visa", "mastercard"]); export const cardPaymentMethodDescriptor = z.object({type: paymentMethodType, scheme: cardScheme}); export const paymentMethodDescriptor = z.discriminatedUnion("type", [paymentMethodBase, cardPaymentMethodDescriptor]); export const checkoutPaymentMethodsResponse = z.object({type: z.enum(["default", "explicit"]), available: z.array(paymentMethodDescriptor)}); export const splitsType = z.literal("per_transaction"); export const splitsAccountType = z.enum(["platform", "seller", "other"]); export const accountId = z.string().min(30).max(50); export const accountVersion = z.string().min(1).max(50); export const accountLegalName = z.string().min(1).max(250); export const splitAmountMinor = z.number().int(); export const splitFixedAmount = z.object({type: z.enum(["fixed", "percentage", "remaining"]), amount: splitAmountMinor}); export const splitPercentageAmountCalculated = z.object({type: z.enum(["fixed", "percentage", "remaining"]), percentage: z.number().gte(0).lte(100).multipleOf(0.1), amount: splitAmountMinor}); export const splitRemainingAmountCalculated = z.object({type: z.enum(["fixed", "percentage", "remaining"]), amount: splitAmountMinor}); export const processingFeeRequest = z.object({percentage: z.number().gte(0).lte(100).multipleOf(0.1)}); export const splitsCalculated = z.object({type: splitsType, accounts: z.array(z.object({type: splitsAccountType, id: accountId, version: accountVersion, legal_name: accountLegalName, split: z.discriminatedUnion("type", [splitFixedAmount, splitPercentageAmountCalculated, splitRemainingAmountCalculated]), processing_fee: processingFeeRequest}))}); export const createCheckoutResponse = z.object({id: checkoutId, status: checkoutStatus, reference: reference, created_at: createdAt, updated_at: updatedAt, expires_at: checkoutExpiresAt, flow: checkoutFlow, payment_methods: checkoutPaymentMethodsResponse, splits: splitsCalculated}); 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 checkout * * POST /v2/checkouts */ export const createApiV2Checkouts = async (args: CreateApiV2CheckoutsArgs, options?: CreateApiV2CheckoutsOptions) => { const {baseUrl = "https://api.getpaid.io", fetch: fetchFn = fetch, OAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Getpaid-Idempotency-Key'] != null) headers.set("Getpaid-Idempotency-Key", String(args['Getpaid-Idempotency-Key'])) if (OAuth !== undefined) headers.set('authorization', `Bearer ${OAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/checkouts${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(createCheckoutResponse, await res.json()) };