import {z} from 'zod' export type PaymentMethod = 'PIX' | 'CARD' | 'BOLETO'; export type Currency = 'BRL'; export type PaymentSplitInput = {recipientCompanyId: string, type: 'PERCENTAGE' | 'FIXED', value: number}; export type PaymentTrackingInput = {utmSource?: string | undefined, utmMedium?: string | undefined, utmCampaign?: string | undefined, utmTerm?: string | undefined, utmContent?: string | undefined, src?: string | undefined, sck?: string | undefined, fbclid?: string | undefined, gclid?: string | undefined, ttclid?: string | undefined, gaClientId?: string | undefined, fbp?: string | undefined, fbc?: string | undefined}; export type PaymentItemInput = {name: string, unitAmount: number, quantity: number, productId?: string | undefined, sku?: string | undefined}; export type OrderBumpInput = {name: string, unitAmount: number, description?: string | undefined, productId?: string | undefined}; export type UpsellInput = {name: string, unitAmount: number, description?: string | undefined, productId?: string | undefined}; export type CreatePaymentRequest = {productId?: string | undefined, customerId?: string | undefined, amount?: number | undefined, methods?: Array | undefined, currency?: Currency | undefined, mode?: ('hosted' | 'headless') | undefined, returnUrl?: string | undefined, completionUrl?: string | undefined, description?: string | undefined, externalId?: string | undefined, expiresInMinutes?: number | undefined, enforcePayerDocument?: boolean | undefined, customer?: ({name?: string | undefined, document?: string | undefined, email?: string | undefined, phone?: string | undefined}) | undefined, metadata?: {[key: string]: string} | undefined, passFeeToPayer?: boolean | undefined, splits?: Array | undefined, tracking?: PaymentTrackingInput | undefined, recoveryKit?: boolean | undefined, items?: Array | undefined, itemsQuantityEditable?: boolean | undefined, couponCode?: string | undefined, orderBump?: (OrderBumpInput | null) | undefined, upsell?: (UpsellInput | null) | undefined, boleto?: ({dueDate?: string | undefined, fine?: ({value: number, type?: ('FIXED' | 'PERCENTAGE') | undefined}) | undefined, interest?: {value: number} | undefined, discount?: ({value: number, type?: ('FIXED' | 'PERCENTAGE') | undefined, dueDateLimitDays?: number | undefined}) | undefined}) | undefined}; export type CreateApiV1PaymentsArgs = {'X-Idempotency-Key': string, 'X-Split-Platform-Key'?: string | undefined, body: CreatePaymentRequest}; export type CreateApiV1PaymentsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const paymentSplit = z.object({id: z.string(), recipientCompanyId: z.string(), type: z.enum(["PERCENTAGE", "FIXED"]), value: z.number()}); export const paymentItem = z.object({id: z.string(), name: z.string(), unitAmount: z.number(), quantity: z.number().int().gte(1).lte(999), kind: z.enum(["ITEM", "ORDER_BUMP", "UPSELL"]), productId: z.string().nullable(), sku: z.string().nullable()}); export const paymentCoupon = z.object({code: z.string()}).nullable(); export const paymentStatus = z.enum(["NEW", "PENDING_METHOD_SELECTION", "PROCESSING", "CONFIRMED", "PAID", "CANCELLED", "EXPIRED", "REFUNDED", "PARTIAL_REFUND", "CHARGEBACK", "MED_FROZEN", "FREE"]); export const paymentMethod = z.enum(["PIX", "CARD", "BOLETO"]); export const currency = z.literal("BRL"); export const headlessPaymentCreateResponse = z.object({id: z.string().optional(), txId: z.string().optional(), amount: z.number().optional(), feeAmount: z.number().optional(), netAmount: z.number().optional(), feePassedToPayer: z.boolean().optional(), payerFeeAmount: z.number().nullable().optional(), splits: z.array(paymentSplit).optional(), items: z.array(paymentItem).optional(), subtotal: z.number().optional(), discount: z.number().optional(), coupon: paymentCoupon.optional(), isSandbox: z.boolean().optional(), status: paymentStatus.optional(), paymentMethod: paymentMethod.optional(), currency: currency.optional(), description: z.string().nullable().optional(), expiresAt: z.string().optional(), createdAt: z.string().optional(), methodData: z.object({type: paymentMethod.optional(), cardFundingType: z.enum(["credit", "debit", "null"]).nullable().optional()}).and(z.record(z.string(), z.unknown())).nullable().optional()}); export const hostedPaymentCreateResponse = z.object({id: z.string().optional(), txId: z.string().optional(), amount: z.number().optional(), feeAmount: z.number().optional(), netAmount: z.number().optional(), feePassedToPayer: z.boolean().optional(), payerFeeAmount: z.number().nullable().optional(), splits: z.array(paymentSplit).optional(), items: z.array(paymentItem).optional(), subtotal: z.number().optional(), discount: z.number().optional(), coupon: paymentCoupon.optional(), status: paymentStatus.optional(), methods: z.array(paymentMethod).optional(), currency: currency.optional(), checkoutUrl: z.string().optional(), expiresAt: z.string().optional(), isSandbox: z.boolean().optional(), createdAt: z.string().optional()}); export const createPaymentResponse = z.object({payment: z.union([headlessPaymentCreateResponse, hostedPaymentCreateResponse])}); 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 * * POST /v1/payments */ export const createApiV1Payments = async (args: CreateApiV1PaymentsArgs, options?: CreateApiV1PaymentsOptions) => { const {baseUrl = "https://api.yuvexpay.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-Idempotency-Key'] != null) headers.set("X-Idempotency-Key", String(args['X-Idempotency-Key'])) if (args['X-Split-Platform-Key'] != null) headers.set("X-Split-Platform-Key", String(args['X-Split-Platform-Key'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/payments${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(createPaymentResponse, await res.json()) };