### Example: normal payment with token binding Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/embedded.md Example of a normal payment with token binding. It sends a payment request with TokenSwitch set to 'get' and TokenTerm, then handles success, 3D, and error responses. ```javascript const response = await client.embeddedCreditCardPayment({ Prime: prime, // from NewebPaySDK.getPrime() at the browser MerchantOrderNo: "Order_123", Amt: 100, ProdDesc: "測試商品", PayerEmail: "customer@example.com", CardHolderName: "Test User", TokenSwitch: "get", // bind a token for later Pn payments TokenTerm: "user@example.com", }); if (isSuccessResponse(response)) { console.log("TradeNo:", response.Result.TradeNo); console.log("TokenValue:", response.Result.TokenValue); // for Pn } else if (is3DResponse(response)) { const html = typeof response === "string" ? response : response.Result; // inject `html` (or client.decode3DHTML(html)) into the page } else { console.error("Payment failed:", response.Status, response.Message); } ``` -------------------------------- ### Basic instantiation example Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/newebpay-client.md Example using CommonJS require to create a NewebpayClient in sandbox mode. ```javascript const NewebpayClient = require("newebpay-mpg-sdk").default; const client = new NewebpayClient({ merchantId: "MS1234567", hashKey: "your-hash-key", hashIV: "your-hash-iv", env: "sandbox", // 'sandbox' | 'production' }); ``` -------------------------------- ### buildCheckCode method and usage example Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/newebpay-client.md Method signature and usage example for verifying the CheckCode returned by the API. The method returns uppercase hex SHA-256 of `HashIV=${this.hashIV}&${paramsStr}&HashKey=${this.hashKey}` where paramsStr is the params object with keys sorted alphabetically then URLSearchParams-encoded. The example compares the computed value to the CheckCode and logs a message if valid. ```typescript public buildCheckCode(params: { [key: string]: any }) ``` ```javascript const clientCheckCode = client.buildCheckCode({ Amt, MerchantID, MerchantOrderNo, TradeNo, }); if (clientCheckCode === CheckCode) { console.log("CheckCode is valid"); } ``` -------------------------------- ### alterPeriodicPaymentAmount usage example Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/periodic-payment.md Example of calling alterPeriodicPaymentAmount to change the amount to 20, with error handling. ```javascript try { const response = await client.alterPeriodicPaymentAmount({ MerOrderNo: "2025010812000000", PeriodNo: "P250108170419c04GYx", AlterAmt: 20, }); console.log(response.Status, response.Result?.NewNextAmt); } catch (error) { console.error("Alter failed:", error); } ``` -------------------------------- ### Instantiation with proxy and partner ID Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/newebpay-client.md Example using ES module import to create a NewebpayClient with proxy options and partner ID. ```javascript import NewebpayClient from "newebpay-mpg-sdk"; const client = new NewebpayClient({ merchantId: "MS1234567", partnerId: "partner-123", hashKey: process.env.NEWEBPAY_HASH_KEY, hashIV: process.env.NEWEBPAY_HASH_IV, env: "production", options: { proxyEndpoint: "https://proxy.mycompany.com", proxySecret: "s3cret", userAgent: "my-app/2.1.0", }, }); ``` -------------------------------- ### Example: 3D transaction with error handling Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/embedded.md Example of a 3D transaction. It sends a payment request with P3D set to '1' and includes NotifyURL and ReturnURL, then handles the 3D response by decoding and rendering the HTML. ```javascript try { const res = await client.embeddedCreditCardPayment({ Prime, MerchantOrderNo: "Order_456", Amt: 1000, ProdDesc: "3D 商品", PayerEmail: "customer@example.com", CardHolderName: "Test User", P3D: "1", NotifyURL: "https://shop.example.com/notify", ReturnURL: "https://shop.example.com/return", }); if (client.is3DResponse(res)) { const html = client.decode3DHTML(res.Result); // URL-encoded HTML -> HTML res.write(html); // render 3D challenge } } catch (error) { console.error(error); } ``` -------------------------------- ### Error handling example with variant by trade number Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/credit-card-refunds.md Example using IndexType 2 to look up by trade number, with try/catch for HTTP errors. ```javascript try { const res = await client.refundCreditCard({ Amt: 1000, IndexType: 2, // lookup by NewebPay trade number TradeNo: tradeNo, CloseType: 1, // claim }); if (res.Status !== "SUCCESS") { console.error("Refund rejected:", res.Message, res.Result); } } catch (error) { console.error("Request failed:", error); } ``` -------------------------------- ### Basic refund example Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/credit-card-refunds.md Example of a basic refund using MerchantOrderNo and optional Cancel flag. ```javascript const { Status, Message, Result } = await client.refundCreditCard({ MerchantOrderNo: "2020072812000000", Amt: 1000, IndexType: 1, TradeNo: "2020072812000000", CloseType: 2, // 2 = refund Cancel: 1, // optional: cancel the refund }); if (Status === "SUCCESS") { console.log("Refunded:", Result.MerchantOrderNo, Result.TradeNo); } ``` -------------------------------- ### refundEWallet basic usage example Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/credit-card-refunds.md Basic implementation of the refundEWallet method to process a refund. ```javascript const { Status, Message, Result } = await client.refundEWallet({ MerchantOrderNo: "2020072812000000", Amount: 1000, PaymentType: "LINEPAY", }); if (Status === "1000") { console.log("Refunded:", Result.RefundAmount, Result.RefundDate); } else { console.error("Refund failed:", Message); } ``` -------------------------------- ### cancelCreditCard usage example Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/credit-card-refunds.md Example of calling cancelCreditCard with IndexType 1 parameters. ```javascript const { Status } = await client.cancelCreditCard({ MerchantOrderNo: "2020072812000000", Amt: 1000, IndexType: 1, TradeNo: "2020072812000000", }); if (Status === "SUCCESS") console.log("Authorization cancelled"); ``` -------------------------------- ### queryTokenStatus Usage (commented out) Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/credit-card.md Example usage of `queryTokenStatus`, currently commented out because the API is not yet usable upstream. ```javascript // ⚠️ Currently unsupported upstream — do not use in production. // const response = await client.queryTokenStatus({ // TokenTerm: "2026-01-16", // TokenValue: "abc123def456", // }); ``` -------------------------------- ### Basic use of parseTradeInfo Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/mpg-payment.md Basic usage example for parseTradeInfo in a NotifyURL handler. The tradeInfo parameter comes from req.body.TradeInfo, and the parsed result is logged. ```javascript // In your NotifyURL handler (e.g. Express) // tradeInfo comes from req.body.TradeInfo (MerchantID and TradeSha are also posted) const trade = client.parseTradeInfo(req.body.TradeInfo); console.log(trade.Status, trade.Message, trade.Result); ``` -------------------------------- ### Usage example for parseCreatePeriodicPaymentResponse Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/periodic-payment.md Example of calling parseCreatePeriodicPaymentResponse with a raw response string. The Result may include TradeNo if the first authorization returned card data. ```javascript const rawResponse = ""; // taken from the response redirect/param (e.g. `Period=...`) const { Status, Message, Result } = client.parseCreatePeriodicPaymentResponse(rawResponse); if (Result?.TradeNo) { console.log("Authorized with trade:", Result.TradeNo); } ``` -------------------------------- ### JavaScript example — partner ID guard for chargeMerchant Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/partner.md Shows how to catch the specific 'Please provide PartnerID' error when partnerId is not set, and prompts constructing the client with partnerId first. ```javascript try { await client.chargeMerchant({ MerchantID: "MS123", Amount: 100, FeeType: "1", BalanceType: "0" }); } catch (error) { if (error.message === "Please provide PartnerID") { console.error("Construct the client with partnerId first"); } } ``` -------------------------------- ### unbindToken Usage (commented out) Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/credit-card.md Example usage of `unbindToken`, currently commented out because the API is not yet usable upstream. ```javascript // ⚠️ Currently unsupported upstream — do not use in production. // const response = await client.unbindToken({ // TokenTerm: "2026-01-16", // TokenValue: "abc123def456", // }); ``` -------------------------------- ### Perform token payment and handle 3D response Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/embedded.md JavaScript example showing how to call embeddedTokenPayment with token parameters, check for success or 3D response, and handle each case. The example uses isSuccessResponse and decode3DHTML. ```javascript const response = await client.embeddedTokenPayment({ TokenValue: tokenValue, // from the P1 response Result.TokenValue TokenTerm: "user@example.com", MerchantOrderNo: "Order_789", Amt: 100, ProdDesc: "續費商品", Inst: "3", }); if (isSuccessResponse(response)) { console.log("Pn TradeNo:", response.Result.TradeNo); } else if (is3DResponse(response)) { const html = client.decode3DHTML(response.Result); // render 3D challenge } else { console.error("Pn failed:", response.Status, response.Message); } ``` -------------------------------- ### Basic getPaymentFormHTML usage Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/mpg-payment.md Basic usage example for getPaymentFormHTML. It creates a payment form for a credit card and ATM transfer, then sends the HTML to the client. ```javascript const html = client.getPaymentFormHTML({ MerchantOrderNo: "2020072812000000", Amt: 1000, ItemDesc: "商品1,商品2", ReturnURL: "https://shop.example.com/return", NotifyURL: "https://shop.example.com/notify", CREDIT: 1, VACC: 1, }); // return this HTML to the client browser res.send(html); ``` -------------------------------- ### Agreement binding with token acquisition Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/credit-card.md Agreement binding (P3D: 1) with TokenSwitch "get" to obtain a token. Includes error handling for HTTP failures. ```javascript try { const res = await client.requestCreditCardPayment({ P3D: 1, NotifyURL: "https://shop.example.com/notify", ReturnURL: "https://shop.example.com/return", MerchantOrderNo: "1234", Amt: 100, ProdDesc: "約定信用卡", PayerEmail: "customer@example.com", CardNo: "4000221111111111", Exp: "2312", CVC: "123", TokenSwitch: "get", TokenTerm: "user@example.com", TokenLife: "2401", }); if (res.Status === "SUCCESS" && typeof res.Result === "object") { console.log("TokenValue:", res.Result.TokenValue, "TokenLife:", res.Result.TokenLife); } } catch (error) { console.error("Request failed:", error); } ``` -------------------------------- ### Basic use of client.authorizeTokenPayment Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/credit-card.md JavaScript example calling authorizeTokenPayment with required fields including TokenValue from the first agreement transaction, TokenTerm, TokenSwitch, CardHolderName, and optional NotifyURL/ReturnURL. Logs TradeNo and TokenUseStatus if Status is SUCCESS and Result exists. ```javascript const response = await client.authorizeTokenPayment({ MerchantOrderNo: "2025011613000000", Amt: 1000, TokenValue: tokenValue, // from the P1 response TokenTerm: "user@example.com", TokenSwitch: "on", ProdDesc: "商品描述", PayerEmail: "customer@example.com", CardHolderName: "Test User", CardHolderPhone: "0912345678", NotifyURL: "https://shop.example.com/notify", ReturnURL: "https://shop.example.com/return", }); if (response.Status === "SUCCESS" && response.Result) { console.log(response.Result.TradeNo, response.Result.TokenUseStatus); } ``` -------------------------------- ### JavaScript example — basic use of chargeMerchant Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/partner.md Calls chargeMerchant with operational fields including FeeType and BalanceType, then logs the scheduled payout on success. ```javascript const { Status, Message, MerchantID, FundTime, MerTrade, ExeNo } = await client.chargeMerchant({ MerchantID: "商店代號", MerTrade: "自訂編號", Amount: 100, FeeType: "1", // commission BalanceType: "0", // positive AppointMerID: "收款商店代號", }); if (Status === "SUCCESS") console.log("Scheduled payout:", FundTime, ExeNo); ``` -------------------------------- ### Credit-card agreement getPaymentFormHTML with error handling Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/mpg-payment.md Example for credit-card agreement (binding P1) foreground payment with error handling. Includes token and mobile verification parameters. ```javascript try { const html = client.getPaymentFormHTML({ MerchantOrderNo: "2025011611000000", Amt: 100, ItemDesc: "約定信用卡", Email: "user@example.com", CREDIT: 1, CREDITAGREEMENT: 1, TokenTerm: "user@example.com", TokenLife: "20260116", UseFor: "0", MobileVerify: 1, MobileNumber: "0912345678", ReturnURL: "https://shop.example.com/return", NotifyURL: "https://shop.example.com/notify", }); res.send(html); } catch (error) { res.status(500).json({ error: String(error) }); } ``` -------------------------------- ### JavaScript example: basic use of createPeriodicPaymentHTML Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/periodic-payment.md Builds a recurring payment HTML form with monthly billing (PeriodType "M"), 99 payments, and returns the HTML. Configures all main fields including return, notify, and back URLs. ```javascript const html = client.createPeriodicPaymentHTML({ LangType: "zh-Tw", MerOrderNo: "2020072812000000", ProdDesc: "約定信用卡", PeriodAmt: 10, PeriodType: "M", PeriodPoint: "01", PeriodStartType: 1, PeriodTimes: 99, PeriodFirstdate: "2020/07/28", PayerEmail: "user@example.com", EmailModify: 0, PaymentInfo: "N", OrderInfo: "N", ReturnURL: "https://shop.example.com/return", NotifyURL: "https://shop.example.com/notify", BackURL: "https://shop.example.com/back", UNIONPAY: 0, }); res.send(html); ``` -------------------------------- ### Decode and render 3D HTML response Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/embedded.md JavaScript example showing how to call embeddedCreditCardPayment, check for a 3D response, decode the Result HTML, and render it with document.write. ```javascript const response = await client.embeddedCreditCardPayment({ P3D: "1", /* ... */ }); if (client.is3DResponse(response)) { const html = client.decode3DHTML(response.Result); document.write(html); } ``` -------------------------------- ### Error handling for parseTradeInfo Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/newebpay-client.md Error handling example for parseTradeInfo. Catches errors thrown when the ciphertext is invalid (crypto module) or when JSON.parse fails (SyntaxError), logging an error message. ```javascript try { const tradeInfo = client.parseTradeInfo(rawTradeInfo); // decrypts + JSON.parse } catch (error) { // Thrown when ciphertext is invalid (crypto module) or JSON.parse fails (SyntaxError) console.error("TradeInfo could not be decrypted/parsed:", error); } ``` -------------------------------- ### Import NewebpayClient Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/README.md Shows how to import the NewebpayClient class using default, named, or CommonJS syntax. ```APIDOC ## Import NewebpayClient ### Description Import the NewebpayClient class from the newebpay-mpg-sdk package. ### Usage ```typescript import NewebpayClient from "newebpay-mpg-sdk"; // default export import { NewebpayClient } from "newebpay-mpg-sdk"; // named export (same class) import { GetPaymentFormHTMLParams, is3DResponse } from "newebpay-mpg-sdk"; // CommonJS const NewebpayClient = require("newebpay-mpg-sdk").default; ``` ``` -------------------------------- ### alterPeriodicPaymentStatus usage example Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/periodic-payment.md Example of calling alterPeriodicPaymentStatus to terminate a periodic payment and logging the next auth time. ```javascript const response = await client.alterPeriodicPaymentStatus({ MerOrderNo: "2020072812000000", PeriodNo: "P250122142116GWoCQJ", AlterType: "terminate", }); if (response.Result) { console.log("Next auth time:", response.Result.NewNextTime); } ``` -------------------------------- ### new NewebpayClient(params) Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/newebpay-client.md Creates a new NewebpayClient instance. Requires merchant credentials and environment, with optional partner ID and client options for proxy and user-agent customization. ```APIDOC ## constructor(params: { partnerId?: string; merchantId: string; hashKey: string; hashIV: string; env: "sandbox" | "production"; options?: NewebpayClientOptions; }) ### Description Constructs a new NewebpayClient instance with the given credentials and environment. The constructor sets up the API and in-frame instances, configures base URLs, and applies proxy and user-agent settings if provided. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `merchantId` | `string` | yes | — | NewebPay merchant ID. | | `hashKey` | `string` | yes | — | NewebPay Hash Key. | | `hashIV` | `string` | yes | — | NewebPay Hash IV. | | `env` | `"sandbox" \| "production"` | yes | — | Selects base URLs: sandbox → `https://ccore.newebpay.com` / `https://c-inframe.newebpay.com`; production → `https://core.newebpay.com` / `https://p-inframe.newebpay.com`. | | `partnerId` | `string` | no | `null` | Only needed for the Partner API methods (`addMerchant`, `modifyMerchant`, `chargeMerchant`). | | `options` | `NewebpayClientOptions` | no | `undefined` | See [configuration.md](../configuration.md). | ### NewebpayClientOptions `NewebpayClientOptions` is a module-local type (not exported from the package root): ```typescript type NewebpayClientOptions = { proxyEndpoint?: string; proxySecret?: string; userAgent?: string; }; ``` ### Behavior - `partnerId` is normalized to `null` when absent. - When both `options.proxyEndpoint` and `options.proxySecret` are set, the axios `baseURL` becomes `proxyEndpoint` and every request carries the headers `x-proxy-type: custom`, `x-proxy-secret: `, `x-proxy-target-endpoint: `. Otherwise `baseURL` is the NewebPay endpoint directly. - When `options.userAgent` is set, the `User-Agent` header is added to the instance. - `apiInstance` is created with default header `Content-Type: multipart/form-data`; `inframeInstance` carries no default headers. ### Example — basic instantiation ```javascript const NewebpayClient = require("newebpay-mpg-sdk").default; const client = new NewebpayClient({ merchantId: "MS1234567", hashKey: "your-hash-key", hashIV: "your-hash-iv", env: "sandbox", // 'sandbox' | 'production' }); ``` ### Example — instantiation with proxy and partner ID ```javascript import NewebpayClient from "newebpay-mpg-sdk"; const client = new NewebpayClient({ merchantId: "MS1234567", partnerId: "partner-123", hashKey: process.env.NEWEBPAY_HASH_KEY, hashIV: process.env.NEWEBPAY_HASH_IV, env: "production", options: { proxyEndpoint: "https://proxy.mycompany.com", proxySecret: "s3cret", userAgent: "my-app/2.1.0", }, }); ``` ``` -------------------------------- ### Usage example for parsePeriodicPaymentResponse with error handling Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/periodic-payment.md Example of calling parsePeriodicPaymentResponse inside a try-catch block. Checks for SUCCESS status and RespondCode '00' to confirm authorization, and logs errors on failure. ```javascript try { const { Status, Result } = client.parsePeriodicPaymentResponse(raw); if (Status === "SUCCESS" && Result.RespondCode === "00") { console.log("Period authorised:", Result.AuthAmt, Result.NextAuthDate); } } catch (error) { console.error("Cannot parse periodic response:", error); } ``` -------------------------------- ### NewebpayClient Constructor Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/newebpay-client.md Creates a new NewebpayClient instance with the provided merchant credentials and environment. The constructor initializes the API endpoints and Axios instances. ```APIDOC ## NewebpayClient Constructor ### Description Creates a new NewebpayClient instance with the provided merchant credentials and environment. The constructor initializes the API endpoints and Axios instances. ### Method Constructor ### Signature ```typescript constructor(params: { partnerId?: string; merchantId: string; hashKey: string; hashIV: string; env: "sandbox" | "production"; options?: NewebpayClientOptions; }); ``` ### Parameters - **partnerId** (string) - Optional - Partner ID for Partner API. - **merchantId** (string) - Required - NewebPay merchant ID. - **hashKey** (string) - Required - NewebPay hash key (AES-256 key and SHA-256 signing seed). - **hashIV** (string) - Required - NewebPay hash IV (AES-256 IV and SHA-256 signing seed). - **env** ("sandbox" | "production") - Required - Selected gateway environment. - **options** (NewebpayClientOptions) - Optional - Additional options including proxyEndpoint, proxySecret, and userAgent. ### Example ```typescript const client = new NewebpayClient({ merchantId: "your-merchant-id", hashKey: "your-hash-key", hashIV: "your-hash-iv", env: "sandbox" }); ``` ``` -------------------------------- ### POST /API/AddMerchant Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/partner.md Creates a new partner store (merchant) using the Partner API. Requires the client to be constructed with a `partnerId`; otherwise it throws an error. ```APIDOC ## [POST] /API/AddMerchant ### Description Creates a new partner store (merchant) using the Partner API. Requires the client to be constructed with a `partnerId`; otherwise it throws an error. ### Method POST ### Endpoint `{apiEndpoint}/API/AddMerchant` ### Parameters #### Request Body (multipart/form-data) - `PartnerID_` (string) - Required - The partner ID from the client configuration. - `PostData_` (string) - Required - Encrypted trade info built from `TimeStamp`, `Version`, and the provided `params`. #### Request Body (params object) - `Version` (string) - Optional - Default `"1.8"`. Can be set to `"2.0"`. - `MerchantID` (string) - Required - Desired store ID. - `MemberName` (string) - Required - Member name. - `MemberPhone` (string) - Required - Member phone. - `MemberAddress` (string) - Required - Member address. - `ManagerName` (string) - Required - Manager name. - `ManagerNameE` (string) - Required - Manager name in English. - `LoginAccount` (string) - Required - Login account. - `ManagerMobile` (string) - Required - Manager mobile. - `ManagerEmail` (string) - Required - Manager email. - `DisputeMail` (string) - Required - Dispute email. - `MerchantEmail` (string) - Required - Merchant email. - `MCType` (string) - Required - Merchant category type. - `MerchantName` (string) - Required - Merchant name. - `MerchantWebURL` (string) - Required - Merchant website URL. - `MerchantAddrCity` (string) - Required - Merchant address city. - `MerchantAddrArea` (string) - Required - Merchant address area. - `MerchantAddrCode` (string) - Required - Merchant address postal code. - `MerchantAddr` (string) - Required - Merchant address. - `MerchantEnAddr` (string) - Required - Merchant address in English. - `MerchantType` (number) - Required - Merchant type (1|2|3|4). - `BusinessType` (string) - Required - Business type. - `MerchantDesc` (string) - Required - Merchant description. - `BankCode` (string) - Required - Bank code. - `SubBankCode` (string) - Required - Sub-bank code. - `BankAccount` (string) - Required - Bank account number. - `MemberUnified` (string) - Required - Unified business number. - `CapitalAmount` (string) - Optional - Capital amount. - `CompanyAddress` (string) - Optional - Company address. ### Request Example ```javascript const { status, message, result } = await client.addMerchant({ MerchantID: "MS1234567", MemberName: "ACME Inc.", MemberPhone: "0222223333", MemberAddress: "Taipei", ManagerName: "Alice", ManagerNameE: "ALICE", LoginAccount: "alice@acme.com", ManagerMobile: "0912345678", ManagerEmail: "alice@acme.com", DisputeMail: "dispute@acme.com", MerchantEmail: "pay@acme.com", MCType: "xxx", MerchantName: "ACME", MerchantWebURL: "https://acme.example.com", MerchantAddrCity: "Taipei", MerchantAddrArea: "TP", MerchantAddrCode: "100", MerchantAddr: "1 Main St", MerchantEnAddr: "1 Main St", MerchantType: 1, BusinessType: "xxx", MerchantDesc: "online store", BankCode: "ESUN", SubBankCode: "007", BankAccount: "1234567890", MemberUnified: "12345678", }); ``` ### Response #### Success Response (200) - `status` (string) - Status of the request (e.g., "SUCCESS"). - `message` (string) - Response message. - `result` (object) - Result object containing merchant data. #### Response Example ```json { "status": "SUCCESS", "message": "", "result": { "MerchantID": "MS1234567" } } ``` ### Error Handling - Throws `Error("Please provide PartnerID")` when the client was constructed without `partnerId`. - Throws an axios error on HTTP failure. ``` -------------------------------- ### POST {apiEndpoint}/API/ChargeInstruct Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/endpoints.md Endpoint to charge a merchant via the partner API. ```APIDOC ## POST {apiEndpoint}/API/ChargeInstruct ### Description Charge a merchant. This endpoint is called by the `chargeMerchant` method in the SDK. ### Method POST ### Endpoint {apiEndpoint}/API/ChargeInstruct ### Parameters #### Request Body (multipart/form-data) - **PartnerID_** (string) - Required - Partner ID. - **PostData_** (string) - Required - AES-encrypted payload containing: - **TimeStamp** (string) - Required - Timestamp. - **Version** (string) - Required - Defaults to "1.1". - **...params** (object) - Required - Additional charge parameters. ### Response #### Success Response - Raw body cast to `ChargeMerchantResult`. #### Response Example ```json { "status": "SUCCESS", "message": "OK", "result": {} } ``` ``` -------------------------------- ### refundEWallet with error handling Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/credit-card-refunds.md Example of using refundEWallet within a try-catch block to handle potential errors. ```javascript try { const res = await client.refundEWallet({ MerchantOrderNo: orderNo, Amount: 3000, PaymentType: "ESUNWALLET", }); if (res.Status !== "1000") { throw new Error(`EWallet refund rejected: ${res.Message}`); } } catch (error) { console.error(error); } ``` -------------------------------- ### JavaScript example calling modifyMerchant Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/partner.md Calls modifyMerchant with a MerchantID and updated fields, then logs the result on success. The MerchantID is required. ```javascript const res = await client.modifyMerchant({ MerchantID: "MS1234567", MerchantName: "ACME (updated)", MerchantWebURL: "https://acme.example.com/v2", }); if (res.status === "SUCCESS") console.log(res.result); ``` -------------------------------- ### Import NewebpayClient and types from newebpay-mpg-sdk Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/README.md Shows the three import styles for the SDK: default import, named import, and CommonJS require. The default and named exports refer to the same class. Use the named import to also access types like GetPaymentFormHTMLParams and is3DResponse. ```typescript import NewebpayClient from "newebpay-mpg-sdk"; // default export import { NewebpayClient } from "newebpay-mpg-sdk"; // named export (same class) import { GetPaymentFormHTMLParams, is3DResponse } from "newebpay-mpg-sdk"; // CommonJS const NewebpayClient = require("newebpay-mpg-sdk").default; ``` -------------------------------- ### requestCreditCardPayment return type Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/credit-card.md Return type of requestCreditCardPayment. When TokenSwitch is "get", a successful result includes TokenValue and TokenLife on TradeInfoResult. ```typescript { Status: "SUCCESS" | string; Message: string; Result: TradeInfoResult | string } ``` -------------------------------- ### TokenPaymentResponseResult type definition Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/types-credit-card.md Defines the detailed transaction result fields for a token payment response. Includes authorization, card, and installment information. This type is module-only and not re-exported. ```typescript export type TokenPaymentResponseResult = { MerchantID: string; Amt: number; TradeNo: string; MerchantOrderNo: string; RespondCode: string; AuthBank: string; Auth: string; AuthDate: string; // YYYYMMDD AuthTime: string; // HHMMSS Card6No: string; Card4No: string; Exp: string; // yymm IP: string; Inst?: number; InstFirst?: number; InstEach?: number; ECI?: string; PaymentMethod?: string; EscrowBank: string; CheckCode: string; }; ``` -------------------------------- ### addMerchant basic usage Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/partner.md Basic usage of addMerchant to create a partner store. Requires a client constructed with partnerId; otherwise it throws Error("Please provide PartnerID"). The response includes status, message, and result; check status === "SUCCESS" to confirm creation. ```javascript const { status, message, result } = await client.addMerchant({ MerchantID: "MS1234567", MemberName: "ACME Inc.", MemberPhone: "0222223333", MemberAddress: "Taipei", ManagerName: "Alice", ManagerNameE: "ALICE", LoginAccount: "alice@acme.com", ManagerMobile: "0912345678", ManagerEmail: "alice@acme.com", DisputeMail: "dispute@acme.com", MerchantEmail: "pay@acme.com", MCType: "xxx", MerchantName: "ACME", MerchantWebURL: "https://acme.example.com", MerchantAddrCity: "Taipei", MerchantAddrArea: "TP", MerchantAddrCode: "100", MerchantAddr: "1 Main St", MerchantEnAddr: "1 Main St", MerchantType: 1, BusinessType: "xxx", MerchantDesc: "online store", BankCode: "ESUN", SubBankCode: "007", BankAccount: "1234567890", MemberUnified: "12345678", }); if (status === "SUCCESS") console.log("Created:", result.MerchantID); ``` -------------------------------- ### buildTradeInfo(params: { [key: string]: any }) Source: https://github.com/depresto/newebpay-mpg-sdk/blob/master/_autodocs/api-reference/newebpay-client.md Builds the TradeInfo payload by URL-encoding the given params (insertion order) and then AES-encrypting the result. Returns the hex-encoded ciphertext expected as the TradeInfo / PostData_ / EncryptData_ payload. ```APIDOC ## buildTradeInfo(params: { [key: string]: any }) ### Description Builds the TradeInfo payload by URL-encoding the given params (insertion order) and then AES-encrypting the result. Returns the hex-encoded ciphertext expected as the TradeInfo / PostData_ / EncryptData_ payload. ### Method `buildTradeInfo(params: { [key: string]: any })` ### Parameters - **params** (object) - Required - Flat object of form fields. ### Returns - **string** - `encryptAESString(new URLSearchParams(params).toString())` — URL-encoded (insertion order, not sorted) then AES-encrypted hex. ```