import {z} from 'zod' export type GetApiApiV1WebhookEventsWebhookEventIdArgs = {webhookEventId: string, 'Client-ID': string, Authorization: string}; export type GetApiApiV1WebhookEventsWebhookEventIdOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const webhookEvent = z.object({id: z.string(), type: z.literal("WebhookEvent"), attributes: z.object({id: z.string(), topic: z.string(), clientId: z.string(), userId: z.string().optional(), walletId: z.string().optional(), updatedAt: z.string(), createdAt: z.string()}), relationships: z.object({event: z.object({data: z.object({id: z.string(), type: z.string()})}).optional()})}); export const bankApplicationLite = z.object({type: z.literal("Lite"), firstName: z.string(), lastName: z.string(), email: z.string(), dateOfBirth: z.string(), phone: z.string(), street: z.string().optional(), street2: z.string().optional(), city: z.string().optional(), state: z.string().optional(), postalCode: z.string().optional()}); export const webhookIncluded = z.discriminatedUnion("type", [z.object({id: z.string(), type: z.literal("PaymentIntent"), attributes: z.object({id: z.string(), status: z.enum(["Promotable", "PromotedToPayment", "Invalid", "Expired", "Canceled"]), error: z.enum(["LinkedAccountUnverified", "LinkedAccountDisconnected", "LinkedAccountMissing", "InsufficientBalance", "MissingFullName", "WrongEmail", "InvalidKycStatus"]).nullable(), userId: z.string(), walletId: z.string().nullable(), fullName: z.string().nullable(), email: z.string().nullable(), phoneNumber: z.string().nullable(), billingAddress: z.record(z.string(), z.unknown()).nullable(), reference: z.string().nullable().optional(), expiresAt: z.string(), createdAt: z.string(), updatedAt: z.string()})}), z.object({id: z.string(), type: z.literal("Payment"), attributes: z.object({id: z.string(), status: z.enum(["Canceled", "Created", "Failed", "Processing", "Returned", "Sent"]), amount: z.number().int(), reference: z.string().nullable().optional(), expiresAt: z.string().nullable(), createdAt: z.string(), updatedAt: z.string(), paymentIntentId: z.string().optional(), channelId: z.string().nullable().optional(), channel: z.string().nullable().optional(), error: z.string().nullable().optional(), secondaryAuthorizationType: z.literal("Card").nullable().optional(), secondaryAuthorizationId: z.string().nullable().optional(), secondaryAuthorizationAmount: z.number().int().nullable().optional(), walletId: z.string().nullable().optional(), userId: z.string().optional()})}), z.object({id: z.string(), type: z.literal("Refund"), attributes: z.object({id: z.string(), paymentId: z.string().optional(), amount: z.number().int(), status: z.enum(["Failed", "Pending", "Sent", "Waiting"]), message: z.string(), reference: z.string().nullable().optional(), charges: z.object({fee: z.object({amount: z.number().int().gte(0), type: z.string()}).optional(), rewards: z.number().int().gte(0).optional()}).optional(), deductions: z.object({rewards: z.number().int().gte(0), fees: z.number().int().gte(0)}).optional(), createdAt: z.string(), updatedAt: z.string()})}), z.object({id: z.string(), type: z.literal("Capture"), attributes: z.object({id: z.string(), method: z.enum(["Direct", "BankRails", "VirtualDebitCard"]), amount: z.number().int(), reference: z.string().nullable().optional(), externalPayments: z.unknown(), createdAt: z.string(), updatedAt: z.string()})}), z.object({id: z.string(), type: z.literal("KycCreated"), attributes: z.object({application: bankApplicationLite, userId: z.string(), provider: z.string(), reference: z.string().nullable().optional(), email: z.string().nullable().optional(), fullName: z.string().nullable().optional(), phoneNumber: z.string().nullable().optional(), error: z.string().nullable().optional(), walletId: z.string().nullable().optional(), billingAddress: z.record(z.string(), z.unknown()).nullable().optional()})}), z.object({id: z.string(), type: z.literal("KycApproved"), attributes: z.object({userId: z.string(), priorStatus: z.enum(["Approved", "AwaitingDocuments", "Denied", "ManualReview", "NotStarted", "Pending", "Unknown"]).optional(), reference: z.string().nullable().optional(), email: z.string().nullable().optional(), fullName: z.string().nullable().optional(), phoneNumber: z.string().nullable().optional(), error: z.string().nullable().optional(), walletId: z.string().nullable().optional(), billingAddress: z.record(z.string(), z.unknown()).nullable().optional()})}), z.object({id: z.string(), type: z.enum(["KycDeclined", "KycPending", "KycAwaitingDocuments", "KycManualReview"]), attributes: z.object({userId: z.string(), reason: z.string().optional(), reference: z.string().nullable().optional(), email: z.string().nullable().optional(), fullName: z.string().nullable().optional(), phoneNumber: z.string().nullable().optional(), error: z.string().nullable().optional(), walletId: z.string().nullable().optional(), billingAddress: z.record(z.string(), z.unknown()).nullable().optional()})}), z.object({id: z.string(), type: z.literal("TransactionCleared"), attributes: z.object({transactionId: z.string(), walletId: z.string(), rewardIds: z.array(z.string()).optional(), reference: z.string().nullable().optional(), email: z.string().nullable().optional(), fullName: z.string().nullable().optional(), phoneNumber: z.string().nullable().optional(), error: z.string().nullable().optional(), billingAddress: z.record(z.string(), z.unknown()).nullable().optional(), fee: z.object({type: z.string().nullable(), amount: z.number().int()})})}), z.object({id: z.string(), type: z.literal("TransactionFailed"), attributes: z.object({transactionId: z.string(), walletId: z.string(), rewardIds: z.array(z.string()).optional(), reference: z.string().nullable().optional(), email: z.string().nullable().optional(), fullName: z.string().nullable().optional(), phoneNumber: z.string().nullable().optional(), error: z.string().nullable().optional(), billingAddress: z.record(z.string(), z.unknown()).nullable().optional(), fee: z.object({type: z.string().nullable(), amount: z.number().int()}), failureReason: z.enum(["Canceled", "HardDecline", "SoftDecline", "Expired", "InsufficientFunds", "Reversed", "Unknown"]).optional()})}), z.object({id: z.string(), type: z.literal("CounterpartyIncomingPayment"), attributes: z.object({counterpartyId: z.string(), merchantId: z.string(), amount: z.number().int(), currency: z.string(), direction: z.enum(["credit", "debit"]), method: z.string(), originatorName: z.string().nullable(), description: z.string().nullable(), asOfDate: z.string(), externalIncomingPaymentId: z.string(), reference: z.string().nullable().optional(), email: z.string().nullable().optional(), fullName: z.string().nullable().optional(), phoneNumber: z.string().nullable().optional(), error: z.string().nullable().optional(), walletId: z.string().nullable().optional(), billingAddress: z.record(z.string(), z.unknown()).nullable().optional()})}), z.object({id: z.string(), type: z.enum(["CounterpartyPayoutCreated", "CounterpartyPayoutSent", "CounterpartyPayoutCompleted"]), attributes: z.object({payoutId: z.string(), counterpartyId: z.string(), merchantId: z.string(), amount: z.number().int(), currency: z.string(), status: z.enum(["Approved", "Cancelled", "Completed", "Denied", "Failed", "NeedsApproval", "Pending", "Processing", "Returned", "Reversed", "Sent"]), description: z.string().nullable(), effectiveDate: z.string(), createdAt: z.string(), updatedAt: z.string(), reference: z.string().nullable().optional(), email: z.string().nullable().optional(), fullName: z.string().nullable().optional(), phoneNumber: z.string().nullable().optional(), error: z.string().nullable().optional(), walletId: z.string().nullable().optional(), billingAddress: z.record(z.string(), z.unknown()).nullable().optional()})}), z.object({id: z.string(), type: z.literal("CounterpartyPayoutReturned"), attributes: z.object({payoutId: z.string(), counterpartyId: z.string(), merchantId: z.string(), amount: z.number().int(), currency: z.string(), status: z.enum(["Approved", "Cancelled", "Completed", "Denied", "Failed", "NeedsApproval", "Pending", "Processing", "Returned", "Reversed", "Sent"]), description: z.string().nullable(), effectiveDate: z.string(), createdAt: z.string(), updatedAt: z.string(), returnCode: z.string().nullable(), returnReason: z.string().nullable(), reference: z.string().nullable().optional(), email: z.string().nullable().optional(), fullName: z.string().nullable().optional(), phoneNumber: z.string().nullable().optional(), error: z.string().nullable().optional(), walletId: z.string().nullable().optional(), billingAddress: z.record(z.string(), z.unknown()).nullable().optional()})}), z.object({id: z.string(), type: z.enum(["CounterpartyTransactionCreated", "CounterpartyTransactionUpdated"]), attributes: z.object({transactionId: z.string(), counterpartyId: z.string(), merchantId: z.string(), amount: z.number().int().gte(0), currency: z.string(), direction: z.enum(["Credit", "Debit"]), type: z.enum(["Deposit", "Payout", "Transfer", "Adjustment", "Other"]), status: z.enum(["Pending", "Posted", "Archived"]), description: z.string().nullable(), originatorName: z.string().nullable(), effectiveAt: z.string(), postedAt: z.string().nullable(), createdAt: z.string(), updatedAt: z.string(), reference: z.string().nullable().optional(), email: z.string().nullable().optional(), fullName: z.string().nullable().optional(), phoneNumber: z.string().nullable().optional(), error: z.string().nullable().optional(), walletId: z.string().nullable().optional(), billingAddress: z.record(z.string(), z.unknown()).nullable().optional()})}), z.object({id: z.string(), type: z.literal("YieldPayoutCreated"), attributes: z.object({yieldPayoutId: z.string(), merchantId: z.string(), amount: z.number().int(), currency: z.string(), periodStart: z.string(), periodEnd: z.string(), paidAt: z.string(), reference: z.string().nullable().optional(), email: z.string().nullable().optional(), fullName: z.string().nullable().optional(), phoneNumber: z.string().nullable().optional(), error: z.string().nullable().optional(), walletId: z.string().nullable().optional(), billingAddress: z.record(z.string(), z.unknown()).nullable().optional()})})]); export const getWebhookEventResponse = z.object({data: webhookEvent, included: z.array(webhookIncluded).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 a webhook event * * GET /api/v1/webhook-events/{webhookEventId} */ export const getApiApiV1WebhookEventsWebhookEventId = async (args: GetApiApiV1WebhookEventsWebhookEventIdArgs, options?: GetApiApiV1WebhookEventsWebhookEventIdOptions) => { const {baseUrl = "https://merchant-api.accruesavings.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/vnd.api+json") if (args['Client-ID'] != null) headers.set("Client-ID", String(args['Client-ID'])) if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/webhook-events/${encodeURIComponent(String(args.webhookEventId))}${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(getWebhookEventResponse, await res.json()) };