import {z} from 'zod' export type SchemasAcceptorKey = string; export type MerchantAcceptorResolver = {merchantAcceptorKey: SchemasAcceptorKey}; export type Pan = string; export type ExpiryMonth = number; export type ExpiryYear = number; export type Cvc = string; export type HolderName = string; export type InputCard = {number: Pan, expiryMonth: ExpiryMonth, expiryYear: ExpiryYear, cvc?: Cvc | undefined, holderName?: HolderName | undefined}; export type ProcessorTokenKey = string; export type CardByProcessorTokenKey = {processorTokenKey: ProcessorTokenKey, cvc?: string | undefined}; export type Card = InputCard | CardByProcessorTokenKey; export type ThreeRiIndicator = 'recurring' | 'ucof' | 'installment' | 'standing-order'; export type AmountValue = number; export type SchemasCurrencyCode = string; export type Amount = {value: AmountValue, currency: SchemasCurrencyCode}; export type PhoneNumber = {countryCode: string, number: string}; export type CardholderInformation = {email?: string | undefined, phone?: ({work?: PhoneNumber | undefined, mobile?: PhoneNumber | undefined, home?: PhoneNumber | undefined}) | undefined}; export type ComponentsSchemasStateOrProvince = string; export type ComponentsSchemasCity = string; export type ComponentsSchemasLine1 = string; export type ComponentsSchemasLine2 = string; export type ComponentsSchemasPostalCode = string; export type AddressInput = {countryCode: {alpha3: string} | {alpha2: string} | {numeric: string}, stateOrProvince?: ComponentsSchemasStateOrProvince | undefined, city: ComponentsSchemasCity, line1: ComponentsSchemasLine1, line2?: ComponentsSchemasLine2 | undefined, postalCode: ComponentsSchemasPostalCode}; export type TransactionReference = string; export type ThreeDsPriorAuthenticationInfo = {authMethod: 'frictionless' | 'challenge', dateTime: unknown, acsTransId: string, dsTransId: string}; export type ThreeRiRecurringExpiry = string; export type ThreeRiRecurringFrequency = number; export type InstallmentTerms = number; export type ThreeRiRequestWithMerchantAcceptor = {merchantAcceptorResolver: MerchantAcceptorResolver, card: Card, threeRiIndicator: ThreeRiIndicator, amount: Amount, cardholderInformation?: CardholderInformation | undefined, billingAddress?: AddressInput | undefined, transactionReference?: TransactionReference | undefined, threeDsPriorAuthenticationInfo: ThreeDsPriorAuthenticationInfo, recurringExpiry?: ThreeRiRecurringExpiry | undefined, recurringFrequency?: ThreeRiRecurringFrequency | undefined, installmentTerms?: InstallmentTerms | undefined}; export type SchemasCountryCodeAlpha3 = {alpha3: string}; export type SchemasCountryCodeAlpha2 = {alpha2: string}; export type SchemasCountryCodeNumeric = {numeric: string}; export type MerchantInfoRequest = {acquirerBin?: string | undefined, merchantId: string, mcc: string, merchantName: string, merchantCountryCode: SchemasCountryCodeAlpha3 | SchemasCountryCodeAlpha2 | SchemasCountryCodeNumeric, websiteUrl: string, network: 'american-express' | 'bancontact' | 'diners' | 'mastercard' | 'visa'}; export type ThreeRiRequestWithMerchantInfo = {merchantInfo: MerchantInfoRequest, card: Card, threeRiIndicator: ThreeRiIndicator, amount: Amount, cardholderInformation?: CardholderInformation | undefined, billingAddress?: AddressInput | undefined, transactionReference?: TransactionReference | undefined, threeDsPriorAuthenticationInfo: ThreeDsPriorAuthenticationInfo, recurringExpiry?: ThreeRiRecurringExpiry | undefined, recurringFrequency?: ThreeRiRecurringFrequency | undefined, installmentTerms?: InstallmentTerms | undefined}; export type ThreeRiRequest = ThreeRiRequestWithMerchantAcceptor | ThreeRiRequestWithMerchantInfo; export type CreateApi3ds3riArgs = {body: ThreeRiRequest}; export type CreateApi3ds3riOptions = {baseUrl?: string | undefined, ApiKey?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const threedsKey = z.string(); export const schemasAcceptorKey = z.string().min(5).max(120); export const version = z.number().int(); export const schemasAcceptorRef = z.object({key: schemasAcceptorKey, version: version}); export const merchantInfoResponse = z.object({acquirerBin: z.string().min(6).max(11).optional(), merchantId: z.string().min(1).max(20), mcc: z.string().min(4).max(4), merchantName: z.string(), merchantCountryCode: z.object({alpha3: z.string(), alpha2: z.string(), numeric: z.string()}), websiteUrl: z.string().max(2048), network: z.enum(["american-express", "bancontact", "diners", "mastercard", "visa"])}); export const amountValue = z.number().int().gte(0).lte(999999999999); export const schemasCurrencyCode = z.string(); export const amount = z.object({value: amountValue, currency: schemasCurrencyCode}); export const unknownAmount = z.object({value: z.literal(-1), currency: z.literal("unknown")}); export const responseAmount = z.union([amount, unknownAmount]); export const authenticationNetwork = z.enum(["american-express", "bancontact", "diners", "mastercard", "visa", "unknown"]); export const result = z.enum(["authenticated", "non-authenticated"]); export const threeDSServerTransID = z.string(); export const messageExtension = z.object({name: z.string().min(1).max(64), id: z.string().min(1).max(64), criticalityIndicator: z.boolean(), data: z.unknown()}); export const messageExtensionList = z.array(messageExtension); export const dsTransID = z.string(); export const acsTransID = z.string(); export const threeRiTransStatus = z.enum(["Y", "N", "R"]); export const transStatusReason = z.string(); export const cardHolderInfo = z.string(); export const acsChallengeMandated = z.string(); export const dsReferenceNumber = z.string(); export const acsReferenceNumber = z.string(); export const acsOperatorID = z.string(); export const acsDecConInd = z.string(); export const authenticationType = z.string(); export const eci = z.string(); export const whiteListStatus = z.string(); export const whiteListStatusSource = z.string(); export const authenticationValue = z.string(); export const threeRiARes = z.object({threeDSServerTransID: threeDSServerTransID, messageExtension: messageExtensionList.optional(), messageType: z.literal("ARes"), dsTransID: dsTransID, acsTransID: acsTransID, transStatus: threeRiTransStatus, messageVersion: z.literal("2.2.0"), transStatusReason: transStatusReason.optional(), cardholderInfo: cardHolderInfo.optional(), acsChallengeMandated: acsChallengeMandated.optional(), dsReferenceNumber: dsReferenceNumber, acsReferenceNumber: acsReferenceNumber, acsOperatorID: acsOperatorID.optional(), acsDecConInd: acsDecConInd.optional(), authenticationType: authenticationType.optional(), eci: eci.optional(), whiteListStatus: whiteListStatus.optional(), whiteListStatusSource: whiteListStatusSource.optional(), authenticationValue: authenticationValue.optional()}); export const transactionReference = z.string().min(1).max(120); export const fraudLiability = z.enum(["acquirer", "issuer"]); export const threeRiIndicator = z.enum(["recurring", "ucof", "installment", "standing-order"]); export const schemasCreated = z.string(); export const threeRiResponse = z.object({key: threedsKey, merchantAcceptorRef: schemasAcceptorRef.optional(), merchantInfo: merchantInfoResponse.optional(), amount: responseAmount, network: authenticationNetwork, protocolVersion: z.literal("2.2.0"), deviceChannel: z.literal("3ri"), result: result, ares: threeRiARes, transactionReference: transactionReference.optional(), fraudLiability: fraudLiability, threeRiIndicator: threeRiIndicator, created: schemasCreated, version: version}); 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 3RI Authentication * * POST /3ds/3ri * * Also accepts auth: BearerToken */ export const createApi3ds3ri = async (args: CreateApi3ds3riArgs, options?: CreateApi3ds3riOptions) => { const {baseUrl = "https://eu-west-1.api.silverflow.com/v1", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKey !== undefined) headers.set('authorization', `Basic ${btoa(`${ApiKey.username}:${ApiKey.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/3ds/3ri${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(threeRiResponse, await res.json()) };