import {z} from 'zod' export type V3OrderResultsRequest = {managedOrderToken: string}; export type CreateApiV3OrdersIdResultsArgs = {id: string, 'api-version': string, 'x-forter-siteid': string, Authorization: string, body: V3OrderResultsRequest}; export type CreateApiV3OrdersIdResultsOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const processorRecommendation = z.object({priority: z.number(), processorMid: z.string(), processorName: z.string(), recommend3DS: z.boolean(), recommendationId: z.string()}); export const verificationData = z.object({ThreeDS: z.object({ACSUrl: z.string().max(2048), ECIValue: z.string().max(300), acsChallengeMandated: z.string().max(1), acsReferenceNumber: z.string().max(32), acsSignedContent: z.string().max(1000), acsTransID: z.string().max(36), authenticationType: z.string().max(2), authenticationValue: z.string().max(28), bankLiabilityShift: z.boolean(), cardEnrolled: z.string().max(1), cavvAlgorithm: z.string().max(1), challengeCancel: z.string().max(2), challengeStatus: z.string().max(1), dsTransID: z.string().max(100), encodedChallengeRequest: z.string(), exemption: z.enum(["LOW_VALUE", "TRANSACTION_RISK_ANALYSIS", "SECURE_CORPORATE", "TRUSTED_BENEFICIARY"]).nullable().optional(), interactionCounter: z.string().max(2), isFallback: z.boolean(), messageCategory: z.string().max(2), outOfScopeForPSD2: z.enum(["ANONYMOUS_PREPAID_CARD", "MERCHANT_INITIATED_TRANSACTIONS", "ONE_LEG_OUT_EEA", "MAIL_ORDER_TELEPHONE_ORDER"]).nullable().optional(), threeDSServerTransID: z.string().max(100), threeDSecureMode: z.string().max(15), threeDSecurePreference: z.string().max(15), threeDSecureResult: z.string().max(6), transStatus: z.string().max(1), transStatusReason: z.string().max(2), verifyStatus: z.string().max(1), version: z.string().max(50)}).nullable().optional(), email: z.object({email: z.string().max(256), emailVerification: z.object({sent: z.boolean().nullable().optional(), timeSent: z.number().nullable().optional(), verified: z.boolean()}).nullable().optional()}).nullable().optional(), phone: z.object({phone: z.string().max(25), smsVerified: z.object({sent: z.boolean().nullable().optional(), timeSent: z.number().nullable().optional(), verified: z.boolean()}).nullable().optional()}).nullable().optional()}); export const verificationMethod = z.object({correlationId: z.string(), status: z.string().max(50), statusCode: z.string().max(50), statusMessage: z.string().max(50), type: z.enum(["OTP_SMS", "OTP_EMAIL", "THREE_DS"]).max(50), verificationId: z.string(), verificationSpecificData: verificationData}); export const v3OrderResultsResponse = z.object({decisionReason: z.string().max(1000), forterDecision: z.enum(["APPROVE", "DECLINE", "NOT REVIEWED"]), linkToEventInDashboard: z.string().max(1000), merchantPolicyId: z.string(), orderId: z.string(), paymentRecommendations: z.object({action: z.enum(["no_processor_preference", "do_not_process", "process_payment"]).nullable().optional(), processor_routing_reason: z.enum(["out_of_scope", "hard_fraud_decline", "model_recommendation", "exceeded_processing_attempts", "authorized_payment", "no_optional_processor"]).nullable().optional(), processors: z.array(processorRecommendation).nullable().optional()}).nullable().optional(), recommendation: z.string().max(1000), verificationMethod: verificationMethod}); 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 }; /** * 3DS result * * POST /v3/orders/{id}/results */ export const createApiV3OrdersIdResults = async (args: CreateApiV3OrdersIdResultsArgs, options?: CreateApiV3OrdersIdResultsOptions) => { const {baseUrl = "https://api.forter-secure.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 (args['api-version'] != null) headers.set("api-version", String(args['api-version'])) if (args['x-forter-siteid'] != null) headers.set("x-forter-siteid", String(args['x-forter-siteid'])) if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/v3/orders/${encodeURIComponent(String(args.id))}/results${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(v3OrderResultsResponse, await res.json()) };