import {z} from 'zod' export type CreatePreAuthRequestDto = {paymentToken: string, merchantUserId: string, amount: number, currency: string, merchantRef: string, merchantMetadata?: Record | undefined}; export type CreateApiTokenizedPaymentV1PreAuthsArgs = {'X-ShopBack-Idempotent-Id': string, body: CreatePreAuthRequestDto}; export type CreateApiTokenizedPaymentV1PreAuthsOptions = {baseUrl?: string | undefined, bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const preAuthResponseDto = z.object({id: z.string(), merchantRef: z.string(), status: z.enum(["PENDING", "AUTHORIZED", "CAPTURE_INITIATED", "CAPTURED", "VOIDED", "DECLINED", "EXPIRED"]), amount: z.number(), currency: z.string(), orderUuid: z.string().nullable(), orderStatus: z.string().nullable(), failureReason: z.string().nullable(), merchantMetadata: z.object({}).nullable(), createdAt: z.string(), updatedAt: z.string()}); 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 pre-authorization * * POST /tokenized-payment/v1/pre-auths */ export const createApiTokenizedPaymentV1PreAuths = async (args: CreateApiTokenizedPaymentV1PreAuthsArgs, options?: CreateApiTokenizedPaymentV1PreAuthsOptions) => { const {baseUrl = "https://integrations-sandbox.shopback.com/demo/merchant", fetch: fetchFn = fetch, bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-ShopBack-Idempotent-Id'] != null) headers.set("X-ShopBack-Idempotent-Id", String(args['X-ShopBack-Idempotent-Id'])) if (bearer !== undefined) headers.set('authorization', `Bearer ${bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/tokenized-payment/v1/pre-auths${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(preAuthResponseDto, await res.json()) };