import {z} from 'zod' export type RefundToken = string; export type Mode = 'live' | 'test'; export type Amount = {currency: string, value: string}; export type Metadata = string | number | {[key: string]: unknown} | Array | null; export type PaymentToken = string; export type SettlementToken = string; export type RefundStatus = 'queued' | 'pending' | 'processing' | 'refunded' | 'failed' | 'canceled'; export type CreatedAt = string; export type RefundExternalReferenceType = 'acquirer-reference'; export type RefundRoutingReversalsSourceType = 'organization'; export type OrganizationToken = string; export type TestmodeCreate = boolean | null; export type Url = {href: string, type: string}; export type UrlNullable = {href?: string | undefined, type?: string | undefined} | null; export type RefundRequest = {resource?: string | undefined, id?: RefundToken | undefined, mode?: Mode | undefined, description?: (string | null) | undefined, amount: Amount, metadata?: Metadata | undefined, paymentId?: PaymentToken | undefined, settlementId?: (SettlementToken | null) | undefined, status?: RefundStatus | undefined, createdAt?: CreatedAt | undefined, externalReference?: ({type?: RefundExternalReferenceType | undefined, id?: string | undefined}) | undefined, reverseRouting?: (boolean | null) | undefined, routingReversals?: (Array<{amount?: Amount | undefined, source?: ({type?: RefundRoutingReversalsSourceType | undefined, organizationId?: OrganizationToken | undefined}) | undefined}> | null) | undefined, testmode?: TestmodeCreate | undefined, _links?: ({self: Url, payment: Url, settlement?: UrlNullable | undefined, documentation: Url}) | undefined}; export type CreateApiV2PaymentsPaymentIdRefundsArgs = {'idempotency-key'?: string | undefined, body: RefundRequest}; export type CreateApiV2PaymentsPaymentIdRefundsOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const refundToken = z.string(); export const mode = z.enum(["live", "test"]); export const amount = z.object({currency: z.string(), value: z.string()}); export const metadata = z.union([z.string(), z.number(), z.record(z.string(), z.unknown()), z.array(z.string())]).nullable(); export const paymentToken = z.string(); export const settlementToken = z.string(); export const refundStatusResponse = z.enum(["queued", "pending", "processing", "refunded", "failed", "canceled"]); export const createdAt = z.string(); export const refundExternalReferenceTypeResponse = z.literal("acquirer-reference"); export const refundRoutingReversalsSourceTypeResponse = z.literal("organization"); export const organizationToken = z.string(); export const testmodeCreate = z.boolean().nullable(); export const url = z.object({href: z.string(), type: z.string()}); export const urlNullable = z.object({href: z.string().optional(), type: z.string().optional()}).nullable(); export const refundResponse = z.object({resource: z.string().optional(), id: refundToken.optional(), mode: mode.optional(), description: z.string().max(255).nullable().optional(), amount: amount.optional(), metadata: metadata.optional(), paymentId: paymentToken.optional(), settlementId: settlementToken.nullable().optional(), status: refundStatusResponse.optional(), createdAt: createdAt.optional(), externalReference: z.object({type: refundExternalReferenceTypeResponse.optional(), id: z.string().optional()}).optional(), reverseRouting: z.boolean().nullable().optional(), routingReversals: z.array(z.object({amount: amount.optional(), source: z.object({type: refundRoutingReversalsSourceTypeResponse.optional(), organizationId: organizationToken.optional()}).optional()})).nullable().optional(), testmode: testmodeCreate.optional(), _links: z.object({self: url, payment: url, settlement: urlNullable.optional(), documentation: url}).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 }; /** * Create payment refund * * POST /v2/payments/{paymentId}/refunds * * Also accepts auth: advancedAccessToken, oAuth */ export const createApiV2PaymentsPaymentIdRefunds = async (args: CreateApiV2PaymentsPaymentIdRefundsArgs, options?: CreateApiV2PaymentsPaymentIdRefundsOptions) => { const {baseUrl = "https://api.mollie.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/hal+json") if (args['idempotency-key'] != null) headers.set("idempotency-key", String(args['idempotency-key'])) if (apiKey !== undefined) headers.set('authorization', `Bearer ${apiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/payments/${encodeURIComponent(String(args.paymentId))}/refunds${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(refundResponse, await res.json()) };