import {z} from 'zod' export type Money = {currency: 'CHF' | 'EUR' | 'GBP', amount: unknown}; export type RedirectURL = {success_url: string, failure_url: string, cancel_url?: (string | string | null) | undefined}; export type ConsumerDetails = {email_address?: (string | string) | undefined, first_name?: (string | null) | undefined, last_name?: (string | null) | undefined, date_of_birth?: (string | null) | undefined, contact_number?: (string | null) | undefined, company_name?: (string | null) | undefined, external_consumer_id?: (string | null) | undefined, nationality?: ('CHE' | 'GBR' | 'ITA' | null) | undefined, residence_status?: ('PERMIT_C' | 'PERMIT_B' | 'OTHER_RESIDENT_PERMIT' | 'null' | null) | undefined, date_of_entry?: (string | null) | undefined, national_identification_number?: string | undefined, additional_data: unknown}; export type ExistingContractInfo = {prefill_from_existing_contract: boolean, existing_external_contract_uuid: string}; export type Product = {external_id?: (string | null) | undefined, sku?: (string | null) | undefined, name?: (string | null) | undefined, quantity: number, price: unknown, list_price?: (unknown | null) | undefined, image_thumbnail?: string | undefined, image_original?: string | undefined, additional_data: unknown, allowed_terms?: (Array | null) | undefined, description?: string | undefined, residual_value?: (unknown | null) | undefined, trade_in_option_date?: (string | null) | undefined}; export type Webhooks = {status_url: string, mapping_scheme?: string | undefined, token: string}; export type Address = {street_number?: string | undefined, street?: string | undefined, address_line_1?: string | undefined, apartment?: string | undefined, address_line_2?: (string | null) | undefined, zip_code: string, city: string, country_code: 'CH' | 'IT' | 'GB', region_code?: string | undefined, region_iso3166_2?: string | undefined, sub_region_code?: string | undefined, is_client_validated?: boolean | undefined, formatted_address?: (string | null) | undefined}; export type ClientMetadata = {ecommerce_platform?: string | undefined, locale?: string | undefined}; export type InitiateCheckout = {amount: Money, amount_format: 'MINOR_UNIT' | 'DECIMAL', redirect_urls: RedirectURL, customer_details?: ConsumerDetails | undefined, existing_contract_info?: ExistingContractInfo | undefined, products?: Array | undefined, order_reference?: string | undefined, order_description?: string | undefined, webhooks?: Webhooks | undefined, billing_address?: Address | undefined, billing_address_raw: unknown, shipping_address?: Address | undefined, shipping_address_raw: unknown, delivery_location?: ('HOME' | 'WORK' | 'IN_STORE' | 'COLLECTION_POINT' | 'null' | null) | undefined, client_metadata?: ClientMetadata | undefined, locale?: ('en' | 'fr' | 'de' | 'it') | undefined, language?: ('en' | 'fr' | 'de' | 'en-gb' | 'it') | undefined, store_id?: string | undefined, store_name?: string | undefined, store_number?: string | undefined, additional_data: unknown, allowed_terms?: (Array | null) | undefined, config: unknown, merchant_user_uuid?: (string | null) | undefined, delay_finalisation?: boolean | undefined, financial_product_type?: ('BNPL' | 'CREDIT') | undefined, pricing_structure_code?: (string | null) | undefined, order_discount_amount?: (unknown | null) | undefined, service_start_date?: (string | null) | undefined, service_end_date?: (string | null) | undefined, bank_account_number?: string | undefined}; export type CreateApiApiCheckoutV1InitArgs = {body: InitiateCheckout}; export type CreateApiApiCheckoutV1InitOptions = {baseUrl?: string | undefined, MerchantAPIAuthentication?: string | undefined, fetch?: typeof fetch | undefined}; export const initiateCheckoutResponse = z.object({action: z.literal("REDIRECT"), redirect_url: z.string(), application_uuid: z.string(), external_contract_uuid: z.string(), risk_status: z.enum(["credit_check_decline", "id_check_decline", "address_not_found_decline", "success", "null"]).nullable().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 }; /** * Contract Create * * POST /api/checkout/v1/init/ */ export const createApiApiCheckoutV1Init = async (args: CreateApiApiCheckoutV1InitArgs, options?: CreateApiApiCheckoutV1InitOptions) => { const {baseUrl = "https://sbx-origination.heidipay.io", fetch: fetchFn = fetch, MerchantAPIAuthentication} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (MerchantAPIAuthentication !== undefined) headers.set('authorization', `Bearer ${MerchantAPIAuthentication}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/checkout/v1/init/${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(initiateCheckoutResponse, await res.json()) };