import {z} from 'zod' export type ExternalIdPayments = string; export type CustomerIdPaymentWidget = string; export type CustomerPaymentWidget = {identifier: string, name?: string | undefined, external_id?: ExternalIdPayments | undefined}; export type EnrollmentBiometricPaymentWidget = {type: 'open_finance_biometric_pix', external_id?: ExternalIdPayments | undefined, details: {name?: string | undefined, customer: CustomerIdPaymentWidget | CustomerPaymentWidget, institution?: string | undefined}, metadata: Record}; export type IndividualRequestBiometricPix = {open_finance_biometric_pix: {beneficiary_bank_account: string, enrollment?: string | undefined}}; export type PaymentIntentBiometricWidget = {amount: string, external_id?: ExternalIdPayments | undefined, description: string, statement_description?: string | undefined, allowed_payment_method_types: Array<'open_finance_biometric_pix'>, payment_method_details: IndividualRequestBiometricPix, metadata: Record}; export type CallbackUrlsBiometricPaymentWidget = {success: string, exit: string}; export type BrandingBiometricWidget = {color_scheme?: ('LIGHT' | 'DARK') | undefined, company_name: string}; export type ThemeBiometricWidget = {css_key: string, value: string}; export type BiometricPaymentWidgetRequest = {use_cases: Array<'ENROLLMENT' | 'PAYMENT_INTENT'>, widget: {enrollment?: EnrollmentBiometricPaymentWidget | undefined, payment_intent?: PaymentIntentBiometricWidget | undefined, callback_urls: CallbackUrlsBiometricPaymentWidget, branding: BrandingBiometricWidget, top_tier_institutions?: (Array<'nubank_retail' | 'inter_retail' | 'picpay_retail' | 'mercadopago_retail' | 'itau_retail' | 'santander_retail' | 'c6_retail' | 'bradesco_retail' | 'banco_do_brasil_retail' | 'sicredi_retail' | 'btg_retail' | 'caixa_retail' | 'pan_retail' | 'pagseguro_retail'>) | undefined, theme?: Array | undefined}}; export type CreateApiPaymentsBrTokenArgs = {body: BiometricPaymentWidgetRequest}; export type CreateApiPaymentsBrTokenOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const widgetToken = z.object({access: z.string().optional(), refresh: 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 }; /** * Generate a payment widget access token * * POST /payments/br/token/ */ export const createApiPaymentsBrToken = async (args: CreateApiPaymentsBrTokenArgs, options?: CreateApiPaymentsBrTokenOptions) => { const {baseUrl = "https://sandbox.belvo.com", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/payments/br/token/${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(widgetToken, await res.json()) };