import {z} from 'zod' export type Amount = {amount: string, currency: string}; export type Address = {phoneNumber?: string | undefined, countryCode?: unknown | undefined, name?: string | undefined, postcode?: string | undefined, suburb?: string | undefined, line1?: string | undefined}; export type Items = Array<{gtin?: string | undefined, quantity: number, price: Amount, name: string, category: string, subcategory?: Array | undefined, sku: string, brand?: string | undefined, pageUrl?: string | undefined, imageUrl?: string | undefined}>; export type MerchantReference = string; export type Extensions = {industry?: ({travel?: ({startDate?: string | undefined, endDate?: string | undefined}) | undefined}) | undefined, type?: ({link?: ({notification: {phoneCountryCode?: string | undefined, phoneNumber?: string | undefined, preferredLanguage?: ('' | 'english' | 'italiano' | 'francais' | 'deutsch' | 'espanol' | 'dutch' | 'suomi' | 'portuguese') | undefined, emailAddress?: string | undefined, channels: Array<'email' | 'sms'>}}) | undefined}) | undefined}; export type CreateApiV2OrdersArgs = {'Idempotency-Key'?: string | undefined, body: {totalAmount: Amount, consumer: {phoneNumber: string, givenNames: string, surname: string, email: string}, billing?: Address | undefined, shipping: Address, items: Items, discounts?: (Array<{amount?: Amount | undefined, displayName?: string | undefined}>) | undefined, merchant: {redirectCancelUrl: string, redirectConfirmUrl: string}, merchantReference?: MerchantReference | undefined, shippingAmount?: Amount | undefined, taxAmount?: Amount | undefined, type?: ('' | 'online' | 'offline' | 'link') | undefined, product?: ('' | 'pay-in-3' | 'pay-in-4' | 'later' | 'pay-now-standalone') | undefined, frequency?: ({number?: number | undefined, frequencyType?: string | undefined}) | undefined, orderExpiryMilliseconds?: number | undefined, extensions?: Extensions | undefined}}; export type CreateApiV2OrdersOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiV2OrdersResponse = z.object({token: z.string(), expires: z.string().optional(), checkoutUrl: z.string().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 order * * POST /v2/orders */ export const createApiV2Orders = async (args: CreateApiV2OrdersArgs, options?: CreateApiV2OrdersOptions) => { const {baseUrl = "https://integration.api.scalapay.com", fetch: fetchFn = fetch, ApiKeyAuth} = 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 (ApiKeyAuth !== undefined) headers.set("Authorization", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/v2/orders${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(createApiV2OrdersResponse, await res.json()) };