import {z} from 'zod' export type GetApiWalletsArgs = {page?: number | undefined, per_page?: number | undefined, external_customer_id: string}; export type GetApiWalletsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const walletStatus = z.enum(["ACTIVE", "TERMINATED", "PENDING"]); export const currency = z.string().min(3).max(3); export const amount = z.object({value: z.number().gte(0), currency_code: currency}); export const dateTimeWithZone = z.string(); export const feeType = z.enum(["SUBSCRIPTION", "COMMITMENT", "CHARGE"]); export const prepaidCreditAppliesTo = z.object({fee_types: z.array(feeType).optional()}); export const recurringTransactionTrigger = z.enum(["INTERVAL", "THRESHOLD"]); export const recurringTransactionMethod = z.enum(["FIXED", "TARGET"]); export const billingCycle = z.enum(["WEEKLY", "MONTHLY", "QUARTERLY", "YEARLY"]); export const recurringTransactionRule = z.object({trigger: recurringTransactionTrigger, paid_credits: z.string().optional(), granted_credits: z.string().optional(), method: recurringTransactionMethod, interval: billingCycle.optional(), started_at: dateTimeWithZone.optional(), expiration_at: dateTimeWithZone.optional(), threshold_credits: z.string().optional(), target_ongoing_balance: z.string().optional()}); export const walletId = z.string(); export const walletWithId = z.object({external_customer_id: z.string(), status: walletStatus, available_balance: amount.optional(), ongoing_usage: z.object({value: z.number().gte(0), currency_code: currency}).optional(), net_balance: z.object({value: z.number().gte(0), currency_code: currency}).optional(), name: z.string().optional(), rate_amount: z.string(), available_credits: z.string().optional(), ongoing_usage_credits: z.string().optional(), net_balance_credits: z.string().optional(), consumed_credits: z.string().optional(), created_at: dateTimeWithZone.optional(), expiration_at: dateTimeWithZone.optional(), terminated_at: dateTimeWithZone.optional(), applies_to: prepaidCreditAppliesTo.optional(), recurring_transaction_rules: z.array(recurringTransactionRule).optional(), id: walletId.optional()}); export const paginationMetadata = z.object({total_count: z.number().int().optional(), total_pages: z.number().int().optional(), current_page: z.number().int().optional()}); export const getApiWalletsResponse = z.object({wallets: z.array(walletWithId).optional(), metadata: paginationMetadata.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 }; /** * Get all wallets * * GET /wallets */ export const getApiWallets = async (args: GetApiWalletsArgs, options?: GetApiWalletsOptions) => { const {baseUrl = "https://api-m.sandbox.paypal.com", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page != null) query.append("page", String(args.page)) if (args.per_page != null) query.append("per_page", String(args.per_page)) if (args.external_customer_id != null) query.append("external_customer_id", String(args.external_customer_id)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/wallets${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiWalletsResponse, await res.json()) };