/** * Every operation the client exposes. The names match the 0.9 API so that call * sites only change shape, not vocabulary. */ export declare const OPERATION_NAMES: readonly ["request", "confirm", "capture", "void", "refund", "paymentDetails", "checkPaymentStatus", "checkRegKey", "payPreapproved", "expireRegKey"]; type OperationName = (typeof OPERATION_NAMES)[number]; /** * Operations whose "unknown outcome" can be resolved by looking at the payment * details afterwards. `request`, the read operations and `expireRegKey` are not * in this list on purpose: a payment that was only requested moves no money and * is asked for again with a new order ID, and the others have nothing to look up. * Both lists are frozen: they decide, for every client of the process, which * calls are looked up. */ export declare const RECONCILABLE_OPERATIONS: readonly ["confirm", "capture", "void", "refund", "payPreapproved"]; type ReconcilableOperation = (typeof RECONCILABLE_OPERATIONS)[number]; /** * - `duplicate`: the call (or the order ID) already exists. The first call may well * have succeeded. * - `unresolved`: LINE Pay answered, but not with a refusal: it failed inside, is * still working on it, or cannot handle the payment in its current state. The * call may have taken effect, so the outcome is `unknown`. * - `unclassified`: every other failing code. LINE Pay refused the call. */ type ReturnCodeCategory = 'duplicate' | 'unresolved' | 'unclassified'; type LinePayErrorCode = 'LINE_PAY_VALIDATION_ERROR' | 'LINE_PAY_API_ERROR' | 'LINE_PAY_HTTP_ERROR' | 'LINE_PAY_NETWORK_ERROR' | 'LINE_PAY_TIMEOUT_ERROR' | 'LINE_PAY_ABORT_ERROR' | 'LINE_PAY_MIDDLEWARE_ERROR'; /** * What the caller may assume about the request that failed. * * - `not-sent`: the request definitely did not leave this process (or never * got past the connection phase), so nothing moved. A request that failed on * the way out can be sent again as it is; one that was refused as invalid has * to be fixed first. "Definitely" rests on the `fetch` in use sending a request * once per call, and refusing redirects. * - `unknown`: the request may have reached LINE Pay and may have been * processed, but no trustworthy response came back. Do not treat it as a * failure; for operations that move money, use `reconcile`. * - `rejected`: LINE Pay (or something in front of it) refused the request. */ type Outcome = 'not-sent' | 'unknown' | 'rejected'; /** * One problem with an input or a configuration. * * `path` is where it is, written the way the field is reached: `amount`, * `packages[0].products[1].price`, `transactionId[2]`. For an input it is relative * to the input object, and `input` alone means the whole input (it is not an * object that can be copied, say). The call options, the second argument of a * call, are `options.timeout` and `options.signal`: the input of `request` has an * `options` field of its own, whose paths read `options.payment.capture`. For a * configuration it is relative to the configuration object (`timeouts.refund`). */ interface ValidationIssue { readonly path: string; readonly message: string; } /** * The minimum facts `reconcile` needs to look a call up. The client attaches one * to the error of every call that was made (`error.context`); an error that comes * before there is a call, such as bad call options, has none. It never contains * headers, signatures or the channel secret. * * To reconcile a call whose error you never saw, because the process died before * it got an answer, write one down before making the call and pass it to * `client.reconcile` later. Every field it needs must be there, with the type * shown, or `reconcile` answers `indeterminate` and says which one is wrong: * * | operation | needs | also uses | * | ---------------- | ------------------------------------- | -------------- | * | `confirm` | `transactionId`, `amount`, `currency` | | * | `capture` | `transactionId`, `amount`, `currency` | | * | `void` | `transactionId` | | * | `refund` | `transactionId` | `refundAmount` | * | `payPreapproved` | `orderId`, `amount`, `currency` | | * * `channelId` is on the context of every error: keep it on a context you save. * When a context carries one, `reconcile` refuses to look it up with a client of * another channel. Without one it never concludes `not-applied` from a payment * that is not there: a client with the wrong credentials sees nothing, and * "nothing" would read as "it did not happen". */ interface ReconcileContext { readonly operation: OperationName; /** * When the call began. A refund, and a pre-approved payment, are looked for * from this second on. A context that was saved comes back from JSON with a * string or a number here, and `reconcile` accepts an ISO 8601 string with a * time zone or milliseconds too. */ readonly startedAt: Date; /** The channel of the client that made the call. */ readonly channelId?: string; /** 1 to 19 digits, as a string. */ readonly transactionId?: string; /** As a string, the one of the call. */ readonly orderId?: string; /** What the call asked for; the payment must match it. */ readonly amount?: number; readonly currency?: string; /** Leave it out for a full refund. */ readonly refundAmount?: number; } interface ReconcileConclusion { readonly status: 'not-applied' | 'indeterminate'; readonly reason: string; } /** * How a call went, as far as it is known: `result.meta` for a call that succeeded * and `error.meta` for one that failed, in the same shape. */ interface CallMeta { operation: OperationName; startedAt: Date; /** Total time in milliseconds, retries and waiting between them included. */ durationMs: number; /** * How many times the request was attempted, including attempts that never * connected. A call that was refused before it could be sent counts as one. */ attempts: number; /** * HTTP status of the last response. Absent when there was none: a network * error, a timeout, an abort, an input that was refused, or a result that was * recovered by `reconcile` (the original call never produced a response). */ httpStatus?: number; } /** The part of the init of every error that is not about its own kind. */ interface LinePayErrorOptions { /** The operation that was being called, when there is one. */ readonly operation?: OperationName | undefined; /** The failure underneath, kept as `error.cause`. */ readonly cause?: unknown; } interface LinePayErrorInit extends LinePayErrorOptions { readonly outcome: Outcome; } /** * The safe view of an error that `toJSON()` returns and that `console.log` and * `util.inspect` print: no response body, no context, no headers or signatures, * and the cause as its message alone. A key that has no value is left out. */ interface LinePayErrorJSON { readonly name: string; readonly code: LinePayErrorCode; readonly message: string; readonly outcome: Outcome; readonly operation?: OperationName; /** `startedAt` is an ISO 8601 string. */ readonly meta?: { readonly operation: OperationName; readonly startedAt: string; readonly durationMs: number; readonly attempts: number; readonly httpStatus?: number; }; readonly reconcileConclusion?: ReconcileConclusion; /** The message of the cause, with the paths of any URLs in it removed. */ readonly cause?: string; } /** * Base class of every error this library throws on purpose. It cannot be * constructed itself: what an error is, is its class, and `code` tells which one * (see {@link AnyLinePayError}). * * `operation`, `context`, `meta` and `reconcileConclusion` are filled in after the * error was made, by the client and by the `retryWhenNotSent` and `autoReconcile` * middleware, so they can be assigned; they are absent until then. * * The brand is not part of the type: a `unique symbol` in the declarations is a * different type in the ESM and in the CommonJS copy of them, and an error of one * would not be assignable to the other. * * An error does not survive `structuredClone` or `postMessage` as one of these * classes: the copy is a plain `Error` with the name, message, stack and cause. * Send `error.toJSON()` instead. */ export declare abstract class LinePayError extends Error { /** Which class the error is. */ abstract readonly code: LinePayErrorCode; readonly outcome: Outcome; /** The operation that was being called. Set when it is known. */ operation?: OperationName | undefined; /** * Attached by the client so that `reconcile` can look the call up again. Not * enumerable, like the response body: a logger that copies the properties of an * error does not write down the order and the transaction. */ context?: ReconcileContext | undefined; /** How the call went; the totals of a retry are in it. */ meta?: CallMeta | undefined; /** Set by `autoReconcile` when it could not resolve the call to "applied". */ reconcileConclusion?: ReconcileConclusion | undefined; protected constructor(name: string, message: string, init: LinePayErrorInit); /** A safe, loggable view: no headers, secrets or signatures. */ toJSON(): LinePayErrorJSON; } interface LinePayValidationErrorInit extends LinePayErrorOptions { /** Every problem that was found, not only the first. */ readonly issues: readonly ValidationIssue[]; /** What was checked. `input` by default. */ readonly subject?: 'input' | 'configuration'; } /** The input or the configuration is invalid. Nothing was sent. */ export declare class LinePayValidationError extends LinePayError { readonly code = "LINE_PAY_VALIDATION_ERROR"; readonly outcome: 'not-sent'; readonly issues: readonly ValidationIssue[]; constructor(init: LinePayValidationErrorInit); toJSON(): LinePayErrorJSON & { readonly issues: readonly ValidationIssue[]; }; } interface LinePayApiBody { returnCode: string; returnMessage: string; [key: string]: unknown; } interface LinePayApiErrorInit { /** The response body, with a `returnMessage` (an empty one if LINE Pay sent none). */ readonly body: LinePayApiBody; readonly httpStatus: number; /** The category of `body.returnCode` by default. */ readonly category?: ReturnCodeCategory; /** * `unknown` for the category `unresolved`, `rejected` for any other by default. */ readonly outcome?: 'rejected' | 'unknown'; readonly operation?: OperationName | undefined; } /** * LINE Pay answered, and the `returnCode` says the request failed (`rejected`). * It is `unknown` when the answer does not say that the call was refused: a code * of the category `unresolved` (an internal error, a payment that is still being * processed), or a status the operation does not define. */ export declare class LinePayApiError extends LinePayError { readonly code = "LINE_PAY_API_ERROR"; readonly outcome: 'rejected' | 'unknown'; readonly returnCode: string; readonly returnMessage: string; readonly httpStatus: number; /** * The response body as LINE Pay sent it. Not enumerable: a logger that copies * the properties of an error does not write it down. */ readonly body: LinePayApiBody; readonly category: ReturnCodeCategory; constructor(init: LinePayApiErrorInit); toJSON(): LinePayErrorJSON & { readonly returnCode: string; readonly returnMessage: string; readonly httpStatus: number; readonly category: ReturnCodeCategory; }; } type HttpErrorReason = 'http-status' | 'invalid-response' | 'unexpected-shape' | 'body-too-large'; interface LinePayHttpErrorInit extends LinePayErrorOptions { readonly httpStatus: number; readonly reason: HttpErrorReason; /** `rejected` for a status of 4xx, `unknown` for anything else. */ readonly outcome: 'rejected' | 'unknown'; readonly body?: unknown; readonly bodyText?: string | undefined; } /** * The HTTP status was not 2xx, the body of a 2xx response is not a LINE Pay * response (for example an HTML page from a proxy), or it is one without the * fields that the operation promises (`reason: 'unexpected-shape'`, the body as * it was received is in `body`). */ export declare class LinePayHttpError extends LinePayError { readonly code = "LINE_PAY_HTTP_ERROR"; readonly outcome: 'rejected' | 'unknown'; readonly httpStatus: number; readonly reason: HttpErrorReason; /** * The `returnCode` of the answer, for `reason: 'unexpected-shape'` only: an * answer of LINE Pay (it has a return code, four digits) that is not the one the * operation promises. `'0000'` there means that LINE Pay answered that the call * succeeded, only not in the shape this library promises. * * For every other reason there is no property. The body is not an answer of LINE * Pay (an HTML page of a proxy, JSON of something else), or it came with an HTTP * status that is not 2xx, and a `returnCode` in it says nothing about the call. * * It is diagnostic: it does not change the outcome (`unknown`); `reconcile` is * what finds out what became of the call. */ readonly returnCode?: string | undefined; /** * What was received, parsed (for an answer that is no LINE Pay response, or * not the one the operation promises). Not enumerable, like `bodyText`. */ readonly body?: unknown; /** Start of the response text, cut at 2 KB. Not enumerable. */ readonly bodyText?: string | undefined; constructor(init: LinePayHttpErrorInit); toJSON(): LinePayErrorJSON & { readonly httpStatus: number; readonly reason: HttpErrorReason; readonly returnCode?: string; }; } type NetworkErrorReason = 'connection-refused' | 'dns' | 'network-unreachable' | 'connection-reset' | 'redirect' | 'other'; interface LinePayNetworkErrorInit extends LinePayErrorOptions { readonly reason: NetworkErrorReason; /** Node.js error code of the underlying failure, for example `ECONNREFUSED`. */ readonly causeCode?: string | undefined; /** `not-sent` only when the connection was never made. */ readonly outcome: 'not-sent' | 'unknown'; } /** `fetch` failed before a usable HTTP response arrived. */ export declare class LinePayNetworkError extends LinePayError { readonly code = "LINE_PAY_NETWORK_ERROR"; readonly outcome: 'not-sent' | 'unknown'; readonly reason: NetworkErrorReason; /** Node.js error code of the underlying failure, for example `ECONNREFUSED`. */ readonly causeCode?: string | undefined; constructor(init: LinePayNetworkErrorInit); toJSON(): LinePayErrorJSON & { readonly reason: NetworkErrorReason; readonly causeCode?: string; }; } interface LinePayTimeoutErrorInit extends LinePayErrorOptions { /** The limit that passed, in milliseconds. */ readonly timeoutMs: number; } /** The time limit passed before LINE Pay answered. The outcome is unknown. */ export declare class LinePayTimeoutError extends LinePayError { readonly code = "LINE_PAY_TIMEOUT_ERROR"; readonly outcome: 'unknown'; readonly timeoutMs: number; constructor(init: LinePayTimeoutErrorInit); toJSON(): LinePayErrorJSON & { readonly timeoutMs: number; }; } interface LinePayAbortErrorInit { /** What the signal was aborted with. It is also the `cause`. */ readonly abortReason: unknown; /** `not-sent` when the request had not gone out yet. */ readonly outcome: 'not-sent' | 'unknown'; readonly operation?: OperationName | undefined; } /** The caller's `AbortSignal` fired. */ export declare class LinePayAbortError extends LinePayError { readonly code = "LINE_PAY_ABORT_ERROR"; readonly outcome: 'not-sent' | 'unknown'; readonly abortReason: unknown; constructor(init: LinePayAbortErrorInit); } interface LinePayMiddlewareErrorInit extends LinePayErrorOptions { /** The operation whose result was wrong. */ readonly operation: OperationName; } /** * A middleware handed back something that is not the result of the operation. The * request may well have been sent, and have taken effect: the outcome is unknown, * and the error carries the context, so that `reconcile` can look the call up. */ export declare class LinePayMiddlewareError extends LinePayError { readonly code = "LINE_PAY_MIDDLEWARE_ERROR"; readonly outcome: 'unknown'; constructor(init: LinePayMiddlewareErrorInit); } /** * An error of this library, as one of its classes. `code` tells them apart, so * that a `switch` on it narrows the error to its class (and to the `outcome` it * can have), and the compiler can check that every class is handled. */ type AnyLinePayError = LinePayValidationError | LinePayApiError | LinePayHttpError | LinePayNetworkError | LinePayTimeoutError | LinePayAbortError | LinePayMiddlewareError; export declare function isLinePayError(error: unknown): error is AnyLinePayError; export declare function isLinePayValidationError(error: unknown): error is LinePayValidationError; export declare function isLinePayApiError(error: unknown): error is LinePayApiError; export declare function isLinePayHttpError(error: unknown): error is LinePayHttpError; export declare function isLinePayNetworkError(error: unknown): error is LinePayNetworkError; export declare function isLinePayTimeoutError(error: unknown): error is LinePayTimeoutError; export declare function isLinePayAbortError(error: unknown): error is LinePayAbortError; export declare function isLinePayMiddlewareError(error: unknown): error is LinePayMiddlewareError; /** * An error of a call that `client.reconcile` can look up: it carries the context. * It is what `needsReconcile` narrows to, and not plain `AnyLinePayError`: a type * guard to the union would leave `never` in the `else` branch of an error that * is a `LinePayError` but needs no lookup. */ type ReconcilableError = AnyLinePayError & { context: ReconcileContext; }; /** * `true` when the failed call may already have taken effect and can be looked up * with `client.reconcile(error)`: its outcome is unknown, or LINE Pay said it * is a duplicate (`category: 'duplicate'`). Only operations that move money or * change state qualify. */ export declare function needsReconcile(error: unknown): error is ReconcilableError; /** * Payment currency (ISO 4217). * * The V4 request and confirm references list USD, TWD and THB. * A merchant channel may support only a subset of these currencies. */ type Currency = 'USD' | 'TWD' | 'THB'; /** A string union that still accepts values this library does not know yet. */ type OpenString = T | (string & Record); /** Fields every LINE Pay response carries. */ interface LinePayResponse { /** `0000` on success. Other codes that start with `0` are status codes. */ returnCode: string; returnMessage: string; } interface Product { /** ID of the product in the merchant's system. */ id?: string; name: string; imageUrl?: string; quantity: number; /** Price of one unit. */ price: number; originalPrice?: number; } interface Recipient { firstName?: string; lastName?: string; firstNameOptional?: string; lastNameOptional?: string; email?: string; phoneNo?: string; } interface Address { country?: string; postalCode?: string; state?: string; city?: string; detail?: string; optional?: string; recipient?: Recipient; } type PayMethod = OpenString<'CREDIT_CARD' | 'BALANCE' | 'DISCOUNT'>; /** One payment method used for a payment. */ interface PayInfo { method: PayMethod; amount: number; /** Nickname of the credit card (pre-approved payment only). */ creditCardNickname?: string; /** `VISA`, `MASTER`, `AMEX`, `DINERS` or `JCB` (pre-approved payment only). */ creditCardBrand?: string; /** For example `**** **** **** 1234`. Taiwan merchants only, on request. */ maskedCreditCardNumber?: string; } /** Shipping chosen by the user, as returned after the payment was approved. */ interface SelectedShipping { methodId: string; feeAmount: number; address?: Address; } /** A package in a response. Confirm omits `products`; payment details has them. */ interface ResponsePackage { id: string; name?: string; /** `sum(products[].quantity * products[].price)` */ amount: number; userFeeAmount?: number; products?: Product[]; } /** * Electronic Payment Institution information added to responses of the V4 API. * * V4 identifies a payment provider by a string, usually TSP or EPI. * Unknown future strings are permitted for forward compatibility. */ type PaymentProvider = OpenString<'TSP' | 'EPI'>; interface CaptureOptions { extra: { /** * Points restriction (Taiwan only). `useLimit` is the amount that cannot be * paid with points; `rewardLimit` the amount that earns no reward points. */ promotionRestriction: Record; }; } /** Fields of the capture API. `transactionId` goes into the URL. */ interface CaptureInput { transactionId: string; amount: number; currency: Currency; options?: CaptureOptions; } interface CaptureResponse extends LinePayResponse { info: { orderId: string; transactionId: string; payInfo: PayInfo[]; /** V4 settlement provider (`TSP` or `EPI`), when supplied. */ paymentProvider?: PaymentProvider; }; } interface CheckPaymentStatusInput { transactionId: string; } /** * The status of the request is carried by `returnCode`; codes that start with `0` * are returned as they are and not thrown. **Here `0000` is not a success**: * * | `returnCode` | Meaning | * | ------------ | -------------------------------------------------------- | * | `0000` | The user has not authorized the payment yet. | * | `0110` | Authorized: `confirm` can be called. | * | `0121` | Canceled by the user, or timed out (20 minutes). Final. | * | `0122` | Failed. Final. | * | `0123` | Completed. Final. | * * Mark an order paid on the result of `confirm` (or of `reconcile`), never on * what this says. * * The V4 status-check reference defines all five return codes, including 0110. * Sandbox testing has observed 0000, 0121, 0122 and 0123. Observing 0110 * requires a buyer to authorize a sandbox request before confirm. */ interface CheckPaymentStatusResponse extends LinePayResponse { info?: { shipping?: { methodId: string; feeAmount: number; }; }[]; } /** Fields of the check regKey API. `regKey` goes into the URL. */ interface CheckRegKeyInput { regKey: string; /** * `true` verifies the card with a minimum authorization (needs approval from * the LINE Pay manager). `false` checks the status with LINE Pay only. A check * with `true` is not repeated by `retryWhenNotSent` after an unknown outcome. */ creditCardAuth?: boolean; } type CheckRegKeyResponse = LinePayResponse; /** Fields of the confirm API. `transactionId` goes into the URL. */ interface ConfirmInput { /** * Transaction ID returned by `request`. It is also on the confirmUrl, but that * one comes from the browser: use the ID you stored for the order, or check * that the one from the URL is that one. */ transactionId: string; /** Must equal the amount of the request. */ amount: number; currency: Currency; } interface ConfirmResponse extends LinePayResponse { info: { orderId: string; transactionId: string; /** Only when the payment was authorized without capture. ISO 8601. */ authorizationExpireDate?: string; /** * Key for payments without approval (15 characters). It is only returned * here, so store it right away. */ regKey?: string; payInfo: PayInfo[]; packages?: ResponsePackage[]; shipping?: SelectedShipping; /** V4 settlement provider (`TSP` or `EPI`), when supplied. */ paymentProvider?: PaymentProvider; }; } interface ExpireRegKeyInput { regKey: string; } type ExpireRegKeyResponse = LinePayResponse; /** Fields of the pre-approved payment API. `regKey` goes into the URL. */ interface PayPreapprovedInput { regKey: string; productName: string; amount: number; currency: Currency; /** A unique order ID, at most 100 characters. Also the key to reconcile. */ orderId: string; /** `false` only authorizes; capture later with `capture`. */ capture?: boolean; } interface PayPreapprovedResponse extends LinePayResponse { info: { orderId?: string; /** 19 digits. */ transactionId: string; /** ISO 8601. */ transactionDate: string; /** The V4 clearing provider (TSP or EPI). */ paymentProvider?: PaymentProvider; /** ISO 8601. Only when `capture` is `false`. */ authorizationExpireDate?: string; }; } /** * Query of the payment details API. Pass at least one of the two ID lists. * * V4 sandbox accepts multiple IDs as repeated parameters * (`transactionId=1&transactionId=2`), as well as comma-joined values. * The SDK sends repeated parameters for both transactionId and orderId. */ interface PaymentDetailsInput { /** Transaction IDs of payments or refunds. */ transactionId?: string[]; /** Your order IDs. */ orderId?: string[]; } interface RefundEntry { /** 19 digits. */ refundTransactionId: string; /** `PAYMENT_REFUND` or `PARTIAL_REFUND`. */ transactionType: OpenString<'PAYMENT_REFUND' | 'PARTIAL_REFUND'>; /** * The amount that was refunded. The sandbox has been observed to report it as * a negative number, so compare absolute values. */ refundAmount: number; /** ISO 8601. */ refundTransactionDate: string; } interface PromotionEvent { /** Alphanumeric event code. */ code: string; totalAmount: number; productQuantity: number; } /** * One payment or refund in the payment details. Sandbox confirmed standalone * refund entries have a refund transaction type, originalTransactionId and * positive payInfo amounts; the original payment carries a refundList with * negative refundAmount values. Other fields differ by entry type. */ interface PaymentDetailsInfo { /** 19 digits. */ transactionId: string; /** `PAYMENT`, `PAYMENT_REFUND` or `PARTIAL_REFUND`. */ transactionType: OpenString<'PAYMENT' | 'PAYMENT_REFUND' | 'PARTIAL_REFUND'>; orderId?: string; /** ISO 8601. */ transactionDate?: string; /** * - `CAPTURE`: captured * - `AUTHORIZATION`: authorized, not yet captured * - `VOIDED_AUTHORIZATION`: authorization voided * - `EXPIRED_AUTHORIZATION`: authorization expired */ payStatus?: OpenString<'CAPTURE' | 'AUTHORIZATION' | 'VOIDED_AUTHORIZATION' | 'EXPIRED_AUTHORIZATION'>; productName?: string; merchantName?: string; /** ISO 4217. Older transactions can be in a currency the library no longer lists. */ currency?: string; /** ISO 8601. Also observed on captured payments; absent from refund entries. */ authorizationExpireDate?: string; payInfo?: PayInfo[]; /** Refunds of the original transaction. */ refundList?: RefundEntry[]; /** Set when this entry is a refund: the payment that was refunded (19 digits). */ originalTransactionId?: string; packages?: ResponsePackage[]; shipping?: SelectedShipping; events?: PromotionEvent[]; /** Observed as "TSP" on sandbox payment and refund entries. */ paymentProvider?: PaymentProvider; } interface PaymentDetailsResponse extends LinePayResponse { info: PaymentDetailsInfo[]; } /** Fields of the refund API. `transactionId` goes into the URL. */ interface RefundInput { /** The transaction ID of the payment to refund. */ transactionId: string; /** Leave it out to refund the whole payment. */ refundAmount?: number; } interface RefundResponse extends LinePayResponse { info: { /** The newly issued transaction ID of the refund. */ refundTransactionId: string; /** ISO 8601. */ refundTransactionDate: string; /** Provider observed on V4 sandbox refund responses. */ paymentProvider?: PaymentProvider; }; } interface RequestPackage { /** A unique ID of the package. */ id: string; /** `sum(products[].quantity * products[].price)` */ amount: number; /** Commission included in the payment amount, if any. */ userFee?: number; /** Name of the package or of an internal shop. */ name?: string; products: Product[]; } interface RedirectUrlsWithCallbacks { /** Prevents phishing when moving between apps on Android. */ appPackageName?: string; /** Where the user is sent after approving the payment. */ confirmUrl: string; /** * How the confirmUrl is used. `NONE` means no redirect: poll * `checkPaymentStatus` instead. * * V4 supports NONE to use polling without redirect callbacks. */ confirmUrlType?: OpenString<'CLIENT' | 'SERVER'>; /** Where the user is sent after cancelling on the LINE Pay page. */ cancelUrl: string; } /** Poll the payment request status instead of receiving redirect callbacks. */ interface RedirectUrlsWithoutCallbacks { confirmUrlType: 'NONE'; /** URLs are not used when no callback is requested. */ confirmUrl?: never; cancelUrl?: never; appPackageName?: string; } type RedirectUrls = RedirectUrlsWithCallbacks | RedirectUrlsWithoutCallbacks; interface PaymentOptions { /** * `true` authorizes and captures at confirm. `false` only authorizes, and the * payment has to be captured with `capture`. Not available by default: contact * LINE Pay to enable it. */ capture?: boolean; /** `PREAPPROVED` registers the user for payments without approval (regKey). */ payType?: 'NORMAL' | 'PREAPPROVED'; } interface DisplayOptions { /** Language of the payment screen: `en`, `ja`, `ko`, `th`, `zh_TW` or `zh_CN`. */ locale?: string; /** Guide the user back to the LINE Pay browser when the confirmUrl browser differs. */ checkConfirmUrlBrowser?: boolean; } interface ShippingOptions { /** `NO_SHIPPING`, `FIXED_ADDRESS` or `SHIPPING`. */ type?: OpenString<'NO_SHIPPING' | 'FIXED_ADDRESS' | 'SHIPPING'>; feeAmount?: number; /** URL LINE Pay calls to look up the shipping method and fee. */ feeInquiryUrl?: string; /** `CONDITION` re-checks the fee when the address changes; `FIXED` does not. */ feeInquiryType?: OpenString<'CONDITION' | 'FIXED'>; address?: Address; } interface AddFriend { /** Service type of the friend list, for example `lineAt`. */ type?: string; idList?: string[]; } interface FamilyServiceOptions { addFriends?: AddFriend[]; } interface ExtraOptions { /** Only the first 100 characters are shown. */ branchName?: string; branchId?: string; } interface RequestPaymentOptions { payment?: PaymentOptions; display?: DisplayOptions; shipping?: ShippingOptions; familyService?: FamilyServiceOptions; extra?: ExtraOptions; /** * Pre-approved payment registration settings added to the V4 request. * * TODO(v4-spec): the child fields remain unverified. Sandbox testing * requires a merchant enabled for PREAPPROVED (otherwise return code 1194). * Keep the input opaque until that flow can be tested. */ regPayRequest?: Record; } /** Fields sent in the body of the request API. */ interface RequestPaymentInput { /** `sum(packages[].amount) + sum(packages[].userFee) + options.shipping.feeAmount` */ amount: number; currency: Currency; /** Your unique order ID, at most 100 characters. */ orderId: string; packages: RequestPackage[]; redirectUrls: RedirectUrls; options?: RequestPaymentOptions; } interface RequestPaymentResponse extends LinePayResponse { info: { /** Use it to confirm, void, capture or refund the payment later. */ transactionId: string; /** The code entered when a code is used instead of the scanner. */ paymentAccessToken?: string; paymentUrl: { /** Opens the LINE Pay app from your app. */ app?: string; /** The LINE Pay payment page. In a desktop pop-up use 700 x 546 px. */ web: string; }; }; } /** Voids an authorization that has not been captured. */ interface VoidInput { transactionId: string; } type VoidResponse = LinePayResponse; /** Input and response type of every operation, keyed by operation name. */ interface OperationTypes { request: { input: RequestPaymentInput; output: RequestPaymentResponse; }; confirm: { input: ConfirmInput; output: ConfirmResponse; }; capture: { input: CaptureInput; output: CaptureResponse; }; void: { input: VoidInput; output: VoidResponse; }; refund: { input: RefundInput; output: RefundResponse; }; paymentDetails: { input: PaymentDetailsInput; output: PaymentDetailsResponse; }; checkPaymentStatus: { input: CheckPaymentStatusInput; output: CheckPaymentStatusResponse; }; checkRegKey: { input: CheckRegKeyInput; output: CheckRegKeyResponse; }; payPreapproved: { input: PayPreapprovedInput; output: PayPreapprovedResponse; }; expireRegKey: { input: ExpireRegKeyInput; output: ExpireRegKeyResponse; }; } type OperationInput = OperationTypes[K]['input']; type OperationOutput = OperationTypes[K]['output']; /** Union of every operation's input, tagged by name: narrow with `operation`. */ type AnyOperationInput = { [K in OperationName]: OperationInput; }[OperationName]; /** Settings of one call. They are separate from the fields sent to LINE Pay. */ interface CallOptions { /** * Time limit of this attempt in milliseconds. Overrides `timeouts[operation]` * and `timeout` of the client configuration, and the operation's default. */ timeout?: number; /** * Cancels the call. Use `AbortSignal.timeout(8000)` to bound the total time, * retries included. */ signal?: AbortSignal; } /** How a call that succeeded went; a call that failed has the {@link CallMeta} on its error. */ interface ResultMeta extends CallMeta { /** Present only when `reconcile` inferred this result after an unknown outcome. */ recovered?: RecoveryInfo; } /** Why a result was inferred instead of received. Log it: it is part of the audit trail. */ interface RecoveryInfo { /** `unknown-outcome`: a timeout or a cut connection. `duplicate`: LINE Pay answered with a duplicate code. */ reason: 'unknown-outcome' | 'duplicate'; /** The error that made the recovery necessary. */ cause: AnyLinePayError; /** What the evidence does not show. Read them. */ notes: readonly string[]; } interface LinePayResult { /** The LINE Pay response as it was sent. IDs beyond 2^53 are strings. */ body: Body; meta: ResultMeta; } /** What a middleware sees of one call. */ interface CallContext { readonly operation: K; readonly input: OperationInput; readonly options: Readonly; readonly startedAt: Date; /** The client the call was made on, with its complete middleware stack. */ readonly client: LinePayClient; } /** A context of any operation. Narrow it by checking `operation`. */ type AnyCallContext = { [K in OperationName]: CallContext; }[OperationName]; /** * The result of the operation `K`. For several operations at once it is the * union of their results, which is what the compiler needs to follow a call * through code that is generic over the operation. */ type ResultOf = { [P in K]: LinePayResult>; }[K]; /** A result of any operation. */ type AnyResult = ResultOf; /** * Wraps a call. Call `next()` to continue with the inner middleware and, in the end, * the request. `next()` may be called more than once, as a retry does. * Middleware registered first is the outermost. */ type Middleware = (ctx: AnyCallContext, next: () => Promise) => Promise; /** * A call that took effect, as `reconcile` found it in the payment details. For * several operations at once it is the union of their results, tagged by * `operation`: narrow it by checking that field. */ type AppliedResult = { [P in K]: { status: 'applied'; operation: P; body: OperationOutput

; notes: readonly string[]; }; }[K]; /** * What `reconcile` found out about a call whose outcome was unknown. * * - `applied`: LINE Pay did process it. `body` is built from the payment details, * not received from the API. * - `not-applied`: it did not take effect. Either the error proves it (the * request was never sent, or LINE Pay refused it), or the payment details show * no sign of it. The second kind is never concluded for a refund, whose absence * from the details proves nothing, nor for a context that does not name its * channel. It is what one look found: a payment that is still being processed * shows up later, so look again after a while before repeating. LINE Pay is * expected to refuse a second confirm, capture or void when the first took * effect (verify that in the V4 sandbox); a second payPreapproved is refused * only with the same orderId, and a new orderId is a new payment. * - `indeterminate`: the evidence does not settle it. Look again later, or check * the Merchant Center. */ type ReconcileResult = AppliedResult | { status: 'not-applied'; operation: ReconcilableOperation; reason: string; } | { status: 'indeterminate'; /** Absent when the error carries nothing to look up. */ operation?: OperationName; reason: string; }; /** * A LINE Pay client. It is immutable: `with()` returns a new client. * * Every method takes one flat input object (path parameters and body or query * fields side by side) and an optional {@link CallOptions}. */ interface LinePayClient { /** * Reserve a payment. Send the user to `body.info.paymentUrl.web` (or `.app`, * from an app), then call `confirm` when they return to your confirmUrl. * * @example * const { body } = await linePay.request({ * amount: 1000, * currency: 'TWD', * orderId: 'order-1', * packages: [{ id: 'p1', amount: 1000, products: [{ name: 'Tea', quantity: 2, price: 500 }] }], * redirectUrls: { confirmUrl: 'https://shop.example/confirm', cancelUrl: 'https://shop.example/cancel' } * }) */ request(input: RequestPaymentInput, options?: CallOptions): Promise>; /** * Complete the payment after the user approved it. An unknown outcome (a * timeout) does not mean the payment failed; see `reconcile`. * * @example * const { body } = await linePay.confirm({ transactionId, amount: 1000, currency: 'TWD' }) */ confirm(input: ConfirmInput, options?: CallOptions): Promise>; /** Capture a payment that was authorized only (`options.payment.capture` was `false`). */ capture(input: CaptureInput, options?: CallOptions): Promise>; /** Void an authorization that has not been captured. */ void(input: VoidInput, options?: CallOptions): Promise>; /** * Refund a payment, fully or partially. A refund is not idempotent: never * repeat it blindly after an unknown outcome. * * @example * const { body } = await linePay.refund({ transactionId, refundAmount: 20 }) */ refund(input: RefundInput, options?: CallOptions): Promise>; /** Look up payments, refunds and orders by transaction ID or order ID. */ paymentDetails(input: PaymentDetailsInput, options?: CallOptions): Promise>; /** Poll whether the user approved a payment request (instead of using the confirmUrl). */ checkPaymentStatus(input: CheckPaymentStatusInput, options?: CallOptions): Promise>; /** Check the status of a registration key (pre-approved payment). */ checkRegKey(input: CheckRegKeyInput, options?: CallOptions): Promise>; /** Charge a registration key without user approval. */ payPreapproved(input: PayPreapprovedInput, options?: CallOptions): Promise>; /** Expire a registration key. */ expireRegKey(input: ExpireRegKeyInput, options?: CallOptions): Promise>; /** * Returns a new client with more middleware, placed inside the existing stack. * The client it is called on does not change. */ with(...middleware: Middleware[]): LinePayClient; /** * Find out, from the payment details, whether a call with an unknown outcome * (a timeout, a cut connection, or a duplicate answer) took effect. It only * concludes from evidence and never repeats the operation. * * Pass the error the call threw. If the process died before it got an answer * there is no error: save a {@link ReconcileContext} before making the call, * and pass that from a background job instead. * * @example * try { * await linePay.confirm({ transactionId, amount, currency }) * } catch (error) { * if (!needsReconcile(error)) throw error * const result = await linePay.reconcile(error) * if (result.status === 'applied' && result.operation === 'confirm') { * markPaid(result.body.info) * } * } */ reconcile(errorOrContext: unknown, options?: CallOptions): Promise; } type LinePayEnv = 'sandbox' | 'production'; interface LinePayConfig { /** The channel ID of the merchant (Merchant Center, "Manage link key"). */ channelId: string; /** The channel secret key. Keep it on the server. */ channelSecretKey: string; /** `sandbox` for testing, `production` for real payments. */ env: LinePayEnv; /** * Time limit of one attempt in milliseconds. It applies to every operation * without a more specific setting. Order of precedence: the `timeout` of the * call, `timeouts[operation]`, `timeout`, the default of the operation. */ timeout?: number; /** Time limits per operation. */ timeouts?: Partial>; /** Replaces the global `fetch`: for a proxy, a fixed IP address, or tests. */ fetch?: typeof fetch; /** * Replaces the host that `env` selects, for example to go through a proxy with a * fixed IP address. It must use https, except for localhost. */ baseUrl?: string; /** * Sent as `X-LINE-MerchantDeviceProfileId`. Give it together with * `merchantDeviceType`: one without the other is refused. */ merchantDeviceProfileId?: string; /** * Sent as `X-LINE-MerchantDeviceType`. Give it together with * `merchantDeviceProfileId`: one without the other is refused. */ merchantDeviceType?: string; /** * Middleware of the client, outermost first. The default is * `[retryWhenNotSent()]`; pass `[]` for none. */ middleware?: readonly Middleware[]; /** * Check the input before sending it, including that amounts add up. `true` by * default. The checks of path parameters (`transactionId`, `regKey`) cannot be * turned off. */ validate?: boolean; } /** * Create a client. It does not connect to anything and keeps no global state, so * creating one per merchant is cheap. * * @example * const linePay = createLinePayClient({ * channelId: process.env.LINE_PAY_CHANNEL_ID ?? '', * channelSecretKey: process.env.LINE_PAY_CHANNEL_SECRET ?? '', * env: 'sandbox' * }) * * @throws {LinePayValidationError} when the configuration is invalid. */ export declare function createLinePayClient(config: LinePayConfig): LinePayClient; type ConfirmQuerySource = string | URL | URLSearchParams | Readonly>; interface ConfirmQuery { /** 1 to 19 digits, as a string. */ transactionId: string; /** Present when LINE Pay appended it. 1 to 100 characters. */ orderId?: string; } /** * Read the parameters LINE Pay appends to the confirmUrl. The `transactionId` * comes from the user's browser, so anyone can put anything there: it has to be a * single string of 1 to 19 digits, and nothing else is let through. * * Find the order in your own database by the `transactionId` that you stored when * you called `request` for it, and take the amount and the currency from that * order, never from the URL. Do not find the order by the `orderId` of the URL and * then confirm the `transactionId` of the URL: the browser can pair any `orderId` * with any `transactionId`, so a cheap order could be paid with the approval of * somebody else's payment. If you do look the order up by `orderId`, check that * `order.transactionId === transactionId` before you go on. * * @example * const { transactionId } = parseConfirmQuery(req.query) * const order = await orders.findByTransactionId(transactionId) // none: answer 404 * * @throws {LinePayValidationError} when a parameter is missing or malformed. */ export declare function parseConfirmQuery(source: ConfirmQuerySource): ConfirmQuery; interface AutoReconcileOptions { /** Operations to reconcile. All five reconcilable operations by default. */ operations?: readonly ReconcilableOperation[]; } /** * When a call ends with an unknown outcome (or LINE Pay answers with a duplicate * code), look the payment up with `client.reconcile`. If it was processed, the * call returns the inferred result, marked in `meta.recovered`. Otherwise the * original error is thrown again, with the conclusion in * `error.reconcileConclusion`. * * It is not on by default: it turns an error into a success, so you opt in. * Place it inside `retryWhenNotSent()`. */ export declare function autoReconcile(options?: AutoReconcileOptions): Middleware; interface RetryOptions { /** Attempts in total, the first one included. Default 3. */ maxAttempts?: number; /** Start of the exponential backoff in milliseconds. Default 200. */ baseDelayMs?: number; /** Upper bound of one wait in milliseconds. Default 2000. */ maxDelayMs?: number; /** Replaces `Math.random`; for tests. */ random?: () => number; /** Replaces the timer; for tests. */ sleep?: (ms: number, signal?: AbortSignal) => Promise; } /** * Repeat a call when that is provably safe, with capped exponential backoff and full * jitter. This is the default middleware of a client. */ export declare function retryWhenNotSent(options?: RetryOptions): Middleware; export type { AddFriend, Address, AnyCallContext, AnyLinePayError, AnyOperationInput, AnyResult, AppliedResult, AutoReconcileOptions, CallContext, CallMeta, CallOptions, CaptureInput, CaptureOptions, CaptureResponse, CheckPaymentStatusInput, CheckPaymentStatusResponse, CheckRegKeyInput, CheckRegKeyResponse, ConfirmInput, ConfirmQuery, ConfirmQuerySource, ConfirmResponse, Currency, DisplayOptions, ExpireRegKeyInput, ExpireRegKeyResponse, ExtraOptions, FamilyServiceOptions, HttpErrorReason, LinePayAbortErrorInit, LinePayApiBody, LinePayApiErrorInit, LinePayClient, LinePayConfig, LinePayEnv, LinePayErrorCode, LinePayErrorInit, LinePayErrorJSON, LinePayErrorOptions, LinePayHttpErrorInit, LinePayMiddlewareErrorInit, LinePayNetworkErrorInit, LinePayResponse, LinePayResult, LinePayTimeoutErrorInit, LinePayValidationErrorInit, Middleware, NetworkErrorReason, OpenString, OperationInput, OperationName, OperationOutput, OperationTypes, Outcome, PayInfo, PayMethod, PayPreapprovedInput, PayPreapprovedResponse, PaymentDetailsInfo, PaymentDetailsInput, PaymentDetailsResponse, PaymentOptions, PaymentProvider, Product, PromotionEvent, Recipient, ReconcilableError, ReconcilableOperation, ReconcileConclusion, ReconcileContext, ReconcileResult, RecoveryInfo, RedirectUrls, RedirectUrlsWithCallbacks, RedirectUrlsWithoutCallbacks, RefundEntry, RefundInput, RefundResponse, RequestPackage, RequestPaymentInput, RequestPaymentOptions, RequestPaymentResponse, ResponsePackage, ResultMeta, ResultOf, RetryOptions, ReturnCodeCategory, SelectedShipping, ShippingOptions, ValidationIssue, VoidInput, VoidResponse };