import {z} from 'zod' export type GetApiV1ReportingBalancesArgs = {as_of_time?: string | undefined, currency_code?: string | undefined}; export type GetApiV1ReportingBalancesOptions = {baseUrl?: string | undefined, Oauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const currencyCode = z.string().min(3).max(3); export const money = z.object({currency_code: currencyCode, value: z.string().max(32)}); export const balanceDetail = z.object({currency: currencyCode, primary: z.boolean().optional(), total_balance: money, available_balance: money.optional(), withheld_balance: money.optional()}); export const balanceDetailList = z.array(balanceDetail); export const accountId = z.string().min(13).max(13); export const dateTime = z.string().min(20).max(64); export const balancesResponse = z.object({balances: balanceDetailList.optional(), account_id: accountId.optional(), as_of_time: dateTime.optional(), last_refresh_time: dateTime.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 }; /** * List all balances * * GET /v1/reporting/balances */ export const getApiV1ReportingBalances = async (args: GetApiV1ReportingBalancesArgs, options?: GetApiV1ReportingBalancesOptions) => { const {baseUrl = "https://api-m.paypal.com", fetch: fetchFn = fetch, Oauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.as_of_time != null) query.append("as_of_time", String(args.as_of_time)) if (args.currency_code != null) query.append("currency_code", String(args.currency_code)) if (Oauth2 !== undefined) headers.set('authorization', `Bearer ${Oauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/reporting/balances${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(balancesResponse, await res.json()) };