import {z} from 'zod' export type ComponentsSchemasAcceptorKeyRef = string; export type SchemasMerchantKey = string; export type SchemasAcceptorRoute = string; export type SchemasAcceptorResolver = {merchantAcceptorKey: ComponentsSchemasAcceptorKeyRef} | {merchantKey: SchemasMerchantKey, route?: SchemasAcceptorRoute | undefined}; export type ComponentsSchemasPan = string; export type ComponentsSchemasExpiryMonth = number; export type ComponentsSchemasExpiryYear = number; export type PosCardInput = {number: ComponentsSchemasPan, expiryMonth: ComponentsSchemasExpiryMonth, expiryYear: ComponentsSchemasExpiryYear, createProcessorToken?: boolean | undefined}; export type CommonCurrencyCode = 'AED' | 'AFN' | 'ALL' | 'AMD' | 'AOA' | 'ARS' | 'AUD' | 'AWG' | 'AZN' | 'BAM' | 'BBD' | 'BDT' | 'BHD' | 'BIF' | 'BMD' | 'BND' | 'BOB' | 'BRL' | 'BSD' | 'BTN' | 'BWP' | 'BYN' | 'BZD' | 'CAD' | 'CDF' | 'CHF' | 'CLP' | 'CNY' | 'COP' | 'CRC' | 'CUC' | 'CUP' | 'CVE' | 'CZK' | 'DJF' | 'DKK' | 'DOP' | 'DZD' | 'EGP' | 'ERN' | 'ETB' | 'EUR' | 'FJD' | 'FKP' | 'GBP' | 'GEL' | 'GHS' | 'GIP' | 'GMD' | 'GNF' | 'GTQ' | 'GYD' | 'HKD' | 'HNL' | 'HTG' | 'HUF' | 'IDR' | 'ILS' | 'INR' | 'IQD' | 'IRR' | 'ISK' | 'JMD' | 'JOD' | 'JPY' | 'KES' | 'KGS' | 'KHR' | 'KMF' | 'KPW' | 'KRW' | 'KWD' | 'KYD' | 'KZT' | 'LAK' | 'LBP' | 'LKR' | 'LRD' | 'LSL' | 'LYD' | 'MAD' | 'MDL' | 'MGA' | 'MKD' | 'MMK' | 'MNT' | 'MOP' | 'MRU' | 'MUR' | 'MVR' | 'MWK' | 'MXN' | 'MYR' | 'MZN' | 'NAD' | 'NGN' | 'NIO' | 'NOK' | 'NPR' | 'NZD' | 'OMR' | 'PAB' | 'PEN' | 'PGK' | 'PHP' | 'PKR' | 'PLN' | 'PYG' | 'QAR' | 'RON' | 'RSD' | 'RUB' | 'RWF' | 'SAR' | 'SBD' | 'SCR' | 'SDG' | 'SEK' | 'SGD' | 'SHP' | 'SOS' | 'SRD' | 'SSP' | 'STN' | 'SYP' | 'SZL' | 'THB' | 'TJS' | 'TMT' | 'TND' | 'TOP' | 'TRY' | 'TTD' | 'TWD' | 'TZS' | 'UAH' | 'UGX' | 'USD' | 'UYU' | 'UZS' | 'VES' | 'VND' | 'VUV' | 'WST' | 'XAF' | 'XCD' | 'XCG' | 'XOF' | 'XPF' | 'YER' | 'ZAR' | 'ZMW' | 'ZWL'; export type RequestAmountBreakdown = {baseAmount: number, cashback?: number | undefined}; export type RequestPosAmount = {value: number, currency: CommonCurrencyCode, breakdown?: RequestAmountBreakdown | undefined}; export type IntentPos = 'purchase' | 'reservation' | 'refund'; export type CardEntryPos = 'terminal'; export type OrderPos = 'counter'; export type ChargesPosTerminalEntryMode = 'contactless' | 'manual-entry' | 'chip' | 'magstripe' | 'magstripe-fallback'; export type SequencePos = 'subsequent'; export type ChargesPosChargePosType = {intent: IntentPos, cardEntry: CardEntryPos, order: OrderPos, terminalEntryMode: ChargesPosTerminalEntryMode, sequence?: SequencePos | undefined}; export type LocalTransactionDateTime = unknown; export type TransactionReference = string; export type Track2Data = string; export type EmvData = string; export type CardSequenceNumber = string; export type PinBlockDataIso0Iso1 = string; export type PinBlockZoneId = string; export type PinBlockKeyId = string; export type PinBlockDataIso4 = string; export type PinBlock = {format: 'ISO-0' | 'ISO-1', block: PinBlockDataIso0Iso1, zoneId: PinBlockZoneId, keyId: PinBlockKeyId} | {format: 'ISO-4', block: PinBlockDataIso4, zoneId: PinBlockZoneId, keyId: PinBlockKeyId}; export type TerminalCapability = 'contactChip' | 'contactlessChip' | 'contactMagStripe' | 'contactlessMagStripe' | 'offlineEncipheredPin' | 'offlinePlaintextPin' | 'onlinePin' | 'signature' | 'keyEntry' | 'noCvm' | 'oneTap'; export type SoftPosTerminalCapability = 'contactlessChip' | 'onlinePin' | 'signature' | 'noCvm' | 'oneTap'; export type Terminal = {type: 'pos', id: string, attended: boolean, capabilities: Array} | {type: 'mpos', id: string, attended: true, capabilities: Array} | {type: 'softpos', id: string, attended: true, capabilities: Array}; export type AllowPartialApproval = boolean; export type SchemasCountryCodeAlpha3 = string; export type ComponentsSchemasCountryCodeAlpha3 = {alpha3: SchemasCountryCodeAlpha3}; export type SchemasCountryCodeAlpha2 = string; export type ComponentsSchemasCountryCodeAlpha2 = {alpha2: SchemasCountryCodeAlpha2}; export type SchemasCountryCodeNumeric = string; export type ComponentsSchemasCountryCodeNumeric = {numeric: SchemasCountryCodeNumeric}; export type OpenapiComponentsSchemasStateOrProvince = string; export type OpenapiComponentsSchemasCity = string; export type OpenapiComponentsSchemasLine1 = string; export type OpenapiComponentsSchemasLine2 = string; export type OpenapiComponentsSchemasPostalCode = string; export type SchemasAddressInput = {countryCode: ComponentsSchemasCountryCodeAlpha3 | ComponentsSchemasCountryCodeAlpha2 | ComponentsSchemasCountryCodeNumeric, stateOrProvince?: OpenapiComponentsSchemasStateOrProvince | undefined, city: OpenapiComponentsSchemasCity, line1: OpenapiComponentsSchemasLine1, line2?: OpenapiComponentsSchemasLine2 | undefined, postalCode: OpenapiComponentsSchemasPostalCode}; export type SubMerchant = {id?: string | undefined, address?: SchemasAddressInput | undefined}; export type PointOfSaleAddressInput = {countryCode: ComponentsSchemasCountryCodeAlpha3 | ComponentsSchemasCountryCodeAlpha2 | ComponentsSchemasCountryCodeNumeric, stateOrProvince?: OpenapiComponentsSchemasStateOrProvince | undefined, city: OpenapiComponentsSchemasCity, line1: OpenapiComponentsSchemasLine1, line2?: OpenapiComponentsSchemasLine2 | undefined, postalCode: OpenapiComponentsSchemasPostalCode}; export type ClearingMode = 'auto' | 'manual'; export type ClearAfter = unknown; export type SchemasDynamicDescriptor = {merchantName?: string | undefined, merchantCity?: string | undefined}; export type ChargeCreatePos = {merchantAcceptorResolver: SchemasAcceptorResolver, card: PosCardInput, amount: RequestPosAmount, type: ChargesPosChargePosType, localTransactionDateTime?: LocalTransactionDateTime | undefined, transactionReference?: TransactionReference | undefined, track2Data?: Track2Data | undefined, emvData?: EmvData | undefined, cardSequenceNumber?: CardSequenceNumber | undefined, pinBlock?: PinBlock | undefined, terminal: Terminal, allowPartialApproval?: AllowPartialApproval | undefined, subMerchant?: SubMerchant | undefined, pointOfSaleAddress?: PointOfSaleAddressInput | undefined, clearingMode?: ClearingMode | undefined, clearAfter?: ClearAfter | undefined, dynamicDescriptor?: SchemasDynamicDescriptor | undefined}; export type CreateApiChargesPosArgs = {'Idempotency-Key'?: string | undefined, body: ChargeCreatePos}; export type CreateApiChargesPosOptions = {baseUrl?: string | undefined, ApiKey?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const chargeKey = z.string().min(5).max(120); export const componentsSchemasAcceptorKey = z.string().min(5).max(120); export const schemasVersion = z.number().int(); export const componentsSchemasAcceptorRef = z.object({key: componentsSchemasAcceptorKey, version: schemasVersion}); export const schemasProcessorTokenKey = z.string().min(5).max(120); export const outputCard = z.object({maskedNumber: z.string(), processorTokenKey: schemasProcessorTokenKey.optional()}); export const commonCurrencyCode = z.enum(["AED", "AFN", "ALL", "AMD", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BHD", "BIF", "BMD", "BND", "BOB", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHF", "CLP", "CNY", "COP", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HTG", "HUF", "IDR", "ILS", "INR", "IQD", "IRR", "ISK", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR", "MVR", "MWK", "MXN", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SOS", "SRD", "SSP", "STN", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "UYU", "UZS", "VES", "VND", "VUV", "WST", "XAF", "XCD", "XCG", "XOF", "XPF", "YER", "ZAR", "ZMW", "ZWL"]); export const responseAmountBreakdown = z.object({baseAmount: z.number().int().gte(1).lte(999999999999), cashback: z.number().int().gte(1).lte(999999999999).optional()}); export const intentPos = z.enum(["purchase", "reservation", "refund"]); export const cardEntryPos = z.literal("terminal"); export const orderPos = z.literal("counter"); export const chargesPosTerminalEntryMode = z.enum(["contactless", "manual-entry", "chip", "magstripe", "magstripe-fallback"]); export const sequencePos = z.literal("subsequent"); export const chargesPosChargePosType = z.object({intent: intentPos, cardEntry: cardEntryPos, order: orderPos, terminalEntryMode: chargesPosTerminalEntryMode, sequence: sequencePos.optional()}); export const clearingStatus = z.enum(["none", "manual", "pending", "completed", "cancelled", "abandoned"]); export const statusPos = z.object({authentication: z.literal("none"), authorization: z.enum(["none", "approved", "approved-partial", "declined", "reversed", "approved-purchase-amount-only"]), clearing: clearingStatus}); export const localTransactionDateTime = z.string(); export const transactionReference = z.string().min(1).max(120); export const newEmvData = z.string().min(1).max(510); export const terminalAction = z.enum(["requestPin", "switchInterface"]); export const isoFieldResponseCode = z.string(); export const isoFieldResponseCodeDescription = z.string(); export const isoFieldAuthorizationCode = z.string(); export const isoFieldNetworkCode = z.string(); export const isoFieldSystemTraceAuditNumber = z.string(); export const isoFieldRetrievalReferenceNumber = z.string(); export const amexSpecificFields = z.object({acquirerReferenceData: z.string(), cvcResult: z.string().optional(), avsResult: z.string().optional()}); export const discoverSpecificFields = z.object({network: z.literal("discover"), avsResponseCode: z.string().optional(), cidResultCode: z.string().optional(), networkReferenceId: z.string().optional()}); export const mastercardSpecificFields = z.object({banknetReference: z.string(), traceId: z.string(), merchantAdviceCode: z.string().optional(), cvcResult: z.string().optional(), nameValidationResult: z.string().optional(), avsResponse: z.string().optional(), paymentAccountReference: z.string().optional(), transactionLinkId: z.string().optional(), digitalCommerceProgramType: z.string().optional(), onBehalfServices: z.array(z.object({onBehalfService: z.string(), onBehalfResult1: z.string(), onBehalfResult2: z.string()})).optional()}); export const visaSpecificFields = z.object({transactionIdentifier: z.string(), cvv2ResultCode: z.string().optional(), avsResultCode: z.string().optional(), paymentAccountReference: z.string().optional(), aniResults: z.object({status: z.string(), fullNameMatch: z.string().optional(), firstNameMatch: z.string().optional(), middleNameMatch: z.string().optional(), lastNameMatch: z.string().optional()}).optional(), vaaiScore: z.string().optional(), tokenRequestorId: z.string().optional()}); export const chargesPosPosAuthorizationIsoFields = z.object({responseCode: isoFieldResponseCode, responseCodeDescription: isoFieldResponseCodeDescription, authorizationCode: isoFieldAuthorizationCode.optional(), networkCode: isoFieldNetworkCode, systemTraceAuditNumber: isoFieldSystemTraceAuditNumber, retrievalReferenceNumber: isoFieldRetrievalReferenceNumber, eci: z.literal("00"), networkSpecificFields: z.union([amexSpecificFields, discoverSpecificFields, mastercardSpecificFields, visaSpecificFields])}); export const allowPartialApproval = z.boolean(); export const schemasCountryCodeAlpha3 = z.string().min(3).max(3); export const schemasCountryCodeAlpha2 = z.string().min(2).max(2); export const schemasCountryCodeNumeric = z.string().min(3).max(3); export const schemasCountryCode = z.object({alpha3: schemasCountryCodeAlpha3, alpha2: schemasCountryCodeAlpha2, numeric: schemasCountryCodeNumeric}); export const openapiComponentsSchemasStateOrProvince = z.string().min(1).max(120); export const openapiComponentsSchemasCity = z.string().min(1).max(120); export const openapiComponentsSchemasLine1 = z.string().min(1).max(120); export const openapiComponentsSchemasLine2 = z.string().min(1).max(120); export const openapiComponentsSchemasPostalCode = z.string().min(1).max(10); export const componentsSchemasAddress = z.object({countryCode: schemasCountryCode, stateOrProvince: openapiComponentsSchemasStateOrProvince.optional(), city: openapiComponentsSchemasCity, line1: openapiComponentsSchemasLine1, line2: openapiComponentsSchemasLine2.optional(), postalCode: openapiComponentsSchemasPostalCode}); export const subMerchantResponse = z.object({id: z.string().min(1).max(15).optional(), address: componentsSchemasAddress.optional()}); export const pointOfSaleAddress = z.object({countryCode: schemasCountryCode, stateOrProvince: openapiComponentsSchemasStateOrProvince.optional(), city: openapiComponentsSchemasCity, line1: openapiComponentsSchemasLine1, line2: openapiComponentsSchemasLine2.optional(), postalCode: openapiComponentsSchemasPostalCode}); export const clearingMode = z.enum(["auto", "manual"]); export const clearAfter = z.string(); export const schemasDynamicDescriptor = z.object({merchantName: z.string().min(1).max(22).optional(), merchantCity: z.string().min(1).max(13).optional()}); export const terminalCapability = z.enum(["contactChip", "contactlessChip", "contactMagStripe", "contactlessMagStripe", "offlineEncipheredPin", "offlinePlaintextPin", "onlinePin", "signature", "keyEntry", "noCvm", "oneTap"]); export const softPosTerminalCapability = z.enum(["contactlessChip", "onlinePin", "signature", "noCvm", "oneTap"]); export const terminal = z.union([z.object({type: z.literal("pos"), id: z.string().min(1).max(8), attended: z.boolean(), capabilities: z.array(terminalCapability)}), z.object({type: z.literal("mpos"), id: z.string().min(1).max(8), attended: z.literal(true), capabilities: z.array(terminalCapability)}), z.object({type: z.literal("softpos"), id: z.string().min(1).max(8), attended: z.literal(true), capabilities: z.array(softPosTerminalCapability)})]); export const openapiComponentsSchemasCreated = z.string(); export const componentsSchemasLastModified = z.string(); export const chargeCreatePosResponse = z.object({key: chargeKey, merchantAcceptorRef: componentsSchemasAcceptorRef, card: outputCard, amount: z.object({value: z.number().int().gte(1).lte(999999999999), currency: commonCurrencyCode, breakdown: responseAmountBreakdown.optional()}), type: chargesPosChargePosType, status: statusPos, localTransactionDateTime: localTransactionDateTime, transactionReference: transactionReference.optional(), newEmvData: newEmvData.optional(), terminalAction: terminalAction.optional(), authorizationIsoFields: chargesPosPosAuthorizationIsoFields, allowPartialApproval: allowPartialApproval.optional(), subMerchant: subMerchantResponse.optional(), pointOfSaleAddress: pointOfSaleAddress.optional(), clearingMode: clearingMode.optional(), clearAfter: clearAfter.optional(), dynamicDescriptor: schemasDynamicDescriptor.optional(), terminal: terminal, created: openapiComponentsSchemasCreated, lastModified: componentsSchemasLastModified.optional(), version: schemasVersion}); 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 POS Charge * * POST /charges/pos * * Also accepts auth: BearerToken */ export const createApiChargesPos = async (args: CreateApiChargesPosArgs, options?: CreateApiChargesPosOptions) => { 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 (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (ApiKey !== undefined) headers.set('authorization', `Basic ${btoa(`${ApiKey.username}:${ApiKey.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/charges/pos${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(chargeCreatePosResponse, await res.json()) };