import {z} from 'zod' export type Metadata = string | number | boolean; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsTaxCategory = 'good' | 'service'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsCurrency = 'GTQ' | 'USD'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsPhoneRequirement = 'none' | 'optional' | 'required'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsAddressRequirement = 'none' | 'optional' | 'required'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsBillingInfoRequirement = 'none' | 'optional' | 'required'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsChargeType = 'one_time' | 'recurring'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsBillingInterval = 'day' | 'week' | 'month' | 'year'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsFreeTrialInterval = 'week' | 'month' | 'year'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsProrationBehavior = 'none' | 'create_prorations'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsPaymentMethodTypesItems = 'card' | 'bank_transfer' | 'stablecoins' | 'balance'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsAvailableInstallmentsItems = '3' | '6' | '12' | '18'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItems = {product_id?: string | undefined, price_id?: string | undefined, quantity?: number | undefined, metadata?: Metadata | undefined, tax_category?: CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsTaxCategory | undefined, name?: string | undefined, currency?: CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsCurrency | undefined, amount_in_cents?: number | undefined, phone_requirement?: CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsPhoneRequirement | undefined, address_requirement?: CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsAddressRequirement | undefined, billing_info_requirement?: CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsBillingInfoRequirement | undefined, image_url?: string | undefined, charge_type?: CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsChargeType | undefined, billing_interval?: CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsBillingInterval | undefined, billing_interval_count?: number | undefined, periods_before_automatic_cancellation?: number | undefined, free_trial_interval?: CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsFreeTrialInterval | undefined, free_trial_interval_count?: number | undefined, proration_behavior?: CheckoutsPostRequestBodyContentApplicationJsonSchemaItemsItemsProrationBehavior | undefined, billing_cycle_anchor_day?: number | undefined, defer_to_billing_day?: boolean | undefined, has_dynamic_pricing?: boolean | undefined, payment_method_types?: Array | undefined, available_installments?: Array | undefined}; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaMode = 'setup'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaTransferSetupsItemsPurpose = 'fund_split' | 'platform_commission'; export type CheckoutsPostRequestBodyContentApplicationJsonSchemaTransferSetupsItems = {amount_in_cents?: number | undefined, amount_percent?: number | undefined, recipient_id?: string | undefined, purpose?: CheckoutsPostRequestBodyContentApplicationJsonSchemaTransferSetupsItemsPurpose | undefined}; export type CreateApiCheckoutsArgs = {body: {items?: Array | undefined, mode?: CheckoutsPostRequestBodyContentApplicationJsonSchemaMode | undefined, success_url?: string | undefined, cancel_url?: string | undefined, bank_transfer_memo?: string | undefined, user_id?: string | undefined, customer_id?: string | undefined, metadata?: Metadata | undefined, expires_at?: string | undefined, discount_code?: string | undefined, application_fee_amount?: number | undefined, application_fee_percent?: number | undefined, transfer_setups?: Array | undefined}}; export type CreateApiCheckoutsOptions = {baseUrl?: string | undefined, secretKey?: string | undefined, fetch?: typeof fetch | undefined}; export const checkoutsPostResponsesContentApplicationJsonSchemaStatus = z.enum(["unpaid", "paid", "payment_in_progress", "expired"]); export const couponDiscountMode = z.enum(["code", "bank", "custom_bins"]); export const couponDuration = z.enum(["once", "forever"]); export const coupon = z.object({id: z.string().optional(), name: z.string().optional(), discount_mode: couponDiscountMode.optional(), display_name: z.string().nullable().optional(), amount_off_in_cents: z.number().int().nullable().optional(), percent_off: z.number().nullable().optional(), automatically_applies: z.boolean().optional(), max_redemptions: z.number().int().nullable().optional(), times_redeemed: z.number().int().optional(), currency: z.string().nullable().optional(), duration: couponDuration.optional(), expires_at: z.string().nullable().optional(), status: z.string().optional()}); export const checkoutsPostResponsesContentApplicationJsonSchemaDiscount = z.object({amount_in_cents: z.number().int().optional(), coupon: coupon.optional()}); export const checkoutsPostResponsesContentApplicationJsonSchemaCurrency = z.enum(["GTQ", "USD"]); export const checkoutsPostResponsesContentApplicationJsonSchemaPaymentMethodTypesItems = z.enum(["card", "bank_transfer", "stablecoins", "balance"]); export const metadata = z.union([z.string().max(500), z.number(), z.boolean()]); export const checkoutItem = z.object({id: z.string(), price_id: z.string(), quantity: z.number().int().gte(1), metadata: metadata}); export const checkoutCustomFieldValueType = z.enum(["text", "numeric", "dropdown"]); export const checkoutCustomFieldValue = z.object({field_id: z.string().optional(), key: z.string().optional(), type: checkoutCustomFieldValueType.optional(), value: z.string().optional()}); export const transferSetupStatus = z.enum(["pending", "completed", "cancelled", "reversed"]); export const transferSetupPurpose = z.enum(["fund_split", "platform_commission"]); export const transferSetup = z.object({id: z.string().optional(), status: transferSetupStatus.optional(), amount_in_cents: z.number().int().nullable().optional(), amount_percent: z.number().nullable().optional(), currency: z.string().optional(), recipient_id: z.string().optional(), purpose: transferSetupPurpose.optional()}); export const checkoutsPostResponsesContentApplicationJsonSchemaLatestIntentData = z.object({auth_code: z.string().nullable().optional()}); export const checkoutsPostResponsesContentApplicationJsonSchemaLatestIntent = z.object({id: z.string().optional(), type: z.string().optional(), created_at: z.string().optional(), data: checkoutsPostResponsesContentApplicationJsonSchemaLatestIntentData.optional()}); export const address = z.object({address_line_1: z.string().nullable().optional(), address_line_2: z.string().nullable().optional(), city: z.string().nullable().optional(), region: z.string().nullable().optional(), country: z.string().nullable().optional(), zip_code: z.string().nullable().optional()}); export const checkoutsPostResponsesContentApplicationJsonSchemaPaymentPaymentable = z.object({type: z.string().optional(), id: z.string().optional(), tax_name: z.string().nullable().optional(), tax_id: z.string().nullable().optional(), address: address.optional(), phone_number: z.string().nullable().optional()}); export const checkoutsPostResponsesContentApplicationJsonSchemaPayment = z.object({id: z.string().optional(), paymentable: checkoutsPostResponsesContentApplicationJsonSchemaPaymentPaymentable.optional()}); export const checkoutsPostResponsesContentApplicationJsonSchemaPaymentMethodCard = z.object({last4: z.string().optional(), expiration_month: z.number().int().optional(), expiration_year: z.number().int().optional(), network: z.string().optional(), issuer_name: z.string().nullable().optional()}); export const checkoutsPostResponsesContentApplicationJsonSchemaPaymentMethod = z.object({id: z.string().optional(), type: z.string().optional(), card: checkoutsPostResponsesContentApplicationJsonSchemaPaymentMethodCard.optional(), address: address.optional(), phone_number: z.string().nullable().optional()}); export const checkoutsCreateCheckoutResponse201 = z.object({id: z.string(), status: checkoutsPostResponsesContentApplicationJsonSchemaStatus, bank_transfer_memo: z.string().nullable().optional(), total_in_cents: z.number().int().optional(), subtotal_in_cents: z.number().int().optional(), discount: checkoutsPostResponsesContentApplicationJsonSchemaDiscount.nullable().optional(), currency: checkoutsPostResponsesContentApplicationJsonSchemaCurrency.optional(), payment_method_types: z.array(checkoutsPostResponsesContentApplicationJsonSchemaPaymentMethodTypesItems).optional(), available_installments: z.array(z.number().int()).optional(), live_mode: z.boolean().optional(), success_url: z.string().optional(), cancel_url: z.string().optional(), expires_at: z.string().optional(), created_at: z.string().optional(), metadata: metadata.optional(), items: z.array(checkoutItem), custom_fields: z.array(checkoutCustomFieldValue).optional(), transfer_setups: z.array(transferSetup).optional(), application_fee_amount: z.number().int().nullable().optional(), application_fee_percent: z.number().nullable().optional(), latest_intent: checkoutsPostResponsesContentApplicationJsonSchemaLatestIntent.nullable().optional(), payment: checkoutsPostResponsesContentApplicationJsonSchemaPayment.nullable().optional(), payment_method: checkoutsPostResponsesContentApplicationJsonSchemaPaymentMethod.nullable().optional(), checkout_url: z.string().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 }; /** * Crear un checkout * * POST /checkouts */ export const createApiCheckouts = async (args: CreateApiCheckoutsArgs, options?: CreateApiCheckoutsOptions) => { const {baseUrl = "https://app.recurrente.com/api", fetch: fetchFn = fetch, secretKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (secretKey !== undefined) headers.set("X-SECRET-KEY", secretKey) const url = `${baseUrl.replace(/\/+$/, '')}/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(checkoutsCreateCheckoutResponse201, await res.json()) };