/** * PayWay Client * Main client class for interacting with PayWay Payment Gateway API * Acts as a facade to coordinate service operations */ import { PayWayConfig, PaymentLinkRequest, PaymentLinkResponse, PaymentLinkDetailRequest, PaymentLinkDetailResponse } from './types'; import type { CreateQROptions, GenerateQRRequest, GenerateQRResponse, GetTransactionDetailOptions, TransactionDetailResponse, CloseTransactionOptions, CloseTransactionResponse, CheckTransactionOptions, CheckTransactionResponse, RefundOptions, RefundResponse, CompletePreAuthOptions, CompletePreAuthResponse, CancelPreAuthOptions, CancelPreAuthResponse, TransactionListOptions, TransactionListResponse, PurchaseOptions, PurchaseResponse, TokenPurchaseOptions, TokenPurchaseRequest, TokenPurchaseResponse, ExchangeRateResponse, LinkAccountOptions, LinkAccountRequest, LinkAccountResponse, RemoveAccountTokenOptions, RemoveAccountTokenRequest, RemoveAccountTokenResponse, GetLinkedAccountDetailOptions, GetLinkedAccountDetailRequest, GetLinkedAccountDetailResponse, LinkCardOptions, LinkCardRequest, LinkCardFormResponse, RemoveCardTokenOptions, RemoveCardTokenRequest, RemoveCardTokenResponse, PayoutOptions, PayoutResponse } from './types'; /** * PayWay Client for integrating with PayWay Payment Gateway * * @example * // Using environment variables * const client = new PayWayClient(); * * @example * // Using configuration * const client = new PayWayClient({ * merchantId: 'ec000002', * apiKey: 'your-api-key', * sandbox: true * }); * * @example * // Enable debug mode to log all requests and responses * const client = new PayWayClient({ * merchantId: 'ec000002', * apiKey: 'your-api-key', * sandbox: true, * debug: true // Logs all API calls with URLs, parameters, and responses * }); * * // Or set environment variable DEBUG_PAYWAY=true */ export declare class PayWayClient { private merchantId; private apiKey; private rsaPublicKey?; private baseURL; private sandbox; private debug; private httpClient; private qrService; private transactionService; private purchaseService; private paymentLinkService?; private linkAccountService; private linkCardService; private payoutService; /** * Create a new PayWay client * @param config - Client configuration * @throws {PayWayError} If required configuration is missing */ constructor(config?: PayWayConfig); /** * Get merchant ID * @returns Merchant ID */ getMerchantId(): string; /** * Get base URL * @returns Base URL of the PayWay API */ getBaseURL(): string; /** * Check if in sandbox mode * @returns true if in sandbox mode */ isSandbox(): boolean; /** * Create a QR code for payment (simplified API) * * @param options - QR creation options * @returns QR generation response with QR code and deeplinks * @throws {PayWayError} If request fails or validation errors occur * * @example * const result = await client.createQR({ * amount: 10.00, * currency: 'USD', * items: [{ name: 'Product 1', quantity: 1, price: 10.00 }] * }); */ createQR(options: CreateQROptions): Promise; /** * Generate QR code (low-level API) * * @param params - Full request parameters * @returns QR generation response * @throws {PayWayError} If API request fails */ generateQR(params: GenerateQRRequest): Promise; /** * Get transaction details * * @param options - Transaction detail options * @returns Transaction detail response with full transaction information * @throws {PayWayError} If request fails or transaction not found * * @example * const details = await client.getTransactionDetail({ * tranId: '17394277693' * }); */ getTransactionDetail(options: GetTransactionDetailOptions): Promise; /** * Close (cancel) a transaction * * If your business involves transactions that may need cancellation—such as flash sales, * hotel bookings, or ticket sales—you can use this method to cancel a transaction. * Once a transaction is closed, its payment status is updated to CANCELLED. * * @param options - Close transaction options * @returns Close transaction response with cancellation status * @throws {PayWayError} If request fails, transaction not found, or invalid merchant * * @example * const result = await client.closeTransaction({ * tranId: '1729573626' * }); * console.log(result.status.code); // '00' for success */ closeTransaction(options: CloseTransactionOptions): Promise; /** * Check transaction status (for recent transactions within 7 days) * * Get the status of a transaction created within the last 7 days. * For older transactions, use getTransactionDetail() instead. * * Rate limit: 600 requests/second (much higher than getTransactionDetail) * * @param options - Check transaction options * @returns Check transaction response with payment status * @throws {PayWayError} If request fails or transaction not found * * @example * const status = await client.checkTransaction({ * tranId: '17394277693' * }); * console.log(status.data.payment_status); // 'APPROVED', 'PENDING', etc. */ checkTransaction(options: CheckTransactionOptions): Promise; /** * Refund a transaction (full or partial) * * Issue refunds within 30 days of transaction creation. * Only COMPLETED transactions can be refunded. * Multiple partial refunds are supported. * * @param options - Refund options including RSA public key * @returns Refund response with refund status * @throws {PayWayError} If request fails or transaction ineligible * * @example * const result = await client.refundTransaction({ * tranId: '17394277693', * refundAmount: 10.00, * rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY * }); * console.log('Total refunded:', result.total_refunded); */ refundTransaction(options: RefundOptions): Promise; /** * Complete a pre-authorized transaction * * Captures funds from a pre-authorized transaction, finalizing the payment. * * Conditions: * - Can only complete pre-auth once * - Cannot complete expired or canceled transactions * - For card payments: can complete up to 10% above original amount * * @param options - Complete pre-auth options including RSA public key * @returns Complete pre-auth response with transaction status * @throws {PayWayError} If request fails or transaction ineligible * * @example * const result = await client.completePreAuth({ * tranId: '17394277693', * completeAmount: 11.00, // Up to 10% above original for cards * rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY * }); * console.log('Status:', result.transaction_status); */ completePreAuth(options: CompletePreAuthOptions): Promise; /** * Cancel a pre-authorized transaction * * Release the hold on funds for a pre-auth transaction. Cannot be undone. * Transaction status must be PRE-AUTH (not completed or already cancelled). * * Fund Release: * - ABA Pay & Cards: Instant release * - KHQR: Refunded to payer * * @param options - Cancel pre-auth options * @returns Cancel response with CANCELLED status * @throws {PayWayError} If request fails or cannot be cancelled * * @example * const result = await client.cancelPreAuth({ * tranId: '17394277693', * rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY * }); * console.log('Status:', result.transaction_status); // 'CANCELLED' */ cancelPreAuth(options: CancelPreAuthOptions): Promise; /** * Get transaction list with filters * * Retrieve transactions filtered by date, amount, status, etc. * Maximum 3 days date range. Rate limit: 50 requests/minute. * * @param options - Filter and pagination options * @returns Transaction list with pagination * @throws {PayWayError} If request fails * * @example * const list = await client.getTransactionList({ * fromDate: '2026-02-03 00:00:00', * toDate: '2026-02-05 23:59:59', * status: ['APPROVED', 'PENDING'], * page: 1, * pagination: 50 * }); * console.log('Transactions:', list.data.length); */ getTransactionList(options?: TransactionListOptions): Promise; /** * Create a purchase transaction * * Initiates a payment transaction and redirects customer to PayWay's checkout page. * * @param options - Purchase options * @returns Purchase response with checkout URL or HTML * @throws {PayWayError} If request fails or validation errors occur * * @example * const result = await client.createPurchase({ * amount: 10.00, * currency: 'USD', * items: [{ name: 'Product 1', quantity: 1, price: 10.00 }], * returnUrl: 'https://example.com/callback' * }); */ createPurchase(options: PurchaseOptions): Promise; /** * Purchase using saved token (Card on File / Account on File) * * Process payments using tokens obtained from card or account linking APIs. * This allows charging customers without requiring them to re-enter payment details. * * NOTE: Before using this API, ensure your profile has enabled Card on File or Account on File feature. * Contact merchant digital support (digitalsupport@ababank.com) for sandbox profile, * or merchant acquisition team (paywaysales@ababank.com) for production profile. * * @param options - Token purchase options * @returns Token purchase response with payment status * @throws {PayWayError} If request fails or validation errors occur * * @example * // Purchase using card token * const result = await client.purchaseWithToken({ * amount: 50.00, * ctid: 'customer-123', * pwt: 'card-token-from-linking', * items: [{ name: 'Subscription', quantity: 1, price: 50.00 }], * payer: { * firstName: 'John', * lastName: 'Doe', * email: 'john@example.com', * phone: '0123456789' * } * }); * * // Check payment status (API returns number 0 for success) * if (result.payment_status.status === 0 || result.payment_status.status === '0') { * console.log('Payment successful:', result.payment_status.pw_tran_id); * } */ purchaseWithToken(options: TokenPurchaseOptions): Promise; /** * Create token purchase (low-level API) * * @param params - Full token purchase request parameters * @returns Token purchase response * @throws {PayWayError} If API request fails */ createTokenPurchase(params: TokenPurchaseRequest): Promise; /** * Calculate HMAC SHA-512 hash for custom requests * * Generates a hash string using HMAC SHA-512 algorithm with your API key. * Useful for webhook verification or custom API integrations. * * @param data - String data to hash (concatenated request parameters) * @param apiKey - Optional API key (uses client's API key if not provided) * @returns Base64 encoded hash * @throws {PayWayError} If API key is not provided * * @example * // Calculate hash for webhook verification * const hash = client.calculateHash( * req_time + merchant_id + tran_id + amount * ); * * @example * // Calculate hash with custom API key * const hash = client.calculateHash( * 'data_to_hash', * 'custom-api-key' * ); */ calculateHash(data: string, apiKey?: string): string; /** * Get current exchange rates from ABA Bank * * Fetches the latest foreign exchange rates for multiple currencies. * Exchange rates are the same as on https://www.ababank.com/en/forex-exchange * * Rates are in KHR per unit of foreign currency. * * @returns Exchange rate response with all currency rates * @throws {PayWayError} If request fails * * @example * const rates = await client.getExchangeRate(); * console.log('USD to KHR sell rate:', rates.exchange_rates.usd?.sell); * console.log('EUR sell rate:', rates.exchange_rates.eur.sell); * console.log('THB buy rate:', rates.exchange_rates.thb.buy); */ getExchangeRate(): Promise; /** * Create a link account request for Account on File * * Returns a QR code or ABA Mobile deeplink that enables users to either scan * the QR code or use the deeplink to automatically launch the ABA Mobile app * and prompt the customer to select an ABA account to link to your platform. * Once the user finishes linking, PayWay will send pushback account details * and token to the merchant through the return_url. * * NOTE: Before using this API, ensure your profile has enabled the Account on File feature. * Contact merchant digital support (digitalsupport@ababank.com) for sandbox profile, * or merchant acquisition team (paywaysales@ababank.com) for production profile. * * @param options - Link account options * @returns Link account response with QR code and deeplink * @throws {PayWayError} If request fails or validation errors occur * * @example * const result = await client.createLinkAccount({ * returnParam: 'REQ0012', * returnUrl: Buffer.from('https://yourapp.com/api/account-linked').toString('base64'), * returnDeeplink: { * ios_scheme: 'myapp://account/linked', * android_scheme: 'myapp://account/linked' * } * }); * * console.log('Deeplink:', result.deeplink); * console.log('QR String:', result.qr_string); * console.log('QR Image URL:', result.qr_image); */ createLinkAccount(options: LinkAccountOptions): Promise; /** * Request account linking (low-level API) * * @param params - Full request parameters * @returns Link account response * @throws {PayWayError} If API request fails */ linkAccount(params: LinkAccountRequest): Promise; /** * Remove a customer's linked account token * * Removes a customer's linked account token from your platform. Once the token * is removed, this action cannot be undone, and the token will no longer be * valid for purchases. * * NOTE: Before using this API, ensure your profile has enabled the Account on File feature. * Contact merchant digital support (digitalsupport@ababank.com) for sandbox profile, * or merchant acquisition team (paywaysales@ababank.com) for production profile. * * @param options - Remove account token options * @returns Remove account token response * @throws {PayWayError} If request fails or validation errors occur * * @example * const result = await client.removeAccountToken({ * ctid: '522235C...C8FA2890C5378D7', * pwt: '522235462D55FA...6AF3DA7B968DD7B7F57A' * }); * * if (result.status.code === '00') { * console.log('Account token removed successfully'); * } else if (result.status.code === '29') { * console.error('Invalid ctid or pwt value'); * } */ removeAccountToken(options: RemoveAccountTokenOptions): Promise; /** * Remove account token (low-level API) * * @param params - Full request parameters * @returns Remove account token response * @throws {PayWayError} If API request fails */ removeAccount(params: RemoveAccountTokenRequest): Promise; /** * Get linked account details * * Retrieves linked account details if you encounter issues with the pushback * notification and do not receive the account details automatically. * * NOTE: This API only works for retrieving account tokens. It is not applicable * for card tokens. * * @param options - Get linked account detail options * @returns Linked account details with ctid, pwt, and masked account * @throws {PayWayError} If request fails or validation errors occur * * @example * const result = await client.getLinkedAccountDetail({ * returnParam: 'REQ0012' * }); * * if (result.status.code === '00') { * console.log('Account Token:', result.data.pwt); * console.log('Customer Token:', result.data.ctid); * console.log('Masked Account:', result.data.mask_account); * } else if (result.status.code === '403') { * console.log('Account linking not completed yet'); * } */ getLinkedAccountDetail(options: GetLinkedAccountDetailOptions): Promise; /** * Get linked account details (low-level API) * * @param params - Full request parameters * @returns Linked account details * @throws {PayWayError} If API request fails */ getAccountDetail(params: GetLinkedAccountDetailRequest): Promise; /** * Generate form parameters for client-side HTML form submission * * This method generates the form parameters that can be used to build an HTML form * that submits directly to PayWay. This is useful for client-side implementations * where you want to avoid sending the API key to the client. * * ⚠️ IMPORTANT: The generated form MUST include enctype="multipart/form-data" * * Validation Rules: * - returnParam: Required, max 255 characters * - email: Must be valid email format if provided, max 50 characters * - firstname, lastname: Max 50 characters * - phone: Max 20 characters * - ctid: Max 255 characters * - returnUrl, continueAddCardSuccessUrl: MUST be base64 encoded (not plain URLs) * * @param options - Link card options * @returns Form parameters including hash and formAction URL * @throws {Error} If validation fails (e.g., invalid email, field too long, invalid URL) * * @example * const formData = client.generateLinkCardFormParams({ * returnParam: 'USER-123', * ctid: '239acf04eace99ea1590857c7066acf260e', * firstname: 'Samnang', * lastname: 'Sok', * email: 'sok.samnang@gmail.com', * phone: '0123456789', * returnUrl: 'https://yourapp.com/api/card-linked' * }); * * // Form must include:
*/ generateLinkCardFormParams(options: LinkCardOptions): LinkCardFormResponse; /** * Remove a customer's linked card token * * Removes a customer's linked card token from your platform. Once the token * is removed, this action cannot be undone, and the token will no longer be * valid for purchases. * * NOTE: Before using this API, ensure your profile has enabled the Card on File feature. * Contact merchant digital support (digitalsupport@ababank.com) for sandbox profile, * or merchant acquisition team (paywaysales@ababank.com) for production profile. * * @param options - Remove card token options * @returns Remove card token response * @throws {PayWayError} If request fails or validation errors occur * * @example * const result = await client.removeCardToken({ * ctid: '522235F63E4998...ABC270FC9FE07409F6ACD716B88', * pwt: '5222359B5394FF7B...259BFE3868B08461F' * }); * * if (result.status.code === '00') { * console.log('Card token removed successfully'); * } else if (result.status.code === '29') { * console.error('Invalid ctid or pwt value'); * } else if (result.status.code === '1') { * console.error('Invalid hash value'); * } */ removeCardToken(options: RemoveCardTokenOptions): Promise; /** * Remove card token (low-level API) * * @param params - Full request parameters * @returns Remove card token response * @throws {PayWayError} If API request fails */ removeCard(params: RemoveCardTokenRequest): Promise; /** * Create a payment link * * Creates a shareable payment link that allows customers to pay via various methods. * Supports optional image upload, payment limits, expiration dates, and payout instructions. * * @param options - Payment link creation options * @param rsaPublicKey - RSA public key (optional if set in config or env) * @returns Payment link creation response * @throws {PayWayError} If RSA public key is missing or request fails * * @example * const paymentLink = await client.createPaymentLink({ * title: 'Product Purchase', * amount: 50.00, * currency: 'USD', * description: 'Premium subscription', * payment_limit: 10, * expired_date: Date.now() + 7 * 24 * 60 * 60 * 1000, // 7 days * return_url: 'https://example.com/payment-callback', * merchant_ref_no: 'LINK-001' * }); * * console.log('Payment Link:', paymentLink.data.payment_link); */ createPaymentLink(options: PaymentLinkRequest, rsaPublicKey?: string): Promise; /** * Get payment link details * * Retrieve detailed information about an existing payment link including status, * total transactions, refund information, and more. * * @param options - Payment link detail request options * @param rsaPublicKey - RSA public key (optional if set in config or env) * @returns Payment link detail response * @throws {PayWayError} If RSA public key is missing or request fails * * @example * const details = await client.getPaymentLinkDetail({ * id: 'hEbr4***xQbpGQ==' * }); * * console.log('Status:', details.data.status); // OPEN, PAID, CLOSED, EXPIRED * console.log('Total Transactions:', details.data.total_trxn); * console.log('Total Amount:', details.data.total_amount); */ getPaymentLinkDetail(options: PaymentLinkDetailRequest, rsaPublicKey?: string): Promise; /** * Create a payout transaction to distribute funds to multiple beneficiaries * * The ABA PayWay Funds Route API provides a seamless solution for splitting * and distributing payments to third parties, sellers, service providers, * or your ABA bank accounts. * * @param options - Payout options * @returns Payout response with transaction details and beneficiary information * @throws {PayWayError} If request fails or validation errors occur * * @example * const result = await client.payout({ * beneficiaries: [ * { account: '200030000', amount: 100 }, * { account: '012538302', amount: 200 } * ], * amount: 300, * currency: 'USD', * rsaPublicKey: process.env.PAYWAY_RSA_PUBLIC_KEY * }); * * console.log('Status:', result.status?.message); * console.log('Transaction ID:', result.transaction_id); */ payout(options: PayoutOptions): Promise; } export type { CreateQROptions, GenerateQRRequest, GenerateQRResponse, GetTransactionDetailOptions, TransactionDetailResponse, CloseTransactionOptions, CloseTransactionResponse, CheckTransactionOptions, CheckTransactionResponse, RefundOptions, RefundResponse, CompletePreAuthOptions, CompletePreAuthResponse, CancelPreAuthOptions, CancelPreAuthResponse, TransactionListOptions, TransactionListResponse, PurchaseOptions, PurchaseResponse, TokenPurchaseOptions, TokenPurchaseRequest, TokenPurchaseResponse, ExchangeRateResponse, LinkAccountOptions, LinkAccountRequest, LinkAccountResponse, RemoveAccountTokenOptions, RemoveAccountTokenRequest, RemoveAccountTokenResponse, GetLinkedAccountDetailOptions, GetLinkedAccountDetailRequest, GetLinkedAccountDetailResponse, LinkCardOptions, LinkCardRequest, LinkCardFormResponse, RemoveCardTokenOptions, RemoveCardTokenRequest, RemoveCardTokenResponse, PayoutOptions, PayoutResponse, };