# List balance transactions Source: https://docs.kyrenpay.com/api-reference/balance/list-balance-transactions /openapi.yaml get /v1/balance/transactions Returns a paginated list of balance transactions showing all changes to your account balance. # Retrieve account balance Source: https://docs.kyrenpay.com/api-reference/balance/retrieve-account-balance /openapi.yaml get /v1/balance Returns the current balance of your merchant account. # Create a checkout session Source: https://docs.kyrenpay.com/api-reference/checkouts/create-a-checkout-session /openapi.yaml post /v1/checkouts Creates a new checkout session for a product. Returns a URL where you can redirect your customer to complete the payment. Checkout sessions expire after 24 hours. Amount and currency come from the active product; per-session price, currency and quantity overrides are not supported. Hosted checkout must be enabled for the merchant. Persist the session against your business order and reuse it on repeated purchase attempts. Creation has no idempotency-key support: reconcile an uncertain creation result before retrying. Configure the merchant Webhook URL and Secret before payment. Use the returned data.url directly; browser success/cancel redirects are not payment confirmation. # Retrieve a checkout session Source: https://docs.kyrenpay.com/api-reference/checkouts/retrieve-a-checkout-session /openapi.yaml get /v1/checkouts/{id} Retrieves a session belonging to the authenticated merchant. OPEN is awaiting payment, COMPLETE indicates completion and exposes the associated successful orderId, and EXPIRED indicates session expiry. orderId is omitted until a successful order is associated. For payment reconciliation, retrieve that order and use the same idempotent fulfillment transaction as Webhooks. Session expiry is not evidence that an existing payment attempt failed. # Get current merchant services agreement Source: https://docs.kyrenpay.com/api-reference/config/get-current-merchant-services-agreement /openapi.yaml get /v1/config/legal/merchant-services-agreement Returns the current rendered agreement, its version, effective date, hashes, and public URL. Retrieve it without an API key. Complete acceptance in the merchant dashboard; downloading this document does not sign it or change the account's agreement status. # Get historical merchant services agreement Source: https://docs.kyrenpay.com/api-reference/config/get-historical-merchant-services-agreement /openapi.yaml get /v1/config/legal/merchant-services-agreement/{version} Returns the agreement for an explicit version and effective date. Reading a historical document does not complete acceptance of the current agreement. # Get legal configuration Source: https://docs.kyrenpay.com/api-reference/config/get-legal-configuration /openapi.yaml get /v1/config/legal Returns the current legal terms version and public document URLs. Reading these documents does not record merchant agreement acceptance. # Get settlement configuration Source: https://docs.kyrenpay.com/api-reference/config/get-settlement-configuration /openapi.yaml get /v1/config/settlement Returns the platform-wide settlement period in business days. Individual orders may use their channel's period captured at creation. Use order `settleDateTime` for the expected eligibility time and `settledAt` for actual settlement. This configuration does not guarantee payout timing. # Get supported currencies Source: https://docs.kyrenpay.com/api-reference/config/get-supported-currencies /openapi.yaml get /v1/config/currencies Returns the list of currencies supported by the platform and the default currency. Use this when creating products or configuring pricing to ensure you use a supported currency. # api.php (order query/refund compatibility endpoint) Source: https://docs.kyrenpay.com/api-reference/epay-compatibility/apiphp-order-queryrefund-compatibility-endpoint /openapi.yaml post /epay/api.php Executes compatibility operations with `act`. - `act=order`: query order status/result. - `act=refund`: submit a refund for an eligible Epay-source order. Paydify 订单仍通过 `act=order` 查询本地权威状态,`type=crypto`,`money` 保持原商品计价金额。 `code=1` 表示请求成功;只有本地 `PAID/SETTLED` 对应 `status=1`,其余为 `0`。 Paydify 经上游验签查询确认后沿用易支付成功通知;浏览器回跳不是付款证据。 本次 Paydify 接入不新增退款能力,不能由通用 `act=refund` 推断该渠道支持退款。 This endpoint also accepts GET with the same parameters. # mapi.php (direct create payment compatibility endpoint) Source: https://docs.kyrenpay.com/api-reference/epay-compatibility/mapiphp-direct-create-payment-compatibility-endpoint /openapi.yaml post /epay/mapi.php Creates (or reuses) an order directly and returns Epay-style response fields. For QR-style channels, response includes `qrcode` and `img`. For redirect-style channels, response includes `payurl`. Paydify:商户一次性加密货币通道绑定 Paydify 时使用 `type=crypto`,沿用 MD5 签名。 返回 `code=1/trade_no/out_trade_no/payurl`,其中 `payurl` 指向 KyrenPay 本地支付页;不返回上游 `qrcode/img`。 买家选择 App / 网络并确认有效 USDT 报价后才创建上游支付;不新增商户必填参数,目前不支持 USDC。 `money/money_type` 表示原商品计价金额,不是应付 USDT 数量;入口 `code=1` 不代表已付款。 同一商户 `out_trade_no` 重试必须保持金额、币种和支付方式一致,不能用重建订单处理未知支付结果。 目标环境须已部署且渠道已开通;文档不替代 Sandbox 真付验收。 Signature algorithm: 1. Remove `sign` and `sign_type`, and drop empty values. 2. Sort parameters by key in ascending order. 3. Join as `k=v` with `&`, append merchant API key. 4. MD5 the final string and compare in lowercase. # submit.php (redirect checkout compatibility endpoint) Source: https://docs.kyrenpay.com/api-reference/epay-compatibility/submitphp-redirect-checkout-compatibility-endpoint /openapi.yaml post /epay/submit.php Creates (or reuses) an Epay-compatible payment and returns HTTP 302 redirect to the hosted payment page. This endpoint also accepts GET with the same parameters. Paydify:商户一次性加密货币通道绑定 Paydify 时使用 `type=crypto`(不是 `paydify`)。 返回 302 到 KyrenPay 本地 `/epay/redirect/{orderId}`,入口受理时不创建上游支付。 买家在本地页选择 App / 网络并确认 USDT 报价后,才创建上游支付和展示二维码。 无需商户提交 App、网络或 Paydify 专用 `channel_param`。目标环境须已部署且渠道已开通。 Signature algorithm: 1. Remove `sign` and `sign_type`, and drop empty values. 2. Sort parameters by key in ascending order. 3. Join as `k=v` with `&`, append merchant API key. 4. MD5 the final string and compare in lowercase. # Export orders as CSV Source: https://docs.kyrenpay.com/api-reference/orders/export-orders-as-csv /openapi.yaml get /v1/orders/export Exports orders within the specified date range as a CSV file. Use Unix timestamps (milliseconds) for startDate and endDate. # List all orders Source: https://docs.kyrenpay.com/api-reference/orders/list-all-orders /openapi.yaml get /v1/orders Returns a paginated list of your orders. An order may exist before payment completes; use its status to decide whether to fulfill. # Retrieve an order Source: https://docs.kyrenpay.com/api-reference/orders/retrieve-an-order /openapi.yaml get /v1/orders/{id} Retrieves merchant-visible order details, including original and payable amounts, fee sharing, refund status, and rolling reserve information. # Archive a product Source: https://docs.kyrenpay.com/api-reference/products/archive-a-product /openapi.yaml delete /v1/products/{id} Archives a product. Archived products cannot be used to create new checkout sessions. # Create a product Source: https://docs.kyrenpay.com/api-reference/products/create-a-product /openapi.yaml post /v1/products Creates a new product. Products represent the goods or services you sell. # List all products Source: https://docs.kyrenpay.com/api-reference/products/list-all-products /openapi.yaml get /v1/products Returns a paginated list of your products. # Retrieve a product Source: https://docs.kyrenpay.com/api-reference/products/retrieve-a-product /openapi.yaml get /v1/products/{id} Retrieves the details of an existing product. # Update a product Source: https://docs.kyrenpay.com/api-reference/products/update-a-product /openapi.yaml patch /v1/products/{id} Updates an existing product. Only the provided fields will be updated. # Create a refund Source: https://docs.kyrenpay.com/api-reference/refunds/create-a-refund /openapi.yaml post /v1/orders/{orderId}/refunds Creates a full or partial refund for an eligible paid order created through the native KyrenPay API. Epay-source orders must be refunded through the Epay compatibility API. # Retrieve a refund Source: https://docs.kyrenpay.com/api-reference/refunds/retrieve-a-refund /openapi.yaml get /v1/refunds/{refundId} Retrieves a refund created for one of your orders. # Payment API authentication Source: https://docs.kyrenpay.com/authentication Authenticate KyrenPay server-side API requests with x-api-key. Find your merchant API key, keep it private, and handle authentication errors. Public merchant integration endpoints, such as `/v1/products`, `/v1/checkouts`, and `/v1/orders`, use an API key passed in the `x-api-key` header. Authentication depends on the endpoint: | Endpoint | Authentication | | - | - | | Public merchant integration API | `x-api-key` | | Public `/v1/config/*` configuration endpoints | No authentication required | | Merchant Dashboard `/v1/merchant/*` endpoints | Dashboard login JWT in `Authorization: Bearer `; an API key does not replace this login | | Epay compatibility API | `pid` plus the endpoint's MD5 `sign`, or `pid` plus the raw `key` for `/epay/api.php` | See [Epay signatures](/epay-migration/signature) for its separate signing rules. ## API Keys KyrenPay uses API keys to authenticate requests. You can manage your API keys from the [Merchant Dashboard](https://merchant.kyrenpay.com). The current backend implementation accepts live API keys: | Key Type | Prefix | Purpose | | - | - | - | | **Live** | `kyren_live_` | Production environment — real payments | ## Making Authenticated Requests Include your API key in the `x-api-key` header when calling a protected public merchant integration endpoint: ```bash theme={null} curl https://api.kyrenpay.com/v1/products \ -H "x-api-key: kyren_live_xxxxxxxxxxxxxxxxxxxx" ``` > [!WARNING] > > **Keep your API keys secure.** > > * Never expose API keys in client-side code (JavaScript, mobile apps) > * Never commit API keys to version control > * Use environment variables to store keys in your server > * Regenerate keys immediately if they are compromised ## Environments | Environment | Base URL | API Key Prefix | | - | - | - | | Production | `https://api.kyrenpay.com` | `kyren_live_` | | Staging | Issued by KyrenPay support | Use only the credentials issued for that staging environment | > [!NOTE] > > The current public production API accepts live API keys with the `kyren_live_` prefix. > KyrenPay does not currently expose self-service `kyren_test_` keys in the merchant dashboard. > Use a staging base URL only when KyrenPay has issued matching staging credentials to you. ## Regenerating API Keys If your API key is compromised, you can regenerate it from the Dashboard: 1. Go to **Dashboard > Developer** 2. Click **Regenerate** next to the key you want to replace 3. Confirm the action > [!WARNING] > > Regenerating a key immediately invalidates the old key. Make sure to update all your integrations with the new key. ## Error Responses Missing or rejected API credentials on a protected endpoint return HTTP `401 Unauthorized`. Authentication middleware does not guarantee a JSON response body. Check the HTTP status before attempting to parse JSON. Application-level JSON error codes are described in [Errors](/errors). Common causes: * Missing `x-api-key` header * Invalid or regenerated API key * Using an API key prefix not accepted by the current environment * A blocked merchant account or a request IP outside your configured API IP allowlist # Checkout links and hosted checkout Source: https://docs.kyrenpay.com/dashboard/checkouts Understand how customers complete payment through KyrenPay checkout KyrenPay checkout lets your customer complete payment on a hosted payment page. ## Before you start Create a product and prepare your success and cancel URLs. If your integration uses the API, your server creates a checkout session and redirects the customer to the returned checkout URL. ## API checkout flow 1. Your server creates a checkout session. 2. KyrenPay returns a hosted checkout URL. 3. Your frontend redirects the customer to that URL. 4. The customer completes payment. 5. KyrenPay sends a Webhook event to your server. 6. Your system fulfills the order after confirming payment success. ## Common mistakes Creation returns a Session inside `data`, with amount and currency taken from the product. Persist its ID, URL, amount, currency and expiry against your business order. Reuse a valid Session on repeated clicks and reconcile uncertain creation outcomes before retrying. Sessions last 24 hours and use `OPEN`, `COMPLETE`, `EXPIRED`. For missed notifications, query `GET /v1/checkouts/{id}` from your server and retrieve its successful associated `orderId`. Verify the order's product, base amount, currency and metadata, then use the same idempotent fulfillment transaction as Webhooks. Browser success/cancel pages are not payment evidence, and Session expiry does not prove an existing payment attempt failed. See the [full example](/guides/collect-first-payment). * Creating checkout sessions from browser JavaScript with an API key. * Fulfilling the order before a paid status or payment-success Webhook. * Not storing your internal user or order ID in metadata when you need reconciliation. ## Related pages * [Quickstart](/quickstart) * [Create a checkout session API reference](/api-reference/checkouts/create-a-checkout-session) * [Webhook overview](/webhooks/overview) # Developer settings Source: https://docs.kyrenpay.com/dashboard/developer-settings Manage API keys, Webhooks, and integration settings Use Developer settings to connect your server to KyrenPay. ## API keys Open **Dashboard > Developer Tools > API Keys** (`/dashboard/developers/api-keys`). If no key exists, click Generate and immediately save its full value. Otherwise use the original you securely saved. Full keys are shown only when generated; a masked value cannot configure your application. Privately put it in the server-side `KYREN_API_KEY` setting or its application-specific equivalent, not in an Agent chat. Use API keys only from your server. Do not expose them in frontend JavaScript, mobile apps, logs, screenshots, or public repositories. If you regenerate an API key, update every server environment that calls KyrenPay. The previous key stops working after regeneration. ## Webhooks Configure a Webhook URL that KyrenPay can reach over HTTPS. Your server should verify the Webhook signature before trusting the event body. Open **Dashboard > Developer Tools > Webhooks** (`/dashboard/developers/webhooks`), enter your application's actual public HTTPS callback URL and save. First configuration generates a separate Webhook Secret. Copy its full value into the private server-side `KYREN_WEBHOOK_SECRET` setting. If no Secret exists, click Generate; otherwise use your securely saved original. It is not the API key, and its masked display cannot verify signatures. Regeneration immediately invalidates the old Secret and requires updating the relevant servers. Do not overwrite another application's callback URL just to set up a new application. Kyren cannot send notifications to localhost. Use your HTTPS deployment or an authorized tunnel's current URL, with the callback path implemented by your application. Configure it before the first payment; later configuration does not automatically backfill ordinary past payment notifications. ## Product ID and application settings For application integration, prefer setup code or an Agent that queries/reuses or, within authorization, creates `ACTIVE` one-time products through the Products API. Persist each local SKU-to-Kyren-product-ID mapping in the database or existing durable catalog, scoped to the environment and merchant. Lists use `data.items` and `data.pagination`; creation returns `data.id`. Repeated initialization reuses mappings. Check price and currency, but do not identify products by price alone; ask the user to resolve ambiguity and do not create a new product per purchase. Manual creation, selection and copying **Product ID** in **Dashboard > Product Management** (`/dashboard/products`) remain available for manual setup. `KYREN_PRODUCT_ID` is an optional shortcut for a simple single-product application, not a general integration prerequisite. A product ID is not a secret, merchant PID, Checkout ID or order ID; users need not obtain it manually as a third credential. These variable names are examples; follow your application's implementation. Reload or restart according to its instructions after updating the actual server configuration. Obtain all values from the selected environment's dashboard; do not mix a development integration with production settings or credentials. See [Quickstart](/quickstart) for the walkthrough. ## IP allowlist If IP allowlist is enabled for your merchant account, make sure every server that calls KyrenPay is included. Missing server IPs can cause authentication or authorization failures. ## Related pages * [Authentication](/authentication) * [Webhook overview](/webhooks/overview) * [Webhook signatures](/webhooks/signatures) * [Testing](/testing) # Disputes Source: https://docs.kyrenpay.com/dashboard/disputes Review dispute cases, deadlines, timelines and their recorded financial impact Use **Disputes** in the merchant dashboard to view cases matched to your own orders. Case availability and financial processing depend on the platform and provider being enabled for your account and environment. An empty list does not establish that no dispute exists at a provider. ## Review a case 1. Open **Disputes**, optionally filter by status, and use pagination to find the case. 2. Check the provider case number, order ID, case type, amount, status and occurrence time. 3. Choose **View details** to open the detail drawer. 4. Review the reason, response deadline, financial impact and case timeline. 5. Contact KyrenPay support promptly when a response is needed, using the case number and order ID. The list and detail drawer are read-only. Evidence submission, appeals, editing a case and executing financial actions are handled with operations support. A **Needs response** status or deadline does not mean a response has been submitted automatically. Only merchant-visible timeline events are shown. ## Case status and funds | Item | What to check | | - | - | | Case status | Whether a response is needed, review is underway, or the case is won, lost, accepted, canceled or closed. | | Provider dispute amount | Amount and currency reported for the case; it can differ from the settlement currency. | | Frozen principal | Principal actually recorded as frozen. | | Allocated rolling reserve | Reserve associated with the case. | | Charged-back principal and offset reserve | Amounts already recorded as deducted or used to offset the chargeback. | | Chargeback fee | Recorded chargeback fee in the displayed settlement currency. | An active dispute can freeze affected funds. An eligible release can return frozen funds; a chargeback deducts affected principal and may use the associated reserve and incur a chargeback fee. These operations depend on enabled financial processing and the recorded outcome. A terminal case status alone does not confirm that a funds operation completed, or that previously charged-back funds were restored. When an order has multiple related cases, the drawer indicates the shared order financial context. Do not add shared figures across cases as if each were a separate balance. Reconcile actual amounts against [Funds](/dashboard/funds), transaction records and [Orders](/dashboard/orders). ## Notifications and support Where dispute notifications are enabled, `dispute.created` and `dispute.updated` can notify your endpoint of case changes. See [Webhook events](/webhooks/events). Use the case identifier to correlate notifications and recheck the latest case and financial records; a case notification does not by itself establish a successful balance operation. For missing cases, approaching deadlines, or funds that differ from the case status, provide support with your merchant ID, provider case number, order ID, amount, currency, deadline and relevant timestamps. Do not include API keys or Webhook secrets. ## Related pages * [Orders](/dashboard/orders) * [Funds](/dashboard/funds) * [Order refunds](/dashboard/order-refunds) * [Webhook events](/webhooks/events) # Funds Source: https://docs.kyrenpay.com/dashboard/funds Review balances, transactions, settlements, and settlement accounts Use Funds to review balances, transaction records, settlements, and settlement accounts for your KyrenPay account. ## What you can manage | Area | Use it for | | - | - | | Balance | Check available and pending funds. | | Transactions | Review payment, refund, fee, and adjustment records. | | Settlements | Track settlement status and settlement-related records. | | Settlement accounts | Add, review, or update the account used to receive settlements. | ## Currencies KyrenPay supports acquiring in `CNY`, `HKD`, and `USD`. Merchant settlement currency is `USD`. If an order is paid in `CNY` or `HKD`, review the order detail and transaction records for the conversion information used for USD settlement. ## Acquiring Fees Percentage fee rates apply to the order amount. Per-transaction fixed fees and chargeback fixed fees are configured in `USD`; they do not follow the order currency. Configure customer and merchant fee contributions in [Payment methods](/dashboard/payment-methods). The amount the customer pays can exceed the original order amount; merchant proceeds also reflect merchant fees and applicable reserves. Use the order's fee snapshot and settlement records for reconciliation. ## Dispute funds Where dispute financial processing is enabled, cases can freeze affected funds, release eligible frozen funds or deduct principal and chargeback fees. [Disputes](/dashboard/disputes) shows the recorded frozen principal, reserve allocation, deducted principal, reserve offset and chargeback fee. Compare these with transaction records and available funds. A won or closed case alone does not confirm that a release completed or that charged-back funds were restored. ## Before managing settlement accounts 1. Make sure required KYC or KYB verification is complete. 2. Confirm account holder information matches your merchant profile or business documents. 3. Review recent orders and transactions for reconciliation. 4. Keep settlement account information accurate before settlement processing. If a [merchant agreement](/dashboard/merchant-agreement) grace period expires, the agreement gate still permits balances, settlements and settlement accounts. Their normal balance, account and verification requirements continue to apply. ## Related pages * [Orders](/dashboard/orders) * [Payment methods](/dashboard/payment-methods) * [Disputes](/dashboard/disputes) * [Merchant agreement](/dashboard/merchant-agreement) * [KYC](/dashboard/kyc) * [KYB](/dashboard/kyb) # KYB Source: https://docs.kyrenpay.com/dashboard/kyb Submit and review business verification information Use KYB to submit business verification information for your merchant account. ## What to prepare * Registered business name and registration details. * Business website, product description, and operating region. * Business registration documents when required. * Beneficial owner or authorized representative information when requested. ## Review tips Submitting business verification opens the [Merchant Services Agreement](/dashboard/merchant-agreement) dialog. Confirm the business legal name and authorized signer, read the current agreement, then accept and submit verification. The same party's valid current acceptance can be reused. An accepted agreement does not approve KYB; monitor the separate review result. * Keep business names consistent across documents, website, and account profile. * Make sure your website clearly describes what customers buy. * Respond to review follow-up requests with complete information. ## Related pages * [KYC](/dashboard/kyc) * [Merchant agreement](/dashboard/merchant-agreement) * [Funds](/dashboard/funds) * [Personal settings](/dashboard/personal-settings) # KYC Source: https://docs.kyrenpay.com/dashboard/kyc Submit and review personal verification information Use KYC to submit personal identity verification information when KyrenPay requires it for account review or settlement access. ## What to prepare * Legal name that matches your identity document. * Identity document details and required images. * Contact information that KyrenPay can use for follow-up. * Any additional information requested during review. ## Review status Before submitting, review and accept the [Merchant Services Agreement](/dashboard/merchant-agreement) in the confirmation dialog. Check the displayed signing party and authorized signer; personal verification can use an existing business party. A valid acceptance for the same party and current version can be reused. Signing and verification approval are separate steps. | Status | Meaning | | - | - | | Not submitted | You have not submitted KYC information yet. | | Pending | KyrenPay is reviewing your submission. | | Approved | Your personal verification has been approved. | | Rejected | Review failed or more accurate information is needed. | ## Related pages * [Funds](/dashboard/funds) * [Merchant agreement](/dashboard/merchant-agreement) * [KYB](/dashboard/kyb) * [Go-live checklist](/go-live-checklist) # Merchant agreement Source: https://docs.kyrenpay.com/dashboard/merchant-agreement Accept the merchant services agreement during verification or a signing reminder The Merchant Services Agreement is accepted during KYC or KYB submission. Existing merchants may also receive a signing reminder in the dashboard. Reading the public agreement or loading the latest text does not record acceptance. ## Sign during verification 1. Complete the required information on [KYC](/dashboard/kyc) or [KYB](/dashboard/kyb) and submit it. 2. Review the agreement dialog, including the signing party, legal name, authorized signer and registered email. A personal KYC submission can use the business party already associated with the account; check the party actually displayed. 3. Read the agreement version and effective date. Confirm that the displayed signer is operating personally and has authority to accept for the merchant. 4. Select the acceptance checkbox at the bottom, then choose **Agree and submit verification**. 5. Check the verification submission result and review status. If a valid acceptance for the current version and same party is available, the dialog displays that record and can reuse it. If the legal party or document changes, read and confirm the updated agreement. Use **Return to edit information** if the displayed details are incorrect. Acceptance is associated with the displayed version, document and signing party. KyrenPay retains the acceptance evidence and generates a signed PDF in the backend. Contact support for assistance with a signing record; this workflow does not provide a dashboard PDF download button. Signing does not approve KYC or KYB. Verification remains subject to a separate review. ## Signing reminders and grace periods When a reminder appears, choose **Sign now**, review the current agreement, select the acceptance checkbox and submit. Check that the reminder clears after acceptance. If the content has changed, the dialog reloads it and asks you to read and confirm again. Any grace deadline is shown in Hong Kong time. Where enforcement applies, an unsigned merchant past that deadline cannot create new Checkout or EPay payments, generate or regenerate an API key, or enable a bound payment method. Existing orders and refund handling, dispute viewing, balances, settlement requests and settlement accounts remain accessible, subject to their own account and verification requirements. An unsigned agreement may also block approval of a pending verification when that requirement applies. Signing preserves the existing verification materials and submission status; it allows review to continue. If the agreement or signing party cannot load, use the reload action. If acceptance fails, the party is incorrect, or the reminder remains after a successful submission, contact KyrenPay support with your merchant ID, displayed version, time and error message. ## Related pages * [KYC](/dashboard/kyc) * [KYB](/dashboard/kyb) * [Payment methods](/dashboard/payment-methods) * [Funds](/dashboard/funds) # Order refunds Source: https://docs.kyrenpay.com/dashboard/order-refunds Request refunds from the order detail page and track review, execution, and Webhook updates Use order refunds when a customer needs a full or partial refund for a paid KyrenPay order. Refunds start as a merchant refund request and are reviewed before KyrenPay attempts the refund. ## When you can request a refund You can request a refund from the order detail page when all of these are true: * Your merchant account has refund access enabled. * The order status is `PAID` or `SETTLED`. * The order is not an onboarding fee order. * The refund amount is greater than `0` and does not exceed the remaining refundable amount. * The order does not already have an active refund request in `PENDING` or `REVIEWING`. If the **Request refund** button is not visible, check the order status and whether refund access is enabled for your account. ## Request a refund 1. Open **Dashboard > Orders**. 2. Select the order you want to refund. 3. Click **Request refund**. 4. Enter the refund amount and reason. 5. Submit the request. After submission, the request appears in the refund request table on the order detail page. ## Refund request statuses | Status | Meaning | | - | - | | `PENDING` | The request has been submitted and is waiting for review. | | `REVIEWING` | KyrenPay is reviewing the request or attempting to execute the refund. | | `APPROVED` | The request was approved and linked to a refund record. | | `REJECTED` | The request was rejected. Review the admin note when available. | ## Refund record statuses | Status | Meaning | | - | - | | `CREATED` | The refund record has been created. | | `SUBMITTING` | KyrenPay is submitting the refund to the payment provider. | | `PROCESSING` | The payment provider is processing the refund. | | `SUCCEEDED` | The refund succeeded. | | `FAILED` | The refund failed. Check the error message or contact support. | | `UNKNOWN` | The final provider status is not confirmed yet. | ## Balance and reconciliation When a refund succeeds, KyrenPay records a refund deduction in your funds and updates the order refund status. Review the order detail page, transaction records, and your own fulfillment system together. If your system fulfills automatically, handle refund updates idempotently and reverse or adjust the customer entitlement according to your own product policy. ## Webhook notification When a refund is applied to an order, KyrenPay sends the `order.refunded` Webhook event. Use this event to update entitlement, balance, or reconciliation records in your system. ## Epay compatibility Use `/epay/api.php?act=refund` only for orders created through Epay compatibility endpoints and only when your merchant account has refund access enabled. Native KyrenPay API orders should use the native refund API, while manual operational refunds can still be handled from the dashboard. ## Related pages * [Orders](/dashboard/orders) * [Funds](/dashboard/funds) * [Webhook events](/webhooks/events) * [api.php order query and refund compatibility](/epay-migration/api-php) # Orders Source: https://docs.kyrenpay.com/dashboard/orders Review KyrenPay orders and reconcile payment status Use Orders to review payment status, find order identifiers, and reconcile KyrenPay records with your own system. ## What to check | Field | How to use it | | - | - | | Order number | Share this with KyrenPay support when asking about a payment. | | Status | Decide whether your system should fulfill or wait. | | Amount and currency | Compare with the product or checkout session amount. | | Created and paid times | Compare with your server logs. Times in the API use millisecond timestamps. | | Payment channel | Identify the payment method used by the customer. | ## Reconciliation workflow 1. Search for the order in the dashboard. 2. Compare status, amount, currency, and timestamps with your internal record. 3. Check whether your Webhook endpoint received the corresponding event. 4. Use the Orders API when your system needs automated reconciliation. ## Refunds For paid or settled orders, merchants with refund access can submit a refund request from the order detail page. Review the request status, refund record status, and `order.refunded` Webhook event when reconciling refunded orders. ## Amounts and fee sharing The order amount is the original product amount; the payable amount includes the customer's fee contribution. Review the merchant and customer fee rates, fixed fees and USD fee amounts separately. Per-transaction fixed fees are configured in USD. A change in [Payment methods](/dashboard/payment-methods) does not rewrite existing order fee snapshots. The payable amount is not the merchant's net proceeds. Compare the fee breakdown, reserve, exchange rate and actual USD settlement amount with [Funds](/dashboard/funds). Closed and failed orders hide fee details; a blank fee or settlement value does not confirm that money was received. ## Disputed orders An order can show `DISPUTED` or `CHARGEBACK` when it has dispute exposure or recorded chargeback impact. Open [Disputes](/dashboard/disputes) to check related cases, deadlines and actual frozen or deducted amounts. Case status and completed financial operations can differ; reconcile the recorded funds rather than inferring a release from the case status alone. ## Related pages * [List all orders API reference](/api-reference/orders/list-all-orders) * [Retrieve an order API reference](/api-reference/orders/retrieve-an-order) * [Order refunds](/dashboard/order-refunds) * [Payment methods](/dashboard/payment-methods) * [Disputes](/dashboard/disputes) * [Webhook events](/webhooks/events) # Dashboard overview Source: https://docs.kyrenpay.com/dashboard/overview Find the main merchant dashboard areas in KyrenPay Use the merchant dashboard to manage products, orders, funds, KYC, KYB, developer settings, and personal settings. ## Main areas | Area | Use it for | | - | - | | Products | Create and manage what you sell. | | Orders | Review payments, order status, and reconciliation details. | | Funds | Review balances, transactions, settlements, and settlement accounts. | | KYC | Submit and review personal verification information. | | KYB | Submit and review business verification information. | | Developer | Manage API keys, Webhook settings, and integration configuration. | | Personal settings | Manage profile details, account security, password, and 2FA. | ## Recommended first setup 1. Review merchant profile and website information. 2. Create a product. 3. Create a checkout session from the API or generate a checkout flow. 4. Configure Webhooks in Developer settings. 5. Review paid orders in Orders. ## Related pages * [Products](/dashboard/products) * [Checkout links](/dashboard/checkouts) * [Orders](/dashboard/orders) * [Funds](/dashboard/funds) * [KYC](/dashboard/kyc) * [KYB](/dashboard/kyb) * [Developer settings](/dashboard/developer-settings) * [Personal settings](/dashboard/personal-settings) # Payment methods Source: https://docs.kyrenpay.com/dashboard/payment-methods Enable bound payment methods and configure customer fee sharing Open **Payment methods** in the merchant dashboard to review the methods already bound to your account, their status, and how order fees are shared. Contact KyrenPay support to request a method that is missing from the list. ## Enable or disable a method 1. Find the payment method and check its current status. 2. Use the switch in the action column to enable or disable it. 3. Wait for the success message, then check the method in a new Checkout. An enabled binding is still subject to platform availability, channel configuration, currency and account restrictions. Enabling can fail if the channel is unavailable or an applicable [merchant agreement](/dashboard/merchant-agreement) signing requirement is overdue. Disabling a method does not cancel paid orders or reverse their funds. ## Configure fee sharing Choose **Set fee sharing** for a method. The dialog shows the total percentage fee and fixed fee, then lets you enter: | Setting | Meaning | | - | - | | Customer fee rate | Customer share of the percentage fee used to calculate the Checkout surcharge. The dashboard accepts a percentage; `customerFeeRate` stores a decimal rate, such as `0.01` for 1%. | | Customer fixed fee | Customer contribution per transaction, configured in USD as `customerPerTransactionFee`. | | Merchant contribution | Calculated as the total fee minus the customer contribution, separately for the rate and fixed fee. | | Checkout display text | Optional description shown at Checkout, up to 80 characters. | Both customer contributions must be nonnegative and no greater than their respective total fee. Set both to zero to have the merchant bear the full fee. Choose **Save** and check a new Checkout before directing customers to it. The original order amount is the product price. The payable amount adds the customer fee contribution; the merchant's net proceeds reflect the merchant contribution and any applicable reserve. Fixed fees are configured in **USD**, even when the order uses another currency. Use the payable amount, fee breakdown, conversion and settlement amounts in [Orders](/dashboard/orders) for reconciliation. A settings change does not rewrite fee snapshots on existing orders. Checkout adjusts the customer surcharge to account for processing fees on that surcharge: `(original amount × customer rate + customer fixed fee converted to order currency) ÷ (1 − total order fee rate)`, rounded to two decimal places. For a USD 100.00 order, a total rate of 3%, and a customer share of 1% plus USD 0.20, the surcharge is USD 1.24 and the payable amount is USD 101.24. Always use the Checkout quote and recorded order amounts for the actual charge. ## Multiple channel bindings A payment method name is not a unique channel identity. Several providers or integration routes can be bound to the same method. Channel identity includes the provider, provider method code, integration mode and business mode. The current dashboard identifies actions by payment method and does not offer a complete route selector. If duplicate methods appear or saving reports that channel identity is required, contact KyrenPay support to identify the intended binding. Include the method, intended provider and error message. Do not assume one switch updates every route. ## Related pages * [Orders](/dashboard/orders) * [Funds](/dashboard/funds) * [Merchant agreement](/dashboard/merchant-agreement) * [Checkout sessions](/dashboard/checkouts) # Personal settings Source: https://docs.kyrenpay.com/dashboard/personal-settings Manage profile details, account security, password, and 2FA Use Personal settings to manage your own dashboard account and security settings. ## Common tasks | Task | Notes | | - | - | | Profile details | Keep your contact information current. | | Password | Use a strong password and update it when team access changes. | | Two-factor authentication | Enable 2FA to protect sensitive actions. | | Account security | Review settings before regenerating API keys or changing settlement account information. | ## Set up 2FA Use two-factor authentication (2FA) to add a one-time verification code requirement to your dashboard account. 1. Sign in to the KyrenPay merchant dashboard. 2. Open **Personal settings** from the dashboard navigation. 3. Find **Two-factor authentication** and choose **Enable 2FA**. 4. Scan the QR code with an authenticator app such as Google Authenticator, Microsoft Authenticator, or 1Password. 5. Enter the 6-digit code from the authenticator app to confirm setup. 6. Save any recovery codes shown on the page in a secure place. After 2FA is enabled, keep your authenticator app available when signing in or performing sensitive account actions. If you lose access to the authenticator app or recovery codes, contact KyrenPay support from a verified account channel. ## Security reminders * Do not share your password or 2FA codes. * Do not send API keys, Webhook secrets, or identity documents through chat or email unless KyrenPay explicitly requests a secure channel. * Remove access for team members who no longer need the dashboard. ## Related pages * [Developer settings](/dashboard/developer-settings) * [KYC](/dashboard/kyc) * [KYB](/dashboard/kyb) # Products Source: https://docs.kyrenpay.com/dashboard/products Create and manage products in the KyrenPay dashboard Products represent what your customers pay for, such as AI credits, prepaid packages, or one-time digital services. ## Before you start Decide the product name, description, amount, and currency. KyrenPay API examples use amount strings such as `"9.99"` to avoid floating-point precision issues. ## Steps 1. Open the merchant dashboard. 2. Go to Products. 3. Create a new product. 4. Enter the product name, description, amount, and currency. 5. Save the product. 6. Use the product when creating checkout sessions. ## Common mistakes * Using a vague product name that customers cannot recognize on checkout. * Sending amount values from your own system as floating-point numbers instead of decimal strings. * Archiving a product that is still used by your checkout integration. ## Related pages * [Create a product API reference](/api-reference/products/create-a-product) * [Collect your first payment](/guides/collect-first-payment) # api.php order query and refund compatibility Source: https://docs.kyrenpay.com/epay-migration/api-php Use Epay-compatible api.php order query and understand refund compatibility behavior. `/epay/api.php` provides Epay-compatible operational actions. Use `act=order` to query migrated Epay-style orders. Use `act=refund` to submit refunds for eligible Epay-source orders. ## Order query Call `GET` or `POST` `/epay/api.php?act=order` with `pid`, raw merchant `key`, and one of `out_trade_no` or `trade_no`. This endpoint uses the raw merchant `key` with `pid` for compatibility order query. It may be subject to the API IP allowlist when enabled. ```bash theme={null} curl "https://api.kyrenpay.com/epay/api.php?act=order&pid=10001&key=merchant_secret&out_trade_no=ORDER_10002" ``` Example success response: ```json theme={null} { "code": 1, "msg": "查询订单号成功!", "trade_no": "K202605260001", "out_trade_no": "ORDER_10002", "type": "alipay", "pid": "10001", "addtime": "2026-05-26 10:30:00", "endtime": "2026-05-26 10:31:12", "name": "AI credits", "money": "9.99", "status": 1, "param": "account_123", "buyer": "" } ``` `addtime` and `endtime` are Epay-compatible datetime strings when exposed by this compatibility query. Example failure response: ```json theme={null} { "code": 0, "msg": "order not found" } ``` ## Refund compatibility Call `GET` or `POST` `/epay/api.php?act=refund` with `pid`, raw merchant `key`, `money`, and one of `out_trade_no` or `trade_no`. Refunds through this path are only for orders created by Epay compatibility endpoints. Native KyrenPay API orders should use the native refund API. The merchant account must have refund access enabled, and the order must still have enough refundable amount. Optional `refund_no` is used for idempotency. If omitted, KyrenPay uses the order ID and normalized refund amount as the compatibility idempotency key. ```bash theme={null} curl "https://api.kyrenpay.com/epay/api.php?act=refund&pid=10001&key=merchant_secret&trade_no=K202605260001&money=9.99&refund_no=REFUND_10002" ``` Example response: ```json theme={null} { "code": 1, "msg": "退款提交成功", "trade_no": "K202605260001", "out_trade_no": "ORDER_10002", "refund_no": "REFUND_10002", "refund_id": "refund_abc123", "money": "9.99", "status": "PROCESSING" } ``` See the [`api.php` API reference](/api-reference/epay-compatibility/apiphp-order-queryrefund-compatibility-endpoint). # mapi.php direct payment creation Source: https://docs.kyrenpay.com/epay-migration/mapi-php Use the Epay-compatible mapi.php endpoint for server-to-server payment creation. `/epay/mapi.php` is the server-to-server Epay compatibility endpoint. It accepts form `POST`, creates or reuses a KyrenPay order, and returns Epay-style response fields such as `payurl`, `qrcode`, `img`, and `trade_no` depending on the selected channel. This endpoint uses `pid + sign`, not `x-api-key`. Because it is server-to-server, it may be subject to the API IP allowlist when enabled. A failed allowlist check can return numeric `code` `0` with `msg`. ## Parameters Required parameters: | Parameter | Description | | - | - | | `pid` | KyrenPay-issued merchant Epay-compatible merchant ID. | | `type` | Payment type. Supported values include `alipay`, `wxpay`, `creditcard`, `crypto`, `paynow`, and `duitnow` (DuitNow). | | `out_trade_no` | Your merchant order number. | | `notify_url` | Merchant payment result notification URL. | | `name` | Order or product name. | | `money` | Decimal string amount, for example `"9.99"`. | | `clientip` | End-user client IP collected by your server. | | `sign` | Epay-compatible MD5 signature. | | `sign_type` | Signature type, usually `MD5`. | Optional parameters: | Parameter | Description | | - | - | | `return_url` | Browser return URL when the channel uses a payment page. | | `money_type` | Currency or money type if provided by your existing integration. | | `device` | Optional device hint: `pc` or `mobile`. Reusing the same order number with a different Alipay/WeChat device flow can be rejected. | | `display_merchant_name` | Per-payment merchant display name shown on KyrenPay intermediate payment pages. | | `param` | Passthrough merchant metadata returned in notifications. | | `userId` | Optional merchant user identifier passed to the payment gateway when supported. | | `channel_param` | Optional channel-extension JSON string for non-credit-card payment types. When `type=creditcard`, its original value is included in the Epay signature but KyrenPay completely ignores it after signature verification. Do not send card number, expiry date, CVV, billing details, or contact information in `channel_param`; the buyer enters card details on a KyrenPay or upstream hosted page. Top-level `email`, `phone`, and `userId` parameters are unaffected. | ## Example request ```bash theme={null} curl -X POST https://api.kyrenpay.com/epay/mapi.php \ -H "Content-Type: application/x-www-form-urlencoded" \ --data-urlencode "pid=10001" \ --data-urlencode "type=alipay" \ --data-urlencode "out_trade_no=ORDER_10002" \ --data-urlencode "notify_url=https://merchant.example.com/notify" \ --data-urlencode "name=AI credits" \ --data-urlencode "money=9.99" \ --data-urlencode "display_merchant_name=Campaign Store" \ --data-urlencode "clientip=203.0.113.10" \ --data-urlencode "sign=lowercase_md5_signature" \ --data-urlencode "sign_type=MD5" ``` ## Success response example ```json theme={null} { "code": 1, "trade_no": "K202605260001", "out_trade_no": "ORDER_10002", "payurl": "https://payment.kyren.io/epay/redirect/order_abc123" } ``` ## Failure response example ```json theme={null} { "code": 0, "msg": "IP not allowed" } ``` See [Epay MD5 signature](/epay-migration/signature) and the [`mapi.php` API reference](/api-reference/epay-compatibility/mapiphp-direct-create-payment-compatibility-endpoint). DuitNow uses `type=duitnow`. Availability requires an approved Waffo capability and an explicit merchant binding. The current Sandbox capability accepts USD; upstream country `MYS` is displayed as Malaysia (`MY`). # Epay migration checklist Source: https://docs.kyrenpay.com/epay-migration/migration-checklist Checklist for moving an Epay-style integration to KyrenPay compatibility endpoints. Use this checklist when replacing an existing Epay-style integration with KyrenPay compatibility endpoints. ## Checklist * Replace the old Epay base URL with the KyrenPay API base URL and keep the compatible paths you use. * Set the KyrenPay-issued `pid` and merchant key for the merchant account. * Verify the [Epay MD5 signature](/epay-migration/signature) implementation before sending live traffic. * Map payment type values to supported values such as `alipay`, `wxpay`, `creditcard`, `crypto`, and `paynow`. * Confirm `notify_url` is reachable and can verify the Epay-compatible notification signature. * Confirm `return_url` behavior for browser redirect checkout. * Return the plain string `success` after processing each payment result notification. * Verify [`submit.php`](/epay-migration/submit-php) browser checkout or [`mapi.php`](/epay-migration/mapi-php) direct payment creation, depending on your integration path. * Verify [`api.php?act=order`](/epay-migration/api-php) queries by `out_trade_no` or `trade_no`. * If you need automated refunds for Epay-source orders, verify `api.php?act=refund` with an eligible paid order, refund access enabled, and an idempotent `refund_no`. * Reconcile migrated Epay source orders in KyrenPay orders and settlements. For testing, use KyrenPay-issued credentials. Low-risk live checks should only be performed when approved by KyrenPay or support. # Epay migration and compatibility API Source: https://docs.kyrenpay.com/epay-migration/overview Migrate an existing Epay integration to KyrenPay. Compare submit.php, mapi.php, api.php, MD5 signatures, and asynchronous payment notifications. Use Epay compatibility when you already have an Epay-style integration and need to keep the same request shape while moving payment traffic to KyrenPay. New integrations should prefer native KyrenPay Checkout through the [Quickstart](/quickstart), because native Checkout uses KyrenPay API authentication and the current order model directly. Epay source orders created through these compatibility endpoints flow into the same KyrenPay order and settlement system as native Checkout orders. The compatibility layer is only the entry point and response format. ## Endpoint map | Existing Epay path | Method | Purpose | KyrenPay behavior | | - | - | - | - | | `/epay/submit.php` | `GET` or `POST` | Page redirect checkout | Creates or reuses an order, then returns HTTP `302` to `/epay/redirect/{orderId}` or an upstream payment page. | | `/epay/mapi.php` | `POST` | Server-to-server direct payment creation | Creates or reuses an order and returns Epay-style fields such as `payurl`, `qrcode`, `img`, and `trade_no` depending on channel. | | `/epay/api.php?act=order` | `GET` or `POST` | Order query | Queries by `out_trade_no` or `trade_no`. | | `/epay/api.php?act=refund` | `GET` or `POST` | Refund compatibility path | Submits refunds for eligible Epay-source orders when refund access is enabled. | ## Migration flow 1. Replace your Epay base URL with the KyrenPay API base URL while keeping the compatible path. 2. Use your KyrenPay-issued `pid` and merchant key for Epay-compatible signing. 3. Keep `pid + sign` authentication for Epay-compatible requests. Do not send `x-api-key`. 4. Map your payment `type` values to supported values such as `alipay`, `wxpay`, `creditcard`, `crypto`, or `paynow`. 5. Route browser checkout traffic to [`submit.php`](/epay-migration/submit-php) or server-side payment creation to [`mapi.php`](/epay-migration/mapi-php). 6. Verify payment results from the `notify_url` GET notification and return the plain string `success` after processing. 7. Use [`api.php?act=order`](/epay-migration/api-php) for compatibility order queries, and [`api.php?act=refund`](/epay-migration/api-php) only for Epay-source order refunds. ## Related pages * [Epay MD5 signature](/epay-migration/signature) * [submit.php redirect checkout](/epay-migration/submit-php) * [mapi.php direct payment creation](/epay-migration/mapi-php) * [api.php order query and refund compatibility](/epay-migration/api-php) * [Epay migration checklist](/epay-migration/migration-checklist) # Epay MD5 sign generation and verification Source: https://docs.kyrenpay.com/epay-migration/signature Generate the Epay sign parameter and verify payment notifications with MD5. Follow KyrenPay field sorting, empty-value, and merchant-key rules. Epay-compatible requests use `pid + sign` instead of `x-api-key`. Build `sign` as the lowercase MD5 of `k=v&...` plus the merchant key. ## Algorithm 1. Remove `sign` and `sign_type`. 2. Drop parameters with empty values. 3. Sort the remaining parameters by ascending key in ASCII key order. 4. Join each pair as `k=v`, separated with `&`. 5. Append the merchant key directly to the joined string. 6. Compute MD5 and output lowercase hexadecimal. Do not add an extra `&key=` segment. Append the merchant key directly after the joined parameter string. ## Example Input parameters: ```json theme={null} { "pid": "10001", "type": "alipay", "out_trade_no": "ORDER_10001", "notify_url": "https://merchant.example.com/notify", "return_url": "https://merchant.example.com/return", "name": "AI credits", "money": "9.99", "param": "account_123", "sign_type": "MD5" } ``` After removing `sign_type`, dropping empty values, and sorting by key: ```text theme={null} money=9.99&name=AI credits¬ify_url=https://merchant.example.com/notify&out_trade_no=ORDER_10001¶m=account_123&pid=10001&return_url=https://merchant.example.com/return&type=alipay ``` If the merchant key is `merchant_secret`, sign this exact string: ```text theme={null} money=9.99&name=AI credits¬ify_url=https://merchant.example.com/notify&out_trade_no=ORDER_10001¶m=account_123&pid=10001&return_url=https://merchant.example.com/return&type=alipaymerchant_secret ``` The resulting `sign` is the lowercase MD5 hexadecimal digest of that signing string. ## Verification checklist * Use the KyrenPay-issued `pid` and merchant key for the merchant account receiving the order. * Exclude both `sign` and `sign_type` before signing. * Drop empty values before sorting. * Sort by raw parameter key, not by display label or JSON order. * Keep decimal values as strings, for example `"9.99"`. * Send `sign_type` as `MD5` when the endpoint requires it, but do not include it in the signing string. ## Common mistakes * Adding `&key=` before the merchant key. * Including `sign_type` in the signing string. * Keeping blank optional parameters in the signing string. * Signing a rounded or numeric money value instead of the original decimal string. * Sending `x-api-key` to an Epay-compatible endpoint. See the [`submit.php` API reference](/api-reference/epay-compatibility/submitphp-redirect-checkout-compatibility-endpoint) for the redirect checkout endpoint schema. # submit.php redirect checkout Source: https://docs.kyrenpay.com/epay-migration/submit-php Use the Epay-compatible submit.php endpoint for browser redirect checkout. `/epay/submit.php` is the browser-oriented Epay compatibility endpoint. It creates or reuses a KyrenPay order and returns HTTP `302` to `/epay/redirect/{orderId}` or an upstream payment page. Use this path when the customer browser is redirected to checkout. It uses `pid + sign`, not `x-api-key`, and end-user browser visits do not require a merchant server IP allowlist. ## Parameters Required parameters: | Parameter | Description | | - | - | | `pid` | KyrenPay-issued merchant Epay-compatible merchant ID. | | `type` | Payment type. Supported values include `alipay`, `wxpay`, `creditcard`, `crypto`, `paynow`, and `duitnow` (DuitNow). | | `out_trade_no` | Your merchant order number. | | `notify_url` | Merchant payment result notification URL. | | `return_url` | Browser return URL after checkout. | | `name` | Order or product name. | | `money` | Decimal string amount, for example `"9.99"`. | | `sign` | Epay-compatible MD5 signature. | | `sign_type` | Signature type, usually `MD5`. | Optional parameters: | Parameter | Description | | - | - | | `money_type` | Currency or money type if provided by your existing integration. | | `display_merchant_name` | Per-payment merchant display name shown on KyrenPay intermediate payment pages. | | `param` | Passthrough merchant metadata returned in notifications. | | `userId` | Optional merchant user identifier passed to the payment gateway when supported. | | `device` | Optional device hint: `pc` or `mobile`. Reusing the same order number with a different Alipay/WeChat device flow can be rejected. | | `channel_param` | Optional channel-extension JSON string for non-credit-card payment types. When `type=creditcard`, its original value is included in the Epay signature but KyrenPay completely ignores it after signature verification. Do not send card number, expiry date, CVV, billing details, or contact information in `channel_param`; the buyer enters card details on a KyrenPay or upstream hosted page. Top-level `email`, `phone`, and `userId` parameters are unaffected. | ## Example form ```html theme={null}
``` ## Notification handling After payment completes, KyrenPay sends a GET request to `notify_url` with: `pid`, `trade_no`, `out_trade_no`, `type`, `name`, `money`, `trade_status`, `param`, `sign`, and `sign_type`. Verify the signature, process the result idempotently, then return the plain string: ```text theme={null} success ``` See [Epay MD5 signature](/epay-migration/signature) and the [`submit.php` API reference](/api-reference/epay-compatibility/submitphp-redirect-checkout-compatibility-endpoint). DuitNow uses `type=duitnow`. Availability requires an approved Waffo capability and an explicit merchant binding. The current Sandbox capability accepts USD; upstream country `MYS` is displayed as Malaysia (`MY`). # Payment API errors and status codes Source: https://docs.kyrenpay.com/errors Understand KyrenPay HTTP status codes and API error responses. Diagnose authentication, validation, rate-limit, and server errors. KyrenPay uses conventional HTTP status codes to indicate the success or failure of an API request. ## HTTP Status Codes | Status Code | Description | | - | - | | `200` | OK — Request succeeded | | `201` | Created — Resource created successfully | | `400` | Bad Request — Invalid parameters | | `401` | Unauthorized — Missing or invalid API key | | `403` | Forbidden — Insufficient permissions | | `404` | Not Found — Resource does not exist | | `409` | Conflict — Resource state or idempotency conflict | | `429` | Too Many Requests — Rate limit exceeded | | `500` | Internal Server Error — Something went wrong on our end | | `503` | Service Unavailable — Upstream service error | ## Error Response Format Application errors handled by the API use this JSON structure. Authentication middleware and proxy errors may have an empty or different body; check the HTTP status before parsing JSON. ```json theme={null} { "code": 40001, "message": "Validation failed", "error": { "field": "productId", "reason": "Product ID is required" } } ``` | Field | Type | Description | | - | - | - | | `code` | integer | Application error code; different from the HTTP status | | `message` | string | A human-readable error message | | `error.field` | string | The parameter that caused the error (if applicable) | | `error.reason` | string | Detailed explanation of what went wrong | > [!NOTE] > > `error` is optional. It is included when a field detail is available; `field` and `reason` may also be omitted independently. Do not depend on exact message text. ## Application Error Codes | Code | Meaning | | - | - | | `40001` | Invalid request or validation failure | | `40101` | Application-level unauthorized error | | `40102` | Token expired | | `40103` | Invalid API key | | `40301` | Forbidden | | `40401` | Resource not found | | `40901` | Conflict | | `40902` | Idempotency conflict | | `42901` | Rate limit exceeded | | `50001` | Internal server error | | `50002` | External service error (HTTP `503`) | | `60006` | Product not found | | `60007` | Checkout expired | | `60008` | Order not found | These codes identify the error condition. Business errors can use HTTP `400`; do not infer the HTTP status from the first digits of `code`. ## Common Errors ### 400 Bad Request Returned when the request body or parameters are invalid. ```json theme={null} { "code": 40001, "message": "Bad Request", "error": { "field": "price", "reason": "Price must be at least 0.01" } } ``` ### 401 Unauthorized Returned when the API key is missing or rejected. The authentication entrypoint does not guarantee a JSON body. If an application-level unauthorized error returns JSON, its `code` is `40101`. ### 404 Not Found Returned when the requested resource does not exist. ```json theme={null} { "code": 40401, "message": "Resource not found" } ``` ### 429 Too Many Requests Returned when a configured rate limit is exceeded. Defaults are **100 requests per minute per IP** for general API requests and **60 checkout creations per minute per authenticated merchant** for `POST /v1/checkouts`. These limits are configurable and are not a guaranteed production quota. ```json theme={null} { "code": 42901, "message": "Rate limit exceeded. Try again later." } ``` > [!TIP] > > Implement exponential backoff in your integration to handle rate limiting gracefully. ## Success Response Format Public merchant JSON API success responses include `code: 0` and `message: "success"`. Epay compatibility responses and file downloads follow their endpoint-specific formats. ```json theme={null} { "code": 0, "message": "success", "data": { // Response data here } } ``` For paginated endpoints, the `data` field contains `items` and `pagination`: ```json theme={null} { "code": 0, "message": "success", "data": { "items": [...], "pagination": { "page": 1, "size": 20, "total": 42, "totalPages": 3 } } } ``` # Payment integration and merchant FAQ Source: https://docs.kyrenpay.com/faq/common-questions Find answers to KyrenPay merchant questions about API access, Checkout, Webhooks, refunds, and settlement, with links to detailed guides. ## Getting started ### Which integration path should I use? Use native KyrenPay Checkout for new integrations. Use Epay compatibility only if you already have an Epay-style integration and want to keep most of your existing SDK or request shape. Read: [Start here](/start-here), [Epay-compatible migration](/epay-migration/overview). ### Can I create payments from the dashboard without using the API? Yes. You can create products and checkout links in the merchant dashboard. For automated checkout creation, use the API. Read: [Products dashboard](/dashboard/products), [Checkouts dashboard](/dashboard/checkouts), [Quickstart](/quickstart). ### What format should amount values use? Use decimal strings, not floating-point JSON numbers. For example, send `"9.99"` rather than `9.99`. Read: [Amount, currency, or timestamp validation fails](/troubleshooting/amount-currency-timestamp). ## API and Webhooks ### Why does my API request return 401? Common causes include a missing `x-api-key`, using the wrong key, using a key for the wrong environment, or an IP allowlist mismatch when enabled. Do not expose secret keys in browser code. Read: [API request returns 401](/troubleshooting/api-401), [Authentication](/authentication). ### Why did my Webhook signature verification fail? Verify the raw request body, use the correct Webhook secret, check the timestamp in milliseconds, rebuild the signed string exactly, and compare signatures in constant time. Read: [Webhook signature verification fails](/troubleshooting/webhook-signature-fails), [Webhook signatures](/webhooks/signatures). ### Why did my customer pay but not receive credits? Check whether the KyrenPay order is paid, whether your server received and processed the `order.paid` event, whether your fulfillment logic is idempotent, and whether you stored an internal user or order ID in `metadata`. Read: [Customer paid but was not credited](/troubleshooting/paid-but-not-credited). ## Dashboard and operations ### Where do I find an order? Use the Orders dashboard to search and inspect payment state. Share the KyrenPay order number with support when asking about a specific payment. Read: [Orders dashboard](/dashboard/orders), [Order status does not match expectation](/troubleshooting/order-status). ### Why is settlement not available? Settlement eligibility can depend on KYC/KYB status, available balance, pending balance, frozen funds, and configured thresholds. KyrenPay support can review a case, but the docs cannot guarantee approval or timing. Read: [Settlement eligibility is not met](/troubleshooting/settlement-eligibility). ### What information should I send support? Send the merchant account, affected workflow, order number or checkout session ID, timestamp, endpoint or dashboard page, response status, and redacted logs. Do not send full API keys, Webhook secrets, card data, or private credentials. Read: [Support escalation checklist](/copilot/support-escalation). ## Epay compatibility ### Can I keep using my Epay-style SDK? In many cases, yes. Replace the base URL, use KyrenPay-issued `pid` and merchant key, verify MD5 signing, and map payment types to KyrenPay-supported values. Read: [Epay migration checklist](/epay-migration/migration-checklist). ### How do I calculate the Epay MD5 signature? Remove `sign`, `sign_type`, and empty values; sort remaining parameters by key; join as `k=v` with `&`; append the merchant key directly; then compute lowercase MD5. Read: [Epay MD5 signature](/epay-migration/signature). ### Can I use `api.php?act=refund`? Yes, for eligible orders created through Epay compatibility endpoints. The merchant account must have refund access enabled; send `pid`, raw merchant `key`, `money`, and one of `out_trade_no` or `trade_no`. Use `refund_no` for idempotency. Read: [api.php order query and refund compatibility](/epay-migration/api-php). # Payment integration go-live checklist Source: https://docs.kyrenpay.com/go-live-checklist Review your KyrenPay API keys, Webhook signatures, order fulfillment, reconciliation, and support procedures before accepting production traffic. Use this checklist before sending real customers to KyrenPay checkout. ## Account and product setup * Your merchant profile is complete. * Your product name, description, amount, and currency are correct. * Amount values in your own system are stored and sent as decimal strings, such as `"9.99"`. * Your success and cancel URLs point to production pages. ## API keys * Your API key is stored only on your server. * Your API key is not included in browser JavaScript, mobile apps, logs, screenshots, or public repositories. * Your deployment environment uses the correct KyrenPay API base URL. ## Webhooks * Your Webhook URL is configured in the dashboard. * Your server verifies the KyrenPay Webhook signature. * Your server returns a 2xx response after processing a valid event. * Your fulfillment logic is idempotent and can handle repeated delivery. ## Orders and fulfillment * Your system fulfills only after a paid order or payment-success Webhook event. * Your internal order or user ID is stored in metadata when needed. * Your team knows how to find an order in the KyrenPay dashboard. ## Support readiness * Your support team knows where to find order numbers. * Your team can provide the checkout session ID, order number, timestamp, Webhook URL, and the response or error observed on your server when contacting KyrenPay support. ## Related pages * [Authentication](/authentication) * [Webhook signatures](/webhooks/signatures) * [Orders dashboard](/dashboard/orders) # Payment API code examples Source: https://docs.kyrenpay.com/guides/code-examples Use cURL, Python, Node.js, and Go examples to create KyrenPay products and Checkout Sessions and verify signed Webhook notifications. Complete code examples for common KyrenPay API operations in multiple languages. ## Create a Product ```bash cURL theme={null} curl -X POST https://api.kyrenpay.com/v1/products \ -H "Content-Type: application/json" \ -H "x-api-key: kyren_live_xxxxxxxxxxxx" \ -d '{ "name": "1000 AI Credits", "description": "Top up 1000 credits for AI API usage", "price": "9.99", "currency": "USD", "metadata": { "credits": "1000" } }' ``` ```python Python theme={null} import requests response = requests.post( "https://api.kyrenpay.com/v1/products", headers={ "Content-Type": "application/json", "x-api-key": "kyren_live_xxxxxxxxxxxx", }, json={ "name": "1000 AI Credits", "description": "Top up 1000 credits for AI API usage", "price": "9.99", "currency": "USD", "metadata": {"credits": "1000"}, }, ) product = response.json()["data"] print(f"Product created: {product['id']}") ``` ```javascript Node.js theme={null} const axios = require('axios'); const response = await axios.post('https://api.kyrenpay.com/v1/products', { name: '1000 AI Credits', description: 'Top up 1000 credits for AI API usage', price: '9.99', currency: 'USD', metadata: { credits: '1000' }, }, { headers: { 'x-api-key': 'kyren_live_xxxxxxxxxxxx' }, }); const product = response.data.data; console.log(`Product created: ${product.id}`); ``` ```go Go theme={null} package main import ( "bytes" "encoding/json" "fmt" "net/http" "io" ) func createProduct() { payload := map[string]interface{}{ "name": "1000 AI Credits", "description": "Top up 1000 credits for AI API usage", "price": "9.99", "currency": "USD", "metadata": map[string]string{"credits": "1000"}, } body, _ := json.Marshal(payload) req, _ := http.NewRequest("POST", "https://api.kyrenpay.com/v1/products", bytes.NewBuffer(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("x-api-key", "kyren_live_xxxxxxxxxxxx") resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() respBody, _ := io.ReadAll(resp.Body) fmt.Println(string(respBody)) } ``` ## Create a Checkout Session These are server-side request examples. Populate metadata with your authenticated user and server-generated business order ID; product metadata is not copied automatically. Session creation cannot override product amount, currency or quantity. Read Axios `response.data.data` or the JSON response's `data`, and durably associate its Session ID, URL, amount, currency and expiry with your business order before returning the URL to the browser. See the [full example](/guides/collect-first-payment) for concurrent purchases, uncertain creation outcomes, durable fulfillment and reconciliation. Never run API-key examples in a browser. ```bash cURL theme={null} curl -X POST https://api.kyrenpay.com/v1/checkouts \ -H "Content-Type: application/json" \ -H "x-api-key: kyren_live_xxxxxxxxxxxx" \ -d '{ "productId": "prod_abc123", "successUrl": "https://yoursite.com/success", "cancelUrl": "https://yoursite.com/cancel", "customerEmail": "customer@example.com", "displayMerchantName": "Campaign Store", "metadata": { "userId": "user_456" } }' ``` ```python Python theme={null} import requests response = requests.post( "https://api.kyrenpay.com/v1/checkouts", headers={ "Content-Type": "application/json", "x-api-key": "kyren_live_xxxxxxxxxxxx", }, json={ "productId": "prod_abc123", "successUrl": "https://yoursite.com/success", "cancelUrl": "https://yoursite.com/cancel", "customerEmail": "customer@example.com", "displayMerchantName": "Campaign Store", "metadata": {"userId": "user_456"}, }, ) checkout = response.json()["data"] print(f"Redirect customer to: {checkout['url']}") ``` ```javascript Node.js theme={null} const response = await axios.post('https://api.kyrenpay.com/v1/checkouts', { productId: 'prod_abc123', successUrl: 'https://yoursite.com/success', cancelUrl: 'https://yoursite.com/cancel', customerEmail: 'customer@example.com', displayMerchantName: 'Campaign Store', metadata: { userId: 'user_456' }, }, { headers: { 'x-api-key': 'kyren_live_xxxxxxxxxxxx' }, }); const checkout = response.data.data; console.log(`Redirect customer to: ${checkout.url}`); ``` ```go Go theme={null} func createCheckout() { payload := map[string]interface{}{ "productId": "prod_abc123", "successUrl": "https://yoursite.com/success", "cancelUrl": "https://yoursite.com/cancel", "customerEmail": "customer@example.com", "displayMerchantName": "Campaign Store", "metadata": map[string]string{"userId": "user_456"}, } body, _ := json.Marshal(payload) req, _ := http.NewRequest("POST", "https://api.kyrenpay.com/v1/checkouts", bytes.NewBuffer(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("x-api-key", "kyren_live_xxxxxxxxxxxx") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() respBody, _ := io.ReadAll(resp.Body) fmt.Println(string(respBody)) } ``` ## List Orders ```bash cURL theme={null} curl https://api.kyrenpay.com/v1/orders?status=PAID&page=1&size=10 \ -H "x-api-key: kyren_live_xxxxxxxxxxxx" ``` ```python Python theme={null} response = requests.get( "https://api.kyrenpay.com/v1/orders", headers={"x-api-key": "kyren_live_xxxxxxxxxxxx"}, params={"status": "PAID", "page": 1, "size": 10}, ) data = response.json()["data"] for order in data["items"]: print(f"Order {order['id']}: {order['amount']} {order['currency']}") print(f"Total: {data['pagination']['total']} orders") ``` ```javascript Node.js theme={null} const response = await axios.get('https://api.kyrenpay.com/v1/orders', { headers: { 'x-api-key': 'kyren_live_xxxxxxxxxxxx' }, params: { status: 'PAID', page: 1, size: 10 }, }); const { items, pagination } = response.data.data; items.forEach(order => { console.log(`Order ${order.id}: ${order.amount} ${order.currency}`); }); console.log(`Total: ${pagination.total} orders`); ``` ```go Go theme={null} func listOrders() { req, _ := http.NewRequest("GET", "https://api.kyrenpay.com/v1/orders?status=PAID&page=1&size=10", nil) req.Header.Set("x-api-key", "kyren_live_xxxxxxxxxxxx") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(string(body)) } ``` ## Get Account Balance ```bash cURL theme={null} curl https://api.kyrenpay.com/v1/balance \ -H "x-api-key: kyren_live_xxxxxxxxxxxx" ``` ```python Python theme={null} response = requests.get( "https://api.kyrenpay.com/v1/balance", headers={"x-api-key": "kyren_live_xxxxxxxxxxxx"}, ) balance = response.json()["data"] print(f"Available: {balance['available']} {balance['currency']}") print(f"Pending: {balance['pending']} {balance['currency']}") ``` ```javascript Node.js theme={null} const response = await axios.get('https://api.kyrenpay.com/v1/balance', { headers: { 'x-api-key': 'kyren_live_xxxxxxxxxxxx' }, }); const balance = response.data.data; console.log(`Available: ${balance.available} ${balance.currency}`); console.log(`Pending: ${balance.pending} ${balance.currency}`); ``` ```go Go theme={null} func getBalance() { req, _ := http.NewRequest("GET", "https://api.kyrenpay.com/v1/balance", nil) req.Header.Set("x-api-key", "kyren_live_xxxxxxxxxxxx") resp, _ := http.DefaultClient.Do(req) defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Println(string(body)) } ``` ## Verify Webhook Signature See the [Webhook Signatures](/webhooks/signatures) page for complete verification examples in Node.js, Python, and Go. # Collect your first payment with Checkout Source: https://docs.kyrenpay.com/guides/collect-first-payment Build a KyrenPay payment flow from product and Checkout creation to Webhook verification, durable event handling, and order fulfillment. This guide explains one-time hosted Checkout integration using a Node.js backend. The examples require your application's login and database adapters before they can run. The same flow applies to other languages. Before accepting payments, complete the [Quickstart prerequisites](/quickstart#prerequisites) and configure your public HTTPS Webhook URL and its separate Secret in the merchant dashboard. An `order.paid` event is not queued when the Webhook is unconfigured; configuring it after a payment does not automatically replay that payment. ## Choose your setup path * Use the dashboard guide if you want to create products and review orders manually first. * Use the API guide if your application should create checkout sessions from your server. Related pages: * [Products dashboard](/dashboard/products) * [Orders dashboard](/dashboard/orders) * [Quickstart](/quickstart) * [Webhook overview](/webhooks/overview) ## Overview ```mermaid theme={null} sequenceDiagram participant Customer participant YourServer as Your Server participant KyrenPay as KyrenPay API participant Checkout as Checkout Page Customer->>YourServer: Click "Buy Credits" YourServer->>KyrenPay: POST /v1/checkouts KyrenPay-->>YourServer: { data: { id: "cs_...", url: "https://payment.kyren.io/checkout/one-time/cs_..." } } YourServer-->>Customer: Redirect to checkout URL Customer->>Checkout: Complete payment Checkout->>KyrenPay: Payment confirmed KyrenPay->>YourServer: Webhook: order.paid YourServer-->>YourServer: Fulfill order ``` ## 1. Set Up Your Server Install the required dependencies: ```bash theme={null} npm init -y npm install express axios ``` Create your server file. Implement `app-adapters.js` using your application's authentication and database: * `requireUser` rejects unauthenticated requests and supplies `req.user` from a verified login, never from client-supplied user IDs. Apply your application's CSRF protection to cookie-authenticated purchase requests. * `checkoutStore.withLockedOrder(userId, productId, callback)` creates or locks the user's current pending business order, with authorization and a database lock or durable reservation across processes. Persist its expected product, price, currency and credit entitlement from your server's catalog. * `markCreationPending` durably records creation in progress **before** calling KyrenPay. `attachSession` stores the Session ID, URL, amount, currency and expiry, verifies them against the order, and clears that marker. Keep the marker on timeouts or failed local saves; releasing a lock must not roll it back. Do not automatically create another Session for an uncertain request: the current API has no Checkout creation idempotency key. * `webhookInbox.insertIfAbsent` durably inserts a pending event with a unique event ID. Existing events are acknowledged without resetting their processing state. A worker must claim pending events and retry failures until handled or escalated. * `fulfillPaidOrderIdempotently` checks the business order association, product, base amount and currency using decimal arithmetic. In one database transaction, uniquely record the KyrenPay order ID, mark the business order fulfilled and credit its recorded user and entitlement. Reject missing or mismatched associations. Apply it to both Webhooks and reconciliation. Register JSON parsing only on normal routes, as shown below. Never register a global `express.json()` before the raw Webhook route. The code below deliberately uses `KYREN_PRODUCT_ID` as a minimal single-product shortcut. This is not a platform-required environment variable or the default Agent integration workflow. For an existing application, prefer a repeatable setup step that queries/reuses or, within authorization, creates products and persists local SKU mappings, as described in [Quickstart](/quickstart). Resolve the mapped product ID from the trusted server catalog when creating Checkout instead of copying this single-product constant into every purchase. ```javascript theme={null} // server.js const express = require('express'); const crypto = require('crypto'); const axios = require('axios'); const { requireUser, checkoutStore, webhookInbox, fulfillPaidOrderIdempotently } = require('./app-adapters'); const app = express(); const KYREN_API_KEY = process.env.KYREN_API_KEY; const KYREN_WEBHOOK_SECRET = process.env.KYREN_WEBHOOK_SECRET; const KYREN_BASE_URL = process.env.KYREN_BASE_URL || 'https://api.kyrenpay.com'; const KYREN_PRODUCT_ID = process.env.KYREN_PRODUCT_ID; if (!KYREN_API_KEY || !KYREN_WEBHOOK_SECRET || !KYREN_PRODUCT_ID) { throw new Error('Configure API key, Webhook secret and product ID'); } ``` ## 2. Create a Product (One-Time Setup) For this optional single-product example, create or select a fixed-price product once via the API or dashboard and set its `data.id` as `KYREN_PRODUCT_ID`. In an application-managed mapping flow, persist that ID against its local SKU instead. Checkout takes its amount and currency from that product; it does not accept per-session price, quantity or currency overrides. Product metadata is not automatically merged into Checkout metadata. Keep the expected entitlement in your business order. Create the product before starting `server.js`, because startup requires its ID. For example, with `KYREN_API_KEY` already set in your shell: ```bash theme={null} curl --fail-with-body -X POST "${KYREN_BASE_URL:-https://api.kyrenpay.com}/v1/products" \ -H "Content-Type: application/json" \ -H "x-api-key: ${KYREN_API_KEY}" \ -d '{"name":"1000 AI Credits","price":"9.99","currency":"USD"}' ``` Use the returned `data.id` in the startup command. The function below is an alternative server-side request example; defining it does not execute it. Set `KYREN_BASE_URL` to the environment paired with your credentials when using an issued staging or local environment; changing credentials alone does not change the target API. ```javascript theme={null} async function createProduct() { const response = await axios.post(`${KYREN_BASE_URL}/v1/products`, { name: '1000 AI Credits', description: 'Top up 1000 credits for AI API usage', price: '9.99', currency: 'USD', metadata: { credits: '1000' } }, { headers: { 'x-api-key': KYREN_API_KEY } }); console.log('Product created:', response.data.data.id); return response.data.data; } ``` ## 3. Create Checkout Endpoint Add an endpoint that creates a checkout session when the customer clicks "Buy": ```javascript theme={null} app.post('/api/buy-credits', requireUser, express.json(), async (req, res) => { try { const checkout = await checkoutStore.withLockedOrder(req.user.id, KYREN_PRODUCT_ID, async (order) => { const headers = { 'x-api-key': KYREN_API_KEY }; if (order.checkoutId) { const response = await axios.get(`${KYREN_BASE_URL}/v1/checkouts/${order.checkoutId}`, { headers, timeout: 10000 }); const existing = response.data.data; if (existing.status === 'OPEN' && existing.expiresAt > Date.now()) return existing; throw new Error('Reconcile the previous checkout before starting another purchase'); } if (order.creationPending) throw new Error('Checkout creation requires reconciliation'); await checkoutStore.markCreationPending(order.id); const response = await axios.post(`${KYREN_BASE_URL}/v1/checkouts`, { productId: KYREN_PRODUCT_ID, successUrl: 'https://yoursite.com/payment/success', cancelUrl: 'https://yoursite.com/payment/cancel', customerEmail: req.user.email, metadata: { businessOrderId: order.id, userId: String(req.user.id) } }, { headers, timeout: 10000 }); const session = response.data.data; if (response.data.code !== 0 || !session?.id || !session?.url) throw new Error('Invalid checkout response'); await checkoutStore.attachSession(order.id, session); return session; }); res.json({ checkoutId: checkout.id, checkoutUrl: checkout.url }); } catch (error) { res.status(503).json({ error: 'Checkout unavailable; reconcile before retrying' }); } }); ``` ## 4. Handle the Frontend Redirect On your frontend, redirect the customer to the checkout page: ```html theme={null} ``` ## 5. Handle Webhooks Add a webhook endpoint to receive payment notifications: ```javascript theme={null} function verifySignature(payload, signature, timestamp) { if (typeof signature !== 'string' || !/^sha256=[0-9a-f]{64}$/.test(signature)) return false; if (typeof timestamp !== 'string' || !/^\d+$/.test(timestamp)) return false; const sentAt = Number(timestamp); if (!Number.isSafeInteger(sentAt) || Math.abs(Date.now() - sentAt) > 300000) return false; const data = `${timestamp}.${payload}`; const expected = 'sha256=' + crypto .createHmac('sha256', KYREN_WEBHOOK_SECRET) .update(data) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(expected), Buffer.from(signature) ); } app.post('/webhooks/kyren', express.raw({ type: 'application/json' }), async (req, res) => { const signature = req.headers['x-kyren-signature']; const timestamp = req.headers['x-kyren-timestamp']; if (!Buffer.isBuffer(req.body)) return res.status(400).send('Raw JSON body required'); const payload = req.body.toString('utf8'); if (!verifySignature(payload, signature, timestamp)) { return res.status(400).send('Invalid signature'); } let event; try { event = JSON.parse(payload); } catch { return res.status(400).send('Invalid JSON'); } if (!event || typeof event.id !== 'string' || !event.id || typeof event.type !== 'string' || !event.data) { return res.status(400).send('Invalid event'); } try { await webhookInbox.insertIfAbsent(event.id, event); } catch { return res.status(503).send('Retry later'); } res.status(200).send('OK'); } ); ``` ## 6. Process Notifications and Reconcile Payments Run the following functions from your durable inbox worker and a scheduled reconciliation job, respectively. Mark an inbox event processed only after `processWebhook` succeeds; a failure must remain retryable. ```javascript theme={null} async function processWebhook(event) { if (event.type !== 'order.paid') return; const data = event.data; await fulfillPaidOrderIdempotently({ businessOrderId: data.metadata?.businessOrderId, kyrenOrderId: data.order_id, productId: data.product_id, amount: data.amount, currency: data.currency }); } async function reconcilePayment(order) { const headers = { 'x-api-key': KYREN_API_KEY }; const sessionResponse = await axios.get(`${KYREN_BASE_URL}/v1/checkouts/${order.checkoutId}`, { headers, timeout: 10000 }); const session = sessionResponse.data.data; if (session.status !== 'COMPLETE' || !session.orderId) return; const paymentResponse = await axios.get(`${KYREN_BASE_URL}/v1/orders/${session.orderId}`, { headers, timeout: 10000 }); const payment = paymentResponse.data.data; if (payment.status !== 'PAID') return; if (payment.checkoutSessionId !== order.checkoutId || payment.metadata?.businessOrderId !== order.id) { throw new Error('Payment association mismatch'); } await fulfillPaidOrderIdempotently({ businessOrderId: order.id, kyrenOrderId: payment.id, productId: payment.productId, amount: payment.baseAmount, currency: payment.currency }); } ``` Load reconciliation orders from your own database; do not accept arbitrary order IDs from the browser. Handle refunds separately using [Webhook events](/webhooks/events). Both payment paths must use the same fulfillment transaction so a late Webhook cannot credit an already reconciled order again. Checkout expires after 24 hours and uses `OPEN`, `COMPLETE`, `EXPIRED`. Its successful KyrenPay `orderId` is available through the authenticated Session query; it is not returned when creating the Session. An expired or canceled browser flow is not proof that an existing payment attempt failed. Reconcile before offering a replacement purchase. Show pending status on `successUrl` until your backend confirms payment; never credit from a browser redirect. Use the exact returned `data.url`, without constructing the hosted path yourself. ## 7. Start the Server ```javascript theme={null} app.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); ``` Run your server: ```bash theme={null} KYREN_API_KEY=kyren_live_xxx KYREN_WEBHOOK_SECRET=whsec_xxx KYREN_PRODUCT_ID=prod_xxx node server.js ``` ## 8. Test the Flow 1. If KyrenPay has issued staging credentials or enabled a test-capable gateway for your merchant account, run the flow with those credentials and the payment scenarios KyrenPay provides. 2. If you only have live credentials, verify the flow with a low-risk real payment in production. 3. Confirm your customer is redirected to the KyrenPay checkout page. 4. Confirm your server receives the payment Webhook and that your fulfillment logic handles the event correctly. Test duplicate and concurrent notifications, unavailable inbox storage, worker restart, a Webhook racing reconciliation, and expired Sessions. Each business order must credit at most once, and failed persistence must return a non-`2xx` response. 5. If you used a real payment for verification, refund or handle it operationally according to KyrenPay support guidance if needed. > [!TIP] > > Your integration is ready when checkout creation, redirect handling, Webhook receipt, and fulfillment have all been verified with the credentials and gateway KyrenPay has enabled for your account. ## Next Steps > [card] [Webhook Events](/webhooks/events) > > See all available webhook event types > [card] [Code Examples](/guides/code-examples) > > See integration examples in other languages # new-api payment integration with Epay Source: https://docs.kyrenpay.com/integrations/new-api Configure new-api balance top-ups with KyrenPay Epay settings, merchant credentials, payment methods, and notification checks. Use new-api's built-in **Epay** integration to collect balance top-ups with KyrenPay. This guide applies to [QuantumNous/new-api at commit `56758ed`](https://github.com/QuantumNous/new-api/tree/56758edf95ec162033a6b73b553ac789404f87c9), verified on October 1, 2026, using `go-epay v0.0.4`. Older releases and forks may use different menus or amount calculations. ## Before you start * Prepare a KyrenPay merchant account with the required payment provider bound and credentials active. Enable only methods available to that account. * Obtain the merchant account ID and the complete, current API key beginning with `kyren_live_`. The raw API key, including its prefix, is the Epay merchant secret; a masked key or Webhook secret will not work. * Deploy new-api behind a public HTTPS domain, for example `https://ai.example.com`, with its API callback routed to the backend. See [Developer settings](/dashboard/developer-settings) and [Epay compatibility](/epay-migration/overview). ## Configure Epay 1. Open **System Settings > Billing & Payments > Payment Gateway** (`/system-settings/billing/payment`). 2. For the initial setup, the root administrator must read and complete the page's **Compliance Confirmation**. Payment settings and online top-ups remain locked until confirmation is complete. Skip this step if the page already shows **Compliance Confirmed**. 3. Under **Epay**, enter the payment endpoint, merchant ID, merchant secret key and callback base address (`CustomCallbackAddress`). Enter only the public site origin for the callback address, without the notification path. 4. Under **General**, configure the price, minimum top-up, payment methods, preset recharge amounts and discounts, then click **Save All Settings**. ![new-api Epay settings: payment endpoint, callback address, merchant ID and secret key](https://mintcdn.com/kyren/x94voPzRsCxE5d_B/images/integrations/new-api-epay-settings.png?fit=max\&auto=format\&n=x94voPzRsCxE5d_B\&q=85\&s=9f8f0f78cd14e6c060db5cfe75761403) The screenshot shows an example interface in Simplified Chinese. Use the endpoint and credentials from the table below for your integration. | new-api setting | Value | | - | - | | Payment address (`PayAddress`) | `https://api.kyrenpay.com/epay/` | | Merchant ID (`EpayId`) | Your KyrenPay merchant account ID (`pid`) | | Merchant key (`EpayKey`) | Your complete current `kyren_live_...` API key | | Custom callback address (`CustomCallbackAddress`) | `https://ai.example.com` | | Server address (`ServerAddress`) | Your public new-api origin | | Price (`Price`) | Your chosen Epay base amount in CNY per USD of balance | | Minimum top-up (`MinTopUp`) | Your chosen minimum recharge amount | If the custom callback address is empty, new-api uses `ServerAddress`. It appends `/api/user/epay/notify`; enter the origin rather than the full callback path. The SDK appends `submit.php` to the payment address while retaining `/epay`, resulting in `https://api.kyrenpay.com/epay/submit.php`. [Settings UI](https://github.com/QuantumNous/new-api/blob/56758edf95ec162033a6b73b553ac789404f87c9/web/src/features/system-settings/integrations/payment-settings-section.tsx), [callback origin](https://github.com/QuantumNous/new-api/blob/56758edf95ec162033a6b73b553ac789404f87c9/service/epay.go), [SDK URL construction](https://github.com/Calcium-Ion/go-epay/blob/d8c8810761402e9de0320c4b7eed3cfd7fa94461/epay/order.go). ## Configure payment methods The General settings offer a visual editor and JSON editor for `PayMethods`. The `type` is sent to Epay. Start with the methods enabled for your merchant, for example: ```json theme={null} [ { "name": "Alipay", "type": "alipay", "icon": "SiAlipay" }, { "name": "WeChat Pay", "type": "wxpay", "icon": "SiWechat" } ] ``` This verified version accepts custom Epay method types. You can add entries with `type` equal to `creditcard`, `crypto` or `paynow`, and a suitable display name, when those methods are enabled for your KyrenPay account. Do not use another gateway's aliases. The documented KyrenPay codes here are `alipay`, `wxpay`, `creditcard`, `crypto` and `paynow`. [Payment-method settings](https://github.com/QuantumNous/new-api/blob/56758edf95ec162033a6b73b553ac789404f87c9/web/src/features/system-settings/integrations/payment-settings-section.tsx), [method passed to Epay](https://github.com/QuantumNous/new-api/blob/56758edf95ec162033a6b73b553ac789404f87c9/controller/topup.go). ## Set the amount and credited balance The built-in client does not send `money_type`, so KyrenPay charges **CNY**. A USD or CNY display preference does not change that request currency. For USD display with a requested balance amount `A`, the Epay base amount in CNY is `A × Price × user-group recharge ratio × preset discount`, formatted to two decimals. The credited internal quota is `A × QuotaPerUnit`. For an initial check, use USD display, group ratio `1` and discount `1`. If you deliberately configure `Price = 7.00`, requesting **USD 10.00** balance sends an Epay base amount of **CNY 70.00** and credits **USD 10.00** balance. `7.00` is an example configuration, not a current exchange-rate quote. The Epay base amount is not always the final checkout total. KyrenPay may add a customer-paid fee according to your payment channel's fee-sharing settings. The example total is exactly **CNY 70.00** only when no KyrenPay customer-paid fee applies. Epay notification and order-query `money` report the base amount; new-api credits the quota from its stored recharge amount, rather than any additional fee. Compare the base amount, displayed checkout total and expected credited balance separately. In TOKENS display mode, the request is converted through `QuotaPerUnit`; check the installed version's rounding and recharge presets before using that mode. Confirm the charge and credited balance in a small payment before enabling public top-ups. [Amount calculation and request](https://github.com/QuantumNous/new-api/blob/56758edf95ec162033a6b73b553ac789404f87c9/controller/topup.go), [credit calculation](https://github.com/QuantumNous/new-api/blob/56758edf95ec162033a6b73b553ac789404f87c9/model/topup.go). ## Verify payment and crediting 1. Sign in as a test user, record the starting balance and create a small recharge. Record `out_trade_no`, the Epay base amount and the displayed CNY checkout total. 2. Complete payment and confirm the corresponding KyrenPay order is paid. Confirm the new-api recharge record is successful and the intended balance increase is present. 3. Check that the public backend receives KyrenPay's signed GET notification at `https://ai.example.com/api/user/epay/notify`. The built-in handler verifies Epay MD5, handles `TRADE_SUCCESS`, credits the stored recharge order and returns the plain text `success`. 4. Confirm a repeated notification for that order does not add quota again. The verified implementation uses a database transaction and order-state check to prevent duplicate crediting. Do not credit from the browser return URL or treat a return-page visit as payment proof. [Callback implementation](https://github.com/QuantumNous/new-api/blob/56758edf95ec162033a6b73b553ac789404f87c9/controller/topup.go), [transactional crediting](https://github.com/QuantumNous/new-api/blob/56758edf95ec162033a6b73b553ac789404f87c9/model/topup.go). See [Epay MD5 signatures](/epay-migration/signature) and [Paid but not credited](/troubleshooting/paid-but-not-credited). ## Common configuration problems ### Acceptance limits in the documented version Local tests against the pinned commit's actual controller, Epay SDK and SQLite transaction logic confirmed ordinary crediting and duplicate protection. They also found that `EpayNotify` does not compare signed callback `money` with the stored `TopUp.Money`: a stored CNY 70.00 purchase accepted a correctly signed CNY 0.01 callback and credited its full stored entitlement. Changing an unsigned amount still fails signature verification; this finding concerns a signed amount mismatch. Before production readiness, require that mismatch to be rejected by a verified application version or an explicitly reviewed application change. Do not mark this acceptance check passed for the documented commit. In TOKENS display, requesting 5,250,000 quota units with `QuotaPerUnit = 500,000` and `Price = 7.00` sent CNY 73.50 but persisted integer `Amount = 10` and credited 5,000,000 quota units. Start with the documented USD/integer-balance configuration and verify fractional TOKENS conversion before enabling it. These are isolated source-level tests, not a payment on your deployment. * **Wrong payment URL:** preserve `/epay/` in `PayAddress`; the SDK adds `submit.php` itself. * **Wrong charge:** check `Price`, group recharge ratio, preset discounts, quota display mode and KyrenPay customer-paid fees together. Display currency does not select KyrenPay's charge currency. * **Paid but not credited:** check callback origin, public HTTPS access, GET query forwarding and backend logs. The callback must not redirect to login or require a browser challenge. * **IP allowlist:** this built-in purchase flow uses browser `submit.php`. Do not add customer IPs to the server API allowlist; server-side `mapi.php` calls require the calling server's outbound IP when the allowlist is enabled. * **Key rotation:** regenerating the KyrenPay API key invalidates the old Epay secret. Update `EpayKey` immediately, then check a new payment and pending callbacks. Keep secrets out of logs and support tickets. These instructions were checked against source code; they do not represent a live payment test on your deployment. # sub2api payment integration with EasyPay Source: https://docs.kyrenpay.com/integrations/sub2api Configure sub2api balance top-ups through its built-in EasyPay provider using KyrenPay credentials, payment methods, and notification checks. Use sub2api's built-in **EasyPay** provider to collect balance top-ups with KyrenPay. This guide applies to [Wei-Shaw/sub2api at commit `42bc7f6`](https://github.com/Wei-Shaw/sub2api/tree/42bc7f6cffe24bcb471608e48e66b4a0afa1f882), verified on October 1, 2026. Older releases and forks may have different settings; confirm that your version includes the native provider and the fields below. ## Before you start * Prepare a KyrenPay merchant account with the required payment provider bound and credentials active. Only enable payment methods available to that account. * Obtain the merchant account ID for `pid` and the complete, current API key beginning with `kyren_live_` for the merchant secret. Use the raw key, including its prefix, rather than a masked value or Webhook secret. Store it in the administrator settings only. * Deploy sub2api behind a public HTTPS domain, for example `https://ai.example.com`, with its payment callback routed to the backend. See [Developer settings](/dashboard/developer-settings) and [Epay compatibility](/epay-migration/overview). ## Configure the payment provider 1. Open **Admin > System Settings > Payment Settings**, turn on the **Enable Payment** master switch at the top of the page, and select EasyPay under **Enabled Providers**. When the master switch is off, payment orders cannot be created even if a provider instance is enabled. 2. Under **Provider Management**, add an **EasyPay** provider instance, enter the settings from the table below, and turn on the instance's **Enabled** switch. 3. Save the provider instance, then click **Save Settings** on the payment settings page to save the master switch and provider selection. You can obtain your KyrenPay merchant account ID (PID) and PKey from **KyrenPay Merchant Dashboard > Developer Tools > API Keys**. ![sub2api EasyPay provider settings: custom payment methods, PID, PKey, API base and notification and return addresses](https://mintcdn.com/kyren/x94voPzRsCxE5d_B/images/integrations/sub2api-easypay-settings.png?fit=max\&auto=format\&n=x94voPzRsCxE5d_B\&q=85\&s=e0af8b86e92fadc7c4aca86948cfa51d) The screenshot shows an example interface in Simplified Chinese. Use the endpoint, site origin and credentials from the table below for your integration. | sub2api setting | Value | | - | - | | Provider | `easypay` / EasyPay | | Instance name | `KyrenPay` | | PID (`pid`) | Your KyrenPay merchant account ID | | PKey (`pkey`) | Your complete current `kyren_live_...` API key | | API base (`apiBase`) | `https://api.kyrenpay.com/epay` | | Payment mode (`payment_mode`) | `popup` for hosted browser checkout, or `qrcode` for server-side creation | | Notification URL base | `https://ai.example.com` | | Return URL base | `https://ai.example.com` | | Alipay / WeChat channel ID (`cidAlipay`, `cidWxpay`) | Leave blank | The callback editor appends fixed paths. The resulting URLs are `https://ai.example.com/api/v1/payment/webhook/easypay` and `https://ai.example.com/payment/result`; enter only the origin in those base inputs. `popup` builds `/epay/submit.php`; `qrcode` calls `/epay/mapi.php`. The API base is normalized and the endpoint appended by the provider. [Settings fields](https://github.com/Wei-Shaw/sub2api/blob/42bc7f6cffe24bcb471608e48e66b4a0afa1f882/frontend/src/components/payment/providerConfig.ts), [callback editor](https://github.com/Wei-Shaw/sub2api/blob/42bc7f6cffe24bcb471608e48e66b4a0afa1f882/frontend/src/components/payment/PaymentProviderDialog.vue), [EasyPay client](https://github.com/Wei-Shaw/sub2api/blob/42bc7f6cffe24bcb471608e48e66b4a0afa1f882/backend/internal/payment/provider/easypay.go). ## Choose payment methods Select the built-in `alipay` and/or `wxpay` options as enabled for your merchant. This verified version also has a **Custom payment methods** editor. To offer other documented KyrenPay methods, add matching local and upstream type values, then select the resulting supported methods: | Local type | Upstream type | Display name | | - | - | - | | `creditcard` | `creditcard` | Card | | `crypto` | `crypto` | Crypto | | `paynow` | `paynow` | PayNow | Do not copy a different gateway's type aliases or channel IDs. Availability also depends on your KyrenPay provider binding. If your installed version lacks the custom-method editor, verify or upgrade that version before exposing these methods. [Custom-method editor and serialization](https://github.com/Wei-Shaw/sub2api/blob/42bc7f6cffe24bcb471608e48e66b4a0afa1f882/frontend/src/components/payment/PaymentProviderDialog.vue). ## Set the amount and credited balance This EasyPay client does not send `money_type`, so KyrenPay interprets `money` as **CNY**. Changing a currency label or product-name suffix does not change the request currency. For balance top-ups, sub2api credits `recharge amount × balance recharge multiplier`, rounded to two decimals. Its separate recharge surcharge increases the Epay request amount, with the surcharge rounded up to cents. For an initial check, set `payment_balance_recharge_multiplier = 1` and `payment_recharge_fee_rate = 0`: a recharge amount of `10.00` sends an Epay base amount of **CNY 10.00** and credits **10.00 balance units**. Choose your intended conversion policy before enabling public recharge; a USD balance display does not perform exchange conversion automatically. [Order calculation](https://github.com/Wei-Shaw/sub2api/blob/42bc7f6cffe24bcb471608e48e66b4a0afa1f882/backend/internal/service/payment_order.go), [balance multiplier](https://github.com/Wei-Shaw/sub2api/blob/42bc7f6cffe24bcb471608e48e66b4a0afa1f882/backend/internal/service/payment_amounts.go), [surcharge rounding](https://github.com/Wei-Shaw/sub2api/blob/42bc7f6cffe24bcb471608e48e66b4a0afa1f882/backend/internal/payment/fee.go). The Epay base amount is not always the final checkout total. KyrenPay may add a customer-paid fee according to your payment channel's fee-sharing settings. The example total is exactly **CNY 10.00** only when no KyrenPay customer-paid fee applies. Epay notification and order-query `money` report the base amount; sub2api credits its stored balance amount, rather than any additional fee. Compare the base amount, displayed checkout total and expected credited balance separately. ## Verify payment and crediting 1. Save the settings, sign in as a test user and create a small top-up. Record the merchant order number (`out_trade_no`), Epay base amount, displayed CNY checkout total and starting balance. 2. Complete payment and confirm that the corresponding KyrenPay order is paid. Check the sub2api payment order and confirm the intended balance increase. 3. Confirm that the backend received the signed GET notification at `/api/v1/payment/webhook/easypay`, verified the Epay MD5 signature and `TRADE_SUCCESS`, and returned the plain text `success`. 4. Confirm a repeated notification for the same order does not add balance again. A return-page visit or HTTP `success` response alone is insufficient evidence of crediting; check the order and balance records together. The built-in handler accepts GET notifications and performs verification through the provider. Its acknowledgement can also cover an unknown order, so inspect backend logs if KyrenPay is paid but balance has not increased. [Callback routes](https://github.com/Wei-Shaw/sub2api/blob/42bc7f6cffe24bcb471608e48e66b4a0afa1f882/backend/internal/server/routes/payment.go), [callback handler](https://github.com/Wei-Shaw/sub2api/blob/42bc7f6cffe24bcb471608e48e66b4a0afa1f882/backend/internal/handler/payment_webhook_handler.go). See [Epay MD5 signatures](/epay-migration/signature) and [Paid but not credited](/troubleshooting/paid-but-not-credited). ## Common configuration problems ### Acceptance limits in the documented version Local tests using the pinned commit's real provider, Webhook handler, payment service and PostgreSQL repository found an amount tolerance: a correctly signed `money = 9.99` was accepted for an expected `10.00` order and credited the stored `10.00` balance amount; a large amount mismatch was rejected without crediting. The implemented tolerance is 0.01, not exact decimal equality. Concurrent deliveries can return a retryable conflict rather than all returning `success`. Check that failed attempts are retried and the final order and balance show one fulfillment. These results do not establish a live payment test or an exact-match amount policy on your deployment. * **Wrong endpoint:** preserve `/epay/` in the API base. Do not enter the merchant dashboard URL or a complete `submit.php` URL. * **Server-side creation denied:** if KyrenPay's API IP allowlist is enabled, allow the sub2api server's outbound IP for `mapi.php`. Browser `submit.php` checkout does not require adding each customer's IP. * **Notification missing:** make the HTTPS callback publicly reachable, preserve GET query parameters and route it to the backend without login redirects or browser challenges. * **Signature failure after key rotation:** regenerating the KyrenPay API key invalidates the old secret. Update the provider's PKey immediately and verify a new payment and any pending callbacks. Never publish the key in a support ticket. These instructions were checked against source code; they do not represent a live payment test on your deployment. # Payment API & Checkout documentation Source: https://docs.kyrenpay.com/introduction Integrate KyrenPay payments for your AI or SaaS product. Explore payment APIs, hosted Checkout, signed Webhooks, Epay migration, and merchant guides. ## Build your payment integration with KyrenPay KyrenPay helps **Chinese developers, AI applications, and SaaS teams** accept payments from international customers. Use these guides to create a payment link, integrate the payment API, confirm orders, and reconcile funds. > [card] [Start your integration](/start-here) > > Choose an integration path for your product, from dashboard payment links to a server-side Checkout flow. ## Choose your path > [card] [Payment API quickstart](/quickstart) > > Authenticate your server, create a product and Checkout Session, and send customers to hosted checkout. > [card] [Payment links without code](/dashboard/checkouts) > > Create and share Checkout links from the merchant dashboard, then track orders and payment status. > [card] [Verify payment notifications](/webhooks/overview) > > Handle signed Webhooks, verify events, and make fulfillment safe to retry. > [card] [Migrate an Epay integration](/epay-migration/overview) > > Keep compatible request formats while connecting an existing Epay client to KyrenPay. Using an AI gateway? Follow the dedicated [new-api](/integrations/new-api) or [sub2api](/integrations/sub2api) guide to connect balance top-ups through its built-in Epay integration. ## From Checkout to a confirmed order **1. Prepare your merchant account** Review onboarding, enabled [payment methods](/dashboard/payment-methods), and [API credentials](/authentication) before starting. **2. Create a product and Checkout Session** Define your product, price, and currency. Create the session on your server and redirect the customer to its Checkout URL. **3. Configure and verify Webhooks** Set your notification URL before the first payment. Verify signatures against the original request body and handle duplicate events. **4. Confirm payment and fulfill the order** Use verified payment events and order records to update your system. A browser redirect alone is not proof of payment. For a complete implementation, see [Collect your first payment](/guides/collect-first-payment) and the [go-live checklist](/go-live-checklist). ## Payment methods and availability Available payment methods, currencies, and limits depend on your merchant account, bound channels, and platform configuration. Check [Payment methods](/dashboard/payment-methods) and the [supported currencies API](/api-reference/config/get-supported-currencies) for your integration. Fees and settlement conditions follow your merchant agreement. ## API base URL | Environment | Base URL | | - | - | | Production | `https://api.kyrenpay.com` | Review [Testing](/testing) before running payment checks. Use staging only with the environment and credentials provided by KyrenPay. ## Keep building > [card] [Explore the API reference](/api-reference/config/get-supported-currencies) > > Find request fields, response formats, and examples for products, Checkout, orders, refunds, and balances. > [card] [Find an answer](/faq/common-questions) > > Get help with authentication, payment notifications, order status, and settlement eligibility. # Payment API quickstart Source: https://docs.kyrenpay.com/quickstart Create a KyrenPay product and Checkout Session, redirect customers to hosted checkout, and verify signed payment Webhooks on your server. Follow this guide when you want your server to create KyrenPay checkout sessions through the API. If you want to learn the dashboard first, start with [Dashboard overview](/dashboard/overview). ## Prerequisites * A KyrenPay merchant account ([sign up here](https://merchant.kyrenpay.com)) * Your API key (found in the Developer section of your dashboard) * A product created in the dashboard or through the Products API * A server-side environment where your API key can be stored securely * A Webhook endpoint for payment notifications before you go live For one-time payments, the product must be `ACTIVE`, hosted Checkout must be enabled for your merchant, and an enabled channel must support the product's currency and amount. Resolve merchant agreement restrictions when applicable. Product creation alone does not guarantee an available payment method. Current per-order caps are USD 630.00, CNY 4,000.00, HKD 5,000.00 and IDR 10,000,000.00; channel and merchant limits may be lower. If an API IP whitelist is configured, allow your server's outbound IP. Before the first payment, configure a public HTTPS Webhook URL and obtain its separate Webhook Secret in **Developer Tools > Webhook Settings**. This is not your API Key. Unconfigured Webhooks do not queue ordinary `order.paid` events; later configuration does not automatically replay past payments. ## Step 1: Get your API Key After signing up, navigate to **Dashboard > Developer Tools > API Keys**. A full key is shown only when generated. Use your securely stored original value, not its masked display. Regeneration immediately invalidates the old key. * **Live key**: `kyren_live_xxxxxxxxxxxx` — use this for production > [!WARNING] > > Keep your API keys secure. Never expose them in client-side code or public repositories. Privately put the full value in your application's server-side `KYREN_API_KEY` setting, not in an Agent chat. Generate a key on this page if none exists. If you already have one, use its securely saved full value rather than regenerating it as a routine integration step. ### Configure Webhook and get its Secret 1. Open **Dashboard > Developer Tools > Webhooks**. 2. Enter your application's actual public HTTPS callback URL in **Webhook URL** and save, for example `https://your-app.example/webhooks/kyren`. Use the path implemented by your application. Kyren cannot reach localhost; local testing needs a reachable HTTPS host or an authorized tunnel. 3. First configuration generates a Webhook Secret. Immediately copy its full value into your application's private server-side `KYREN_WEBHOOK_SECRET` setting. If no Secret exists, click Generate. 4. If a Secret is already configured, use its securely saved original. Its masked display cannot verify signatures. Regeneration immediately invalidates the old Secret and requires updating every server that uses it; do not rotate it as a default setup step. The Webhook Secret and API key are different values. An existing Webhook URL may serve another application; confirm its use before changing it. See [Developer settings](/dashboard/developer-settings). This guide uses production addresses. If your integration selects a Kyren-provided development or other environment, use that environment's dashboard, API Base URL and matching credentials throughout instead of switching to the production examples. ## Step 2: Initialize Product Mappings For an application integration, have its setup code or Agent initialize products from the existing catalog. Query the paginated `GET /v1/products` list and reuse an unambiguously matching `ACTIVE` one-time product, checking identity, price and currency. If none matches, create one with `POST /v1/products` within the user's authorization. Read `data.items` and `data.pagination` for lists and `data.id` for creation. Persist each local SKU-to-Kyren-product-ID mapping in the application's database or existing durable catalog, scoped to the environment and merchant. Its backend resolves the mapping when creating Checkout; users do not need to copy every product ID themselves. Price alone is not a product identity. Ask the user to resolve ambiguous matches, and identify missing credentials or creation authorization. Repeated initialization should reuse mappings. Reconcile a create timeout or failed local save before retrying; do not recreate products on every startup or purchase. The following is a manual single-product example. You can also create/select a product in **Dashboard > Product Management** and copy its **Product ID**: ```bash theme={null} curl -X POST https://api.kyrenpay.com/v1/products \ -H "Content-Type: application/json" \ -H "x-api-key: kyren_live_xxxxxxxxxxxx" \ -d '{ "name": "1000 AI Credits", "description": "Top up 1000 credits for AI API usage", "price": "9.99", "currency": "USD" }' ``` Save `data.id` from the JSON response. For example, `{ "code": 0, "message": "success", "data": { "id": "prod_abc123" } }` illustrates the envelope with other product fields omitted. A product ID is not a secret, merchant PID, Checkout ID or order ID. `KYREN_PRODUCT_ID` is only an optional setting for a simple single-product application, not an environment variable the platform requires. For Agent-assisted integration, prefer implementing lookup, authorized creation and durable mappings; the user confirms the catalog/prices and privately configures credentials. The application provides its actual initialization and reload commands. ## Step 3: Create a Checkout Session When a customer wants to pay, create a checkout session: ```bash theme={null} curl -X POST https://api.kyrenpay.com/v1/checkouts \ -H "Content-Type: application/json" \ -H "x-api-key: kyren_live_xxxxxxxxxxxx" \ -d '{ "productId": "prod_abc123", "successUrl": "https://yoursite.com/success", "cancelUrl": "https://yoursite.com/cancel", "displayMerchantName": "Campaign Store", "metadata": { "businessOrderId": "purchase_123", "userId": "user_123" } }' ``` Use `displayMerchantName` when this checkout should show a campaign, store, or app name that differs from your account name. The response is `{ "code": 0, "message": "success", "data": { ... } }`. Read `data.id`, `data.url`, `data.amount`, `data.currency` and `data.expiresAt` (Unix milliseconds), and persist them against your server-generated business order before returning its URL to the browser. Product ID, user identity and metadata must come from trusted server records. Session amount and currency come from the product; price, quantity and currency overrides are not supported. Create one pending Session per business purchase and reuse it on repeated clicks. Sessions expire after 24 hours. The API has no Checkout creation idempotency key, so persist a creation reservation and reconcile timeouts or failed local saves before creating another Session. See the [full example](/guides/collect-first-payment). ## Step 4: Redirect to Checkout Redirect the customer to the checkout URL returned in Step 3. They will see a hosted payment page where they can choose their preferred payment method. ```javascript theme={null} // Example: redirect in your web app // checkoutUrl is supplied by your authenticated backend, from KyrenPay's data.url. window.location.href = checkoutUrl; ``` ## Step 5: Handle the Webhook After payment, KyrenPay sends a signed JSON POST to your configured Webhook URL. Register the raw-body route before any global JSON parser. The following route requires the [signature function](/webhooks/signatures) and the durable inbox adapter described in the [full example](/guides/collect-first-payment): ```javascript theme={null} const crypto = require('crypto'); function verifyWebhookSignature(payload, signature, timestamp, secret) { if (typeof secret !== 'string' || !secret) return false; if (typeof signature !== 'string' || !/^sha256=[0-9a-f]{64}$/.test(signature)) return false; if (typeof timestamp !== 'string' || !/^\d+$/.test(timestamp)) return false; const sentAt = Number(timestamp); if (!Number.isSafeInteger(sentAt) || Math.abs(Date.now() - sentAt) > 300000) return false; const data = `${timestamp}.${payload}`; const expected = 'sha256=' + crypto .createHmac('sha256', secret) .update(data) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(expected), Buffer.from(signature) ); } app.post('/webhooks/kyren', express.raw({ type: 'application/json' }), async (req, res) => { const signature = req.headers['x-kyren-signature']; const timestamp = req.headers['x-kyren-timestamp']; if (!Buffer.isBuffer(req.body)) return res.status(400).send('Raw JSON body required'); const payload = req.body.toString('utf8'); if (!verifyWebhookSignature(payload, signature, timestamp, process.env.KYREN_WEBHOOK_SECRET)) { return res.status(400).send('Invalid signature'); } let event; try { event = JSON.parse(payload); } catch { return res.status(400).send('Invalid JSON'); } if (!event || typeof event.id !== 'string' || !event.id || typeof event.type !== 'string' || !event.data) { return res.status(400).send('Invalid event'); } try { await webhookInbox.insertIfAbsent(event.id, event); } catch { return res.status(503).send('Retry later'); } res.status(200).send('OK'); } ); ``` > [!NOTE] > > Configure your URL in **Dashboard > Developer Tools > Webhook Settings**. Verify, persist, then return `2xx` within 10 seconds. A durable worker must retry failures, deduplicate event IDs and credit each business order only once using a unique KyrenPay order ID and a database transaction. `successUrl` and `cancelUrl` are browser navigation, not payment evidence. Your backend can query `GET /v1/checkouts/{id}`: `OPEN` is pending, `COMPLETE` includes the successfully associated `orderId`, and `EXPIRED` closes the Session. For missed notifications, query `GET /v1/orders/{orderId}`, verify payment and its product/base amount/currency/metadata association, and use the same idempotent fulfillment transaction as Webhooks. Session creation does not return an `orderId`. Use the exact returned `data.url`. `successUrl` is required; `cancelUrl` is optional. ## What's Next? > [card] [Authentication](/authentication) > > Learn about API authentication in detail > [card] [Webhook Signatures](/webhooks/signatures) > > Implement secure webhook verification > [card] [Testing](/testing) > > Test safely with KyrenPay-issued staging credentials or low-risk live checks > [card] [Code Examples](/guides/code-examples) > > See examples in Python, Node.js, Go, and more # Choose your payment integration Source: https://docs.kyrenpay.com/start-here Choose a KyrenPay integration path: dashboard payment links, server-side Checkout, new-api or sub2api top-ups, and production readiness. Use this page to choose the right setup path for your team. > [card] [Use the dashboard first](/dashboard/overview) > > Create products, generate checkout links, review orders, and configure developer settings in the merchant dashboard. > [card] [Integrate the API](/quickstart) > > Create products and checkout sessions from your server, then fulfill orders from Webhook events. > [card] [Collect your first payment](/guides/collect-first-payment) > > Follow an end-to-end flow from product creation to Webhook handling. > [card] [Prepare for production](/go-live-checklist) > > Review keys, Webhooks, order handling, and support handoff before launch. ## Recommended path For sub2api or new-api, start with [sub2api configuration](/integrations/sub2api) or [new-api configuration](/integrations/new-api). Use their Epay integration to collect one-time balance payments; product and Checkout creation in the native API are a separate integration path. 1. Create or review your merchant account. 2. Create a product. 3. Create a checkout session or checkout link. 4. Complete a payment flow. 5. Configure and verify Webhooks. 6. Confirm order fulfillment in your system. 7. Review the go-live checklist. ## Related pages * [Dashboard overview](/dashboard/overview) * [Quickstart](/quickstart) * [Collect your first payment](/guides/collect-first-payment) * [Go-live checklist](/go-live-checklist) # Testing Source: https://docs.kyrenpay.com/testing Test your KyrenPay integration before going live Use this page to test your integration without making assumptions about unsupported environments. ## Current environment model | Item | Current behavior | | - | - | | Production API | `https://api.kyrenpay.com` | | Production API key prefix | `kyren_live_` | | Self-service test keys | Not currently exposed in the merchant dashboard | | Staging access | Available only with a base URL and credentials issued by KyrenPay | > [!WARNING] > > Do not send test traffic to an arbitrary staging URL unless KyrenPay has issued credentials for that environment. ## Test API Keys Use an API key issued for the target environment: ```bash theme={null} curl https://api.kyrenpay.com/v1/products \ -H "x-api-key: kyren_live_xxxxxxxxxxxxxxxxxxxx" ``` ## Test Card Numbers Use these card numbers only when KyrenPay has issued a staging or test-capable environment, or when KyrenPay has enabled a test-capable payment gateway for your merchant. Do not assume these card numbers produce deterministic outcomes on production checkout sessions. | Card Number | Behavior | | - | - | | `4242 4242 4242 4242` | Payment succeeds | | `4000 0000 0000 0002` | Card declined | | `4000 0000 0000 9995` | Insufficient funds | For all test cards: * Use any future expiration date (e.g., `12/28`) * Use any 3-digit CVV (e.g., `123`) * Use any cardholder name * Use any billing address ## Test WeChat Pay / Alipay QR payment behavior depends on the gateway configuration attached to your merchant. Use KyrenPay-provided credentials for the target environment or coordinate a callback simulation when validating asynchronous status updates. ## Testing Webhooks When testing webhooks locally, you can use a tunneling tool like [ngrok](https://ngrok.com) to expose your local server: ```bash theme={null} # Start your local webhook handler node server.js # listening on port 3000 # In another terminal, create a tunnel ngrok http 3000 ``` Then configure the ngrok URL as your webhook endpoint in the Dashboard: ``` https://abc123.ngrok.io/webhooks/kyren ``` > [!TIP] > > Remember to update your webhook URL to your production endpoint before going live. ## Going Live Checklist Before switching to production, make sure you have: **1. Replace API keys** Use the production key issued for `api.kyrenpay.com` **2. Update base URL** If KyrenPay issued a staging base URL, change from that URL to `api.kyrenpay.com` **3. Update webhook URL** Set your production webhook endpoint in the Dashboard **4. Verify webhook signatures** Ensure your server correctly verifies `X-Kyren-Signature` headers **5. Handle errors gracefully** Test error scenarios and ensure your app handles them properly # Amount, currency, or timestamp validation fails Source: https://docs.kyrenpay.com/troubleshooting/amount-currency-timestamp Fix common formatting errors for amounts, currencies, and timestamps. ## Symptom KyrenPay rejects a request because an amount, currency, or timestamp field is invalid. ## Likely causes * Amounts are sent as JSON numbers instead of strings. * Amount strings contain commas, currency symbols, or unsupported precision. * The currency is not supported for the requested product or payment method. * The currency code is not a three-letter code such as `USD`. * Timestamps are sent in seconds or formatted date strings instead of Unix milliseconds. * Date-range queries use the wrong timezone or swap start and end timestamps. ## Check this in KyrenPay * Confirm supported currencies before creating checkout sessions. * Compare the product currency with the request currency. * Review examples in the API reference for timestamp fields. ## Check this in your server * Send amount values as strings, such as `"9.99"`. * Use uppercase three-letter currency codes. * Send Unix millisecond timestamps, such as `1736932200000`. * For date ranges, ensure `start_time` is earlier than `end_time`. ## Fix Normalize request data before calling KyrenPay: convert decimal amounts to strings, validate currency codes against supported currencies, and convert dates to Unix milliseconds. ## Contact support if unresolved Contact KyrenPay support with the endpoint path, response error, amount string, currency code, and timestamp values used in the request. ## Related pages * [Get supported currencies API reference](/api-reference/config/get-supported-currencies) * [Testing](/testing) # API request returns 401 Source: https://docs.kyrenpay.com/troubleshooting/api-401 Diagnose KyrenPay API authentication failures. ## Symptom Your server calls a KyrenPay API endpoint and receives `401 Unauthorized`. If your Checkout API call returns `401`, check authentication before changing product or Session parameters. Check the `x-api-key` header, the credential's environment and your server's IP allowlist entry. See [Checkout Quickstart](/quickstart) for the required server-side credentials. ## Likely causes * The `x-api-key` header is missing or empty. * The API key is invalid, expired, or was rotated. * The request uses a key from the wrong environment. * IP allowlisting is enabled and the request comes from an unlisted server IP. * The key was exposed and should no longer be trusted. ## Check this in KyrenPay * Open **Dashboard > Developer settings** and confirm the active API key. * If IP allowlisting is enabled, confirm your outbound server IP is listed. * If the key may have been exposed, rotate it and update your server configuration. ## Check this in your server * Confirm the request sends `x-api-key` exactly as an HTTP header. * Check that secrets were loaded into the running process after deployment. * Verify the request is going to the intended KyrenPay API base URL. * Search recent deploys for key rotation, secret name, or configuration changes. ## Fix 1. Add or correct the `x-api-key` header. 2. Replace stale keys with the current key from Developer settings. 3. Update the IP allowlist when your hosting provider changes outbound IPs. 4. Rotate any key that was committed, logged, or shared outside trusted systems. ## Contact support if unresolved Contact KyrenPay support with the request time, endpoint path, response status, and merchant account. Do not send your full API key. ## Related pages * [Authentication](/authentication) * [Developer settings](/dashboard/developer-settings) * [Testing](/testing) # Checkout session creation fails Source: https://docs.kyrenpay.com/troubleshooting/checkout-session-fails Fix validation and configuration errors when creating checkout sessions. ## Symptom Creating a Checkout Session returns an error or no hosted checkout URL is created. ## Likely causes * The `product_id` does not exist or belongs to another merchant. * The product is archived and can no longer be used for new sessions. * Hosted Checkout is disabled for the merchant, or applicable merchant agreement restrictions remain unresolved. * The product amount exceeds per-order limits; payment also needs an enabled channel supporting its currency. * Required `successUrl` (also accepted as `success_url`) is missing or invalid. `cancelUrl` / `cancel_url` is optional; omitting it does not fail creation. * Authentication failed before the checkout request was processed. ## Check this in KyrenPay * Confirm the product is active in **Dashboard > Products**. * Check the product price and currency in the dashboard. * Confirm your checkout settings use valid return URLs. * Review Developer settings if the API response indicates authentication failure. ## Check this in your server * Create Checkout with `productId` and `successUrl`, without amount, quantity or currency overrides; the Session uses its product's price and currency. * When creating or updating a product, send `price` as a decimal string such as `"9.99"` and use an allowed three-letter currency code. * `successUrl` is required and accepts `http://` or `https://`; use absolute HTTPS URLs in production. If supplied, use a valid site URL for `cancelUrl` too. * If an API IP whitelist is configured, check your server's outbound IP. Read `data.id` and `data.url`, not top-level fields. * Log the request body and KyrenPay response status, excluding secrets. ## Fix Use your merchant's active product, the required success URL and a valid `x-api-key`. Confirm hosted Checkout access, enabled channels, amount limits and applicable agreement status. Correct price and currency issues in the product configuration. ## Contact support if unresolved Contact KyrenPay support with the request time, product ID, currency, response status, and error message. Do not send API keys. ## Related pages * [Quickstart](/quickstart) * [Dashboard checkouts](/dashboard/checkouts) * [Create a checkout session API reference](/api-reference/checkouts/create-a-checkout-session) # Order status does not match expectation Source: https://docs.kyrenpay.com/troubleshooting/order-status Understand KyrenPay order statuses and reconciliation checks. ## Symptom An order status in KyrenPay differs from what your system or customer expected. ## Likely causes | Status | What it usually means | | - | - | | `pending` | Payment is not completed or the gateway has not confirmed the final result. | | `paid` | Payment succeeded and your system can fulfill if other checks pass. | | `failed` | Payment was declined, canceled, or failed at the payment gateway. | | `closed` / `expired` | The checkout or payment window ended before successful payment. | | `refunded` | A refund has been recorded where available. | Gateway delays can cause short-lived differences between customer-facing payment screens, KyrenPay order status, and your internal system. Epay source orders may also require extra reconciliation against the source order identifier. ## Check this in KyrenPay * Open **Dashboard > Orders** and search for the order. * Compare status, amount, currency, creation time, and paid time. * Check whether the order has an Epay source order identifier. ## Check this in your server * Compare the KyrenPay order ID with your internal order ID. * Confirm whether your system relies on Webhooks, polling, or both. * Check whether an early `pending` status was cached after the order later changed. * Use millisecond timestamps when comparing API data, such as `1736932200000`. ## Fix Use `paid` as the fulfillment signal, keep fulfillment idempotent, and refresh order status before manual reconciliation. Treat `pending` as waiting unless your business rules explicitly close the internal order. ## Contact support if unresolved Contact KyrenPay support with the KyrenPay order number, source order identifier if present, expected status, observed status, and timestamps. ## Related pages * [Dashboard orders](/dashboard/orders) * [Retrieve an order API reference](/api-reference/orders/retrieve-an-order) # Customer paid but was not credited Source: https://docs.kyrenpay.com/troubleshooting/paid-but-not-credited Reconcile paid orders that were not fulfilled in your system. ## Symptom The customer completed payment, but your application did not grant access, credits, or the purchased item. ## Likely causes * Your server is still waiting for the `order.paid` Webhook event. * Your fulfillment worker received the event but failed before updating the user. * Idempotency logic marked a duplicate event as processed too early. * The checkout metadata did not include your internal user ID or order ID. * Your system checked order status before payment processing finished. ## Check this in KyrenPay * Open **Dashboard > Orders** and search by order number, customer email, or time range. * Confirm the KyrenPay order status is `paid`. * Compare the order amount, currency, and paid time with your internal record. ## Check this in your server * Search your Webhook endpoint logs for the event time and KyrenPay order ID. * Confirm the event handler maps `metadata` to the correct internal user or order. * Check fulfillment retries, queue failures, and database write errors. * Make fulfillment idempotent by KyrenPay order ID or event ID. ## Fix If the KyrenPay order is paid, reconcile it against your internal order and re-run fulfillment using your own recovery process. Store internal user IDs in checkout metadata so future events can be matched reliably. ## Contact support if unresolved Contact KyrenPay support with the KyrenPay order number, paid time, amount, currency, and your server log timestamps. ## Related pages * [Dashboard orders](/dashboard/orders) * [Webhook events](/webhooks/events) * [Webhook retries](/webhooks/retries) # Settlement eligibility is not met Source: https://docs.kyrenpay.com/troubleshooting/settlement-eligibility Understand why a merchant account may not yet be eligible for settlement. ## Symptom Your merchant account or balance is not currently eligible for settlement. ## Likely causes * Required KYC or KYB information is missing, incomplete, or under review. * Available balance is below the configured minimum balance or settlement threshold. * Funds are pending and have not moved into available balance. * Some funds are frozen for risk, dispute, compliance, or operational review. * Support needs additional information before the case can move forward. ## Check this in KyrenPay * Review account verification prompts in the dashboard. * Compare pending balance with available balance. * Check whether a settlement threshold is configured for your account. * Review recent orders that may still be pending or under review. ## Check this in your server * Confirm your internal finance report uses available balance, not pending balance. * Reconcile orders by status and paid time before estimating settlement readiness. * Keep legal entity, contact, and bank information consistent with submitted KYC or KYB data. ## Fix Complete requested KYC or KYB information, reconcile pending and available balances, and provide any information requested by support. Eligibility depends on account configuration and review status. ## Contact support if unresolved Contact KyrenPay support with your merchant account, available balance, pending balance, and any dashboard message shown. Support can review the case but cannot guarantee approval or timing. ## Related pages * [Dashboard orders](/dashboard/orders) * [Go-live checklist](/go-live-checklist) # Webhook not received Source: https://docs.kyrenpay.com/troubleshooting/webhook-not-received Find why your server did not receive a KyrenPay Webhook event. ## Symptom An expected payment event occurred, but your Webhook endpoint did not receive a request. ## Likely causes * The configured Webhook URL is wrong or points to an old endpoint. * The URL is not public or cannot be reached from the internet. * Your endpoint returns a non-`2xx` response. * Your endpoint times out before responding. * A firewall, WAF, or reverse proxy blocks the request. * Local development uses no tunnel or a stale tunnel URL. * The expected event type does not match the action that occurred. ## Check this in KyrenPay * Compare the Webhook URL configured in the dashboard with your current endpoint. * Confirm the URL includes the correct scheme, host, path, and trailing slash behavior. * Confirm you are expecting an event type that KyrenPay sends for that payment state. ## Check this in your server * Compare your access logs with the configured Webhook URL and event time. * Confirm the endpoint is public and accepts HTTPS `POST` requests. * Return `2xx` quickly, then process the event asynchronously if needed. * Check firewall, WAF, CDN, and load balancer rules. * For local development, verify the active tunnel URL matches the dashboard setting. ## Fix Update the configured Webhook URL, make the endpoint publicly reachable, and return a fast `2xx` response. Remove network rules that block KyrenPay requests. ## Contact support if unresolved Contact KyrenPay support with the order number, expected event type, configured Webhook URL host and path, and your server log timestamps. ## Related pages * [Webhook overview](/webhooks/overview) * [Webhook retries](/webhooks/retries) * [Testing](/testing) # Webhook signature verification fails Source: https://docs.kyrenpay.com/troubleshooting/webhook-signature-fails Fix common KyrenPay Webhook signature verification errors. ## Symptom Your Webhook endpoint receives a request, but signature verification fails. ## Likely causes * Your framework parsed or reformatted the JSON before verification. * The verifier uses the wrong Webhook secret. * Middleware altered whitespace, encoding, or field order in the body. * The timestamp is handled as seconds instead of Unix milliseconds. * The signed string uses the wrong concatenation format. * The comparison is not constant-time and fails or leaks timing information. ## Check this in KyrenPay * Copy the current Webhook secret from Developer settings. * Confirm the request headers include `X-Kyren-Signature` and `X-Kyren-Timestamp`. * Confirm the timestamp value is a millisecond timestamp, such as `1736932200000`. ## Check this in your server * Verify against the raw request body bytes before JSON parsing. * Build the signed string as `timestamp + "." + raw_body`. * Compute `sha256=` plus the HMAC-SHA256 digest using the Webhook secret. * Compare the expected and received signatures with a constant-time function. ## Fix Change the route to read the raw body for KyrenPay Webhooks, use the current Webhook secret, treat timestamps as Unix milliseconds, and match the documented signing format exactly. ## Contact support if unresolved Contact KyrenPay support with the event time, order number, timestamp header, and a redacted description of your verification code. Do not send the Webhook secret. ## Related pages * [Webhook signatures](/webhooks/signatures) * [Collect your first payment](/guides/collect-first-payment) # Payment, refund, and dispute Webhook events Source: https://docs.kyrenpay.com/webhooks/events Explore KyrenPay order.paid, order.refunded, dispute.created, and dispute.updated Webhook payloads and their delivery conditions. KyrenPay sends webhook notifications for the following event types. ## Event Types | Event | Description | Trigger | | - | - | - | | `order.paid` | A payment has been confirmed | Customer completes checkout | | `order.refunded` | A refund has been applied to an order | A refund succeeds | The current order integration does not emit an `order.closed` webhook. Query `GET /v1/orders/{orderId}` to reconcile unpaid terminal states such as `FAILED`, `CLOSED`, or `REVOKED`; see [Orders](/dashboard/orders). ## Event Object Structure All webhook events share the same top-level structure: ```json theme={null} { "id": "evt_abc123", "type": "order.paid", "created_at": 1736932500000, "data": { // Event-specific data } } ``` | Field | Type | Description | | - | - | - | | `id` | string | Unique event identifier (use for deduplication) | | `type` | string | The event type | | `created_at` | integer | Unix timestamp in milliseconds | | `data` | object | Event-specific payload | ## order.paid Sent when a customer successfully completes a payment. ```json theme={null} { "id": "evt_abc123", "type": "order.paid", "created_at": 1736932500000, "data": { "order_id": "order_def456", "product_id": "prod_abc123", "customer_email": "customer@example.com", "amount": "9.99", "currency": "USD", "net_amount": "9.29", "paid_at": 1736932500000, "metadata": { "user_id": "u_123" } } } ``` | Field | Type | Description | | - | - | - | | `order_id` | string | The order ID | | `product_id` | string | The product that was purchased; may be empty for orders without a product | | `customer_email` | string \| null | Customer's email address, if available | | `amount` | string | Original/base order amount; excludes an additional fee charged to the payer | | `currency` | string | Three-letter currency code | | `net_amount` | string | Amount after fees | | `paid_at` | integer \| null | When the payment was confirmed (Unix timestamp in milliseconds), if available | | `metadata` | object \| null | Merchant metadata from the checkout session; internal provider fields are filtered out | > [!TIP] > > This is the most important event. Use it to fulfill orders — for example, adding credits to a user's account. ## order.refunded Sent when a refund has been applied to an order. Use this event to update entitlement, balance, or reconciliation records in your system. See [Order refunds](/dashboard/order-refunds) for the dashboard refund request flow and refund status definitions. ```json theme={null} { "id": "evt_refund123", "type": "order.refunded", "created_at": 1736932600000, "data": { "order_id": "order_def456", "refund_id": "refund_abc123", "refund_status": "PARTIAL", "amount": "2.50", "currency": "USD", "refunded_amount": "2.50", "original_amount": "9.99", "reason": "customer_request", "metadata": { "user_id": "u_123" } } } ``` | Field | Type | Description | | - | - | - | | `order_id` | string | The order ID | | `refund_id` | string | The refund ID | | `refund_status` | string | Order refund status, such as `PARTIAL` or `FULL` | | `amount` | string | Amount refunded by this event | | `currency` | string | Three-letter currency code | | `refunded_amount` | string | Total refunded amount on the order after this refund | | `original_amount` | string | Original/base order amount; excludes an additional fee charged to the payer | | `reason` | string \| null | Refund reason | | `metadata` | object \| null | Merchant metadata from the checkout session; internal provider fields are filtered out | ## Dispute Events (When Available) If dispute processing is supported and enabled for your account, you may also receive these notifications. Availability depends on the provider and operational configuration; confirm it with KyrenPay support. See [Disputes](/dashboard/disputes). | Event | Trigger | | - | - | | `dispute.created` | A dispute case is first matched to your order and becomes visible to you | | `dispute.updated` | Merchant-visible case details or financial projection change | Both use the same event envelope. Their `data` contains the following case snapshot; nullable values may be unavailable: | Field | Type | Description | | - | - | - | | `id` | string | Dispute case ID, distinct from the top-level event ID | | `provider` | string | Payment provider | | `provider_dispute_id` | string \| null | Provider's dispute ID | | `order_id` | string \| null | Related order ID | | `type`, `status` | string | Case type and normalized status | | `provider_status` | string \| null | Provider status | | `amount`, `currency` | string | Case amount and currency | | `reason_code`, `reason` | string \| null | Dispute reason | | `defendable` | boolean \| null | Whether defense is available, if known | | `response_due_at`, `occurred_at` | integer \| null | Unix timestamps in milliseconds | | `updated_at` | integer | Case update time in milliseconds | | `financial_status`, `financial_allocation_status` | string | Case financial processing and allocation status | | `settlement_currency` | string \| null | Currency of the financial amounts below | | `allocated_merchant_principal`, `allocated_rolling_reserve` | string | Principal and reserve allocated to this case | | `frozen_principal`, `charged_back_principal` | string | Principal frozen or charged back for this case | | `offset_rolling_reserve`, `chargeback_fee` | string | Reserve offset and merchant chargeback fee for this case | | `projection_state` | string \| null | State of the related order's financial projection | | `related_case_count` | integer | Number of cases sharing the order projection | | `shared_order_projection` | boolean | Whether multiple cases share that projection | These are operational case notifications. A change to `status` alone does not prove a balance movement; use the financial fields and dashboard records for reconciliation. Financial amounts are scoped to the individual case, even when `shared_order_projection` is true. ## Handling Events Here's how to handle webhook events in your endpoint: ```javascript theme={null} app.post('/webhooks/kyren', async (req, res) => { // ... verify signature first ... const event = JSON.parse(req.body.toString()); try { switch (event.type) { case 'order.paid': await handleOrderPaidIdempotently(event.id, event.data); break; case 'order.refunded': await handleOrderRefundedIdempotently(event.id, event.data); break; case 'dispute.created': case 'dispute.updated': await handleDisputeIdempotently(event.id, event.data); break; default: console.log(`Unhandled event: ${event.type}`); } res.status(200).send('OK'); } catch (error) { res.status(500).send('Retry later'); } }); ``` The handlers must durably complete their work before acknowledging the event. For longer processing, use the [durable queue pattern](/webhooks/retries) and return `2xx` only after persistence succeeds. # Payment Webhooks integration Source: https://docs.kyrenpay.com/webhooks/overview Configure KyrenPay payment Webhooks, understand event delivery, and connect signature verification, retries, and order fulfillment. Webhooks allow KyrenPay to notify your server when a payment or refund succeeds. See [Events](/webhooks/events) for supported events and optional dispute notifications. ## How Webhooks Work ```mermaid theme={null} sequenceDiagram participant Customer participant KyrenPay as KyrenPay participant YourServer as Your Server Customer->>KyrenPay: Completes payment KyrenPay->>KyrenPay: Process payment KyrenPay->>YourServer: POST webhook (signed) YourServer->>YourServer: Verify signature YourServer->>YourServer: Persist event to durable inbox YourServer-->>KyrenPay: 200 OK YourServer->>YourServer: Process event with worker retries ``` 1. An event occurs (e.g., a customer completes a payment) 2. KyrenPay sends an HTTP POST request to your configured webhook URL 3. The request includes a signature for verification 4. Your server verifies the signature, persists the event, and returns `200` within 10 seconds 5. Your worker processes the persisted event with idempotency and its own retries ## Configuring Webhooks Set up your webhook endpoint in the [Merchant Dashboard](https://merchant.kyrenpay.com): 1. Go to **Dashboard > Developer > Webhook Settings** 2. Enter your **Webhook URL** (e.g., `https://yoursite.com/webhooks/kyren`) 3. Copy your **Webhook Secret** — you'll need this to verify signatures > [!WARNING] > > Your webhook URL must: > > * Use HTTPS (required for production) > * Be publicly accessible > * Complete a `2xx` response within 10 seconds, after durable persistence succeeds ## Webhook Payload Every webhook request includes these headers: | Header | Description | | - | - | | `Content-Type` | `application/json` | | `X-Kyren-Signature` | HMAC-SHA256 signature for verification | | `X-Kyren-Timestamp` | Unix timestamp in milliseconds when the webhook was sent | The request body is a JSON object: ```json theme={null} { "id": "evt_abc123", "type": "order.paid", "created_at": 1736932500000, "data": { "order_id": "order_def456", "product_id": "prod_abc123", "customer_email": "customer@example.com", "amount": "9.99", "currency": "USD", "net_amount": "9.29", "paid_at": 1736932500000, "metadata": null } } ``` ## Best Practices > [card] Verify Signatures > > Always verify the `X-Kyren-Signature` header to ensure the webhook is authentic. See [Webhook Signatures](/webhooks/signatures). > [card] Return 200 Quickly > > Verify the signature and durably store the event before returning `200`. Return non-`2xx` if persistence fails, so KyrenPay can retry. > [card] Handle Duplicates > > Use the event `id` to deduplicate. Your endpoint may receive the same event more than once due to retries. > [card] Use a Queue > > For asynchronous processing, persist to a durable inbox or queue and acknowledge only after storage succeeds. Workers need their own retries after KyrenPay receives `2xx`. ## Next Steps > [card] [Events](/webhooks/events) > > See all event types > [card] [Signatures](/webhooks/signatures) > > Verify webhook signatures > [card] [Retries](/webhooks/retries) > > Understand retry behavior # Webhook retries and duplicate events Source: https://docs.kyrenpay.com/webhooks/retries Understand KyrenPay Webhook retry timing, successful acknowledgments, and idempotent handling of duplicate payment notifications. If your webhook endpoint doesn't respond with a `2xx` status code, KyrenPay will automatically retry the delivery. ## Retry Schedule For order and dispute events described in this guide, KyrenPay makes up to **7 delivery attempts in total: the initial attempt plus 6 retries**. | Attempt | Delay After Failure | | - | - | | 1st retry | 1 minute | | 2nd retry | 5 minutes | | 3rd retry | 15 minutes | | 4th retry | 1 hour | | 5th retry | 6 hours | | 6th retry | 24 hours | Each delay is measured from the preceding failed attempt; actual dispatch may occur later. After 7 failed delivery attempts, the webhook is marked as **failed** and automatic retries stop. ## What Counts as a Failure A webhook delivery is considered failed if: * Your endpoint returns a non-`2xx` HTTP status code (e.g., `400`, `500`) * Your endpoint doesn't complete its response within **10 seconds** * The connection to your server fails (DNS error, connection refused, timeout) > [!NOTE] > > A `2xx` response (e.g., `200`, `201`, `204`) is considered a successful delivery regardless of the response body. ## Handling Retries Since webhooks may be retried, your endpoint should be **idempotent** — processing the same event multiple times should produce the same result. ### Use Event IDs for Deduplication Every webhook event has a unique `id` field. Store processed event IDs durably, with a unique constraint, and commit the business change and processed marker in the same transaction: ```javascript theme={null} app.post('/webhooks/kyren', async (req, res) => { // ... verify signature ... const event = JSON.parse(req.body.toString()); try { await database.transaction(async tx => { // Atomic insert with a unique event ID; duplicates return false. if (!await tx.processedEvents.insertIfAbsent(event.id)) return; await processEvent(tx, event); }); res.status(200).send('OK'); } catch (error) { res.status(500).send('Retry later'); } }); ``` > [!TIP] > > The database methods above illustrate the transaction contract; adapt them to your storage system. Also protect the business operation with a stable identifier, such as `order_id` for payment fulfillment or `refund_id` for a refund. For dispute updates, do not deduplicate only by case ID because one case can have multiple updates. ### Return 200 Quickly For long processing, validate the signature and durably persist the event in an inbox or queue before returning `200`. A worker can then process it with its own retries. If persistence fails, return a non-`2xx` response so KyrenPay can retry: ```javascript theme={null} app.post('/webhooks/kyren', async (req, res) => { // ... verify signature ... const event = JSON.parse(req.body.toString()); try { // Resolves only after durable storage; event.id has a unique constraint. await webhookInbox.insertIfAbsent(event.id, event); res.status(200).send('OK'); } catch (error) { res.status(503).send('Retry later'); } }); ``` ## Monitoring Webhook Deliveries When troubleshooting delivery, compare KyrenPay Webhook events with your own server logs. Record: * Your configured Webhook URL * The event type and order number * The timestamp when your server received the request * The response code or error your server returned If you need KyrenPay to check delivery attempts, contact support with those details. ## Troubleshooting | Problem | Solution | | - | - | | Not receiving webhooks | Check your webhook URL is correct and publicly accessible | | Signature verification fails | Ensure you're using the raw request body (not parsed JSON) | | Frequent timeouts | Persist to a durable inbox or queue, return `200` within 10 seconds, then process with worker retries | | Duplicate events | Implement idempotency using the event `id` field | # Verify Webhook signatures with HMAC-SHA256 Source: https://docs.kyrenpay.com/webhooks/signatures Verify KyrenPay Webhook signatures using HMAC-SHA256, the original request body, and your Webhook secret before trusting payment events. Every webhook request from KyrenPay includes a cryptographic signature that you should verify to ensure the request is authentic and hasn't been tampered with. ## Signature Algorithm KyrenPay uses **HMAC-SHA256** to sign webhook payloads: ``` signature = "sha256=" + HMAC-SHA256(timestamp + "." + payload, webhook_secret) ``` The signature and timestamp are sent in HTTP headers: | Header | Example | | - | - | | `X-Kyren-Signature` | `sha256=5d2dc4f1a...` | | `X-Kyren-Timestamp` | `1704628800000` (Unix timestamp in milliseconds) | ## Verification Steps **1. Extract headers** Read `X-Kyren-Signature` and `X-Kyren-Timestamp` from the request headers. **2. Check timestamp** Verify the timestamp is within 5 minutes (300000 milliseconds) of the current time. This prevents replay attacks. **3. Compute expected signature** Concatenate `timestamp + "." + raw_request_body`, then compute HMAC-SHA256 using your webhook secret. **4. Compare signatures** Compare the computed signature with the one in the header. Use constant-time comparison to prevent timing attacks. ## Code Examples Register the raw Webhook route before any global JSON parser, or parse JSON only on regular routes. Verify headers and the original body before parsing the event. The examples below require your durable inbox adapter: uniquely save an event ID and pending payload before returning `2xx`; a worker must retry and fulfill idempotently. Invalid headers return a rejection, not an unhandled exception. Each retry uses a fresh sending timestamp; use the header, not `created_at`, for signature verification. ### Node.js ```javascript theme={null} const crypto = require('crypto'); function verifyWebhookSignature(payload, signature, timestamp, secret) { if (typeof secret !== 'string' || !secret) return false; if (typeof signature !== 'string' || !/^sha256=[0-9a-f]{64}$/.test(signature)) return false; if (typeof timestamp !== 'string' || !/^\d+$/.test(timestamp)) return false; const sentAt = Number(timestamp); if (!Number.isSafeInteger(sentAt) || Math.abs(Date.now() - sentAt) > 300000) return false; const data = `${timestamp}.${payload}`; const expected = 'sha256=' + crypto .createHmac('sha256', secret) .update(data) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(expected), Buffer.from(signature) ); } app.post('/webhooks/kyren', express.raw({ type: 'application/json' }), async (req, res) => { const signature = req.headers['x-kyren-signature']; const timestamp = req.headers['x-kyren-timestamp']; if (!Buffer.isBuffer(req.body)) return res.status(400).send('Raw JSON body required'); const payload = req.body.toString('utf8'); if (!verifyWebhookSignature(payload, signature, timestamp, process.env.KYREN_WEBHOOK_SECRET)) { return res.status(400).send('Invalid signature'); } let event; try { event = JSON.parse(payload); } catch { return res.status(400).send('Invalid JSON'); } if (!event || typeof event.id !== 'string' || !event.id || typeof event.type !== 'string' || !event.data) { return res.status(400).send('Invalid event'); } try { await webhookInbox.insertIfAbsent(event.id, event); } catch { return res.status(503).send('Retry later'); } res.status(200).send('OK'); } ); ``` ### Python ```python theme={null} import hmac import hashlib import time import re def verify_webhook_signature(payload: str, signature: str, timestamp: str, secret: str) -> bool: # Check timestamp tolerance (5 minutes) if not isinstance(secret, str) or not secret: return False if not isinstance(signature, str) or not re.fullmatch(r"sha256=[0-9a-f]{64}", signature): return False if not isinstance(timestamp, str) or not re.fullmatch(r"[0-9]{1,16}", timestamp): return False if int(timestamp) > 9007199254740991: return False current_time = int(time.time() * 1000) if abs(current_time - int(timestamp)) > 300000: return False # Compute expected signature data = f"{timestamp}.{payload}" expected = "sha256=" + hmac.new( secret.encode("utf-8"), data.encode("utf-8"), hashlib.sha256 ).hexdigest() # Constant-time comparison return hmac.compare_digest(expected, signature) # Usage in Flask from flask import Flask, request app = Flask(__name__) @app.route("/webhooks/kyren", methods=["POST"]) def webhook(): payload = request.get_data(as_text=True) signature = request.headers.get("X-Kyren-Signature", "") timestamp = request.headers.get("X-Kyren-Timestamp", "") if not verify_webhook_signature(payload, signature, timestamp, WEBHOOK_SECRET): return "Invalid signature", 400 event = request.get_json() if not isinstance(event, dict) or not isinstance(event.get("id"), str) or not event["id"]: return "Invalid event", 400 try: webhook_inbox.insert_if_absent(event["id"], event) except Exception: return "Retry later", 503 return "OK", 200 ``` ### Go ```go theme={null} package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" "io" "encoding/json" "math" "net/http" "strconv" "regexp" "time" ) func verifyWebhookSignature(payload, signature, timestamp, secret string) bool { if secret == "" || !regexp.MustCompile("^sha256=[0-9a-f]{64}$").MatchString(signature) || !regexp.MustCompile("^[0-9]+$").MatchString(timestamp) { return false } // Check timestamp tolerance (5 minutes) ts, err := strconv.ParseInt(timestamp, 10, 64) if err != nil || ts > 9007199254740991 { return false } currentTime := time.Now().UnixMilli() if math.Abs(float64(currentTime-ts)) > 300000 { return false } // Compute expected signature data := fmt.Sprintf("%s.%s", timestamp, payload) mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte(data)) expected := "sha256=" + hex.EncodeToString(mac.Sum(nil)) // Constant-time comparison return hmac.Equal([]byte(expected), []byte(signature)) } func webhookHandler(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, "Invalid body", http.StatusBadRequest) return } payload := string(body) signature := r.Header.Get("X-Kyren-Signature") timestamp := r.Header.Get("X-Kyren-Timestamp") if !verifyWebhookSignature(payload, signature, timestamp, webhookSecret) { http.Error(w, "Invalid signature", http.StatusBadRequest) return } var event struct { ID string `json:"id"` } if json.Unmarshal(body, &event) != nil || event.ID == "" { http.Error(w, "Invalid event", http.StatusBadRequest) return } if err := persistWebhookIfAbsent(event.ID, body); err != nil { http.Error(w, "Retry later", http.StatusServiceUnavailable) return } w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) } ``` > [!WARNING] > > **Important security considerations:** > > * Always verify signatures before processing events > * Use constant-time comparison functions to prevent timing attacks > * Reject requests with timestamps older than 5 minutes (300000 ms) to prevent replay attacks > * Use the raw request body for signature verification (before JSON parsing) # List balance transactions Source: https://docs.kyrenpay.com/api-reference/balance/list-balance-transactions /openapi.yaml get /v1/balance/transactions Returns a paginated list of balance transactions showing all changes to your account balance. # Retrieve account balance Source: https://docs.kyrenpay.com/api-reference/balance/retrieve-account-balance /openapi.yaml get /v1/balance Returns the current balance of your merchant account. # Create a checkout session Source: https://docs.kyrenpay.com/api-reference/checkouts/create-a-checkout-session /openapi.yaml post /v1/checkouts Creates a new checkout session for a product. Returns a URL where you can redirect your customer to complete the payment. Checkout sessions expire after 24 hours. Amount and currency come from the active product; per-session price, currency and quantity overrides are not supported. Hosted checkout must be enabled for the merchant. Persist the session against your business order and reuse it on repeated purchase attempts. Creation has no idempotency-key support: reconcile an uncertain creation result before retrying. Configure the merchant Webhook URL and Secret before payment. Use the returned data.url directly; browser success/cancel redirects are not payment confirmation. # Retrieve a checkout session Source: https://docs.kyrenpay.com/api-reference/checkouts/retrieve-a-checkout-session /openapi.yaml get /v1/checkouts/{id} Retrieves a session belonging to the authenticated merchant. OPEN is awaiting payment, COMPLETE indicates completion and exposes the associated successful orderId, and EXPIRED indicates session expiry. orderId is omitted until a successful order is associated. For payment reconciliation, retrieve that order and use the same idempotent fulfillment transaction as Webhooks. Session expiry is not evidence that an existing payment attempt failed. # Get current merchant services agreement Source: https://docs.kyrenpay.com/api-reference/config/get-current-merchant-services-agreement /openapi.yaml get /v1/config/legal/merchant-services-agreement Returns the current rendered agreement, its version, effective date, hashes, and public URL. Retrieve it without an API key. Complete acceptance in the merchant dashboard; downloading this document does not sign it or change the account's agreement status. # Get historical merchant services agreement Source: https://docs.kyrenpay.com/api-reference/config/get-historical-merchant-services-agreement /openapi.yaml get /v1/config/legal/merchant-services-agreement/{version} Returns the agreement for an explicit version and effective date. Reading a historical document does not complete acceptance of the current agreement. # Get legal configuration Source: https://docs.kyrenpay.com/api-reference/config/get-legal-configuration /openapi.yaml get /v1/config/legal Returns the current legal terms version and public document URLs. Reading these documents does not record merchant agreement acceptance. # Get settlement configuration Source: https://docs.kyrenpay.com/api-reference/config/get-settlement-configuration /openapi.yaml get /v1/config/settlement Returns the platform-wide settlement period in business days. Individual orders may use their channel's period captured at creation. Use order `settleDateTime` for the expected eligibility time and `settledAt` for actual settlement. This configuration does not guarantee payout timing. # Get supported currencies Source: https://docs.kyrenpay.com/api-reference/config/get-supported-currencies /openapi.yaml get /v1/config/currencies Returns the list of currencies supported by the platform and the default currency. Use this when creating products or configuring pricing to ensure you use a supported currency. # api.php (order query/refund compatibility endpoint) Source: https://docs.kyrenpay.com/api-reference/epay-compatibility/apiphp-order-queryrefund-compatibility-endpoint /openapi.yaml post /epay/api.php Executes compatibility operations with `act`. - `act=order`: query order status/result. - `act=refund`: submit a refund for an eligible Epay-source order. Paydify 订单仍通过 `act=order` 查询本地权威状态,`type=crypto`,`money` 保持原商品计价金额。 `code=1` 表示请求成功;只有本地 `PAID/SETTLED` 对应 `status=1`,其余为 `0`。 Paydify 经上游验签查询确认后沿用易支付成功通知;浏览器回跳不是付款证据。 本次 Paydify 接入不新增退款能力,不能由通用 `act=refund` 推断该渠道支持退款。 This endpoint also accepts GET with the same parameters. # mapi.php (direct create payment compatibility endpoint) Source: https://docs.kyrenpay.com/api-reference/epay-compatibility/mapiphp-direct-create-payment-compatibility-endpoint /openapi.yaml post /epay/mapi.php Creates (or reuses) an order directly and returns Epay-style response fields. For QR-style channels, response includes `qrcode` and `img`. For redirect-style channels, response includes `payurl`. Paydify:商户一次性加密货币通道绑定 Paydify 时使用 `type=crypto`,沿用 MD5 签名。 返回 `code=1/trade_no/out_trade_no/payurl`,其中 `payurl` 指向 KyrenPay 本地支付页;不返回上游 `qrcode/img`。 买家选择 App / 网络并确认有效 USDT 报价后才创建上游支付;不新增商户必填参数,目前不支持 USDC。 `money/money_type` 表示原商品计价金额,不是应付 USDT 数量;入口 `code=1` 不代表已付款。 同一商户 `out_trade_no` 重试必须保持金额、币种和支付方式一致,不能用重建订单处理未知支付结果。 目标环境须已部署且渠道已开通;文档不替代 Sandbox 真付验收。 Signature algorithm: 1. Remove `sign` and `sign_type`, and drop empty values. 2. Sort parameters by key in ascending order. 3. Join as `k=v` with `&`, append merchant API key. 4. MD5 the final string and compare in lowercase. # submit.php (redirect checkout compatibility endpoint) Source: https://docs.kyrenpay.com/api-reference/epay-compatibility/submitphp-redirect-checkout-compatibility-endpoint /openapi.yaml post /epay/submit.php Creates (or reuses) an Epay-compatible payment and returns HTTP 302 redirect to the hosted payment page. This endpoint also accepts GET with the same parameters. Paydify:商户一次性加密货币通道绑定 Paydify 时使用 `type=crypto`(不是 `paydify`)。 返回 302 到 KyrenPay 本地 `/epay/redirect/{orderId}`,入口受理时不创建上游支付。 买家在本地页选择 App / 网络并确认 USDT 报价后,才创建上游支付和展示二维码。 无需商户提交 App、网络或 Paydify 专用 `channel_param`。目标环境须已部署且渠道已开通。 Signature algorithm: 1. Remove `sign` and `sign_type`, and drop empty values. 2. Sort parameters by key in ascending order. 3. Join as `k=v` with `&`, append merchant API key. 4. MD5 the final string and compare in lowercase. # Export orders as CSV Source: https://docs.kyrenpay.com/api-reference/orders/export-orders-as-csv /openapi.yaml get /v1/orders/export Exports orders within the specified date range as a CSV file. Use Unix timestamps (milliseconds) for startDate and endDate. # List all orders Source: https://docs.kyrenpay.com/api-reference/orders/list-all-orders /openapi.yaml get /v1/orders Returns a paginated list of your orders. An order may exist before payment completes; use its status to decide whether to fulfill. # Retrieve an order Source: https://docs.kyrenpay.com/api-reference/orders/retrieve-an-order /openapi.yaml get /v1/orders/{id} Retrieves merchant-visible order details, including original and payable amounts, fee sharing, refund status, and rolling reserve information. # Archive a product Source: https://docs.kyrenpay.com/api-reference/products/archive-a-product /openapi.yaml delete /v1/products/{id} Archives a product. Archived products cannot be used to create new checkout sessions. # Create a product Source: https://docs.kyrenpay.com/api-reference/products/create-a-product /openapi.yaml post /v1/products Creates a new product. Products represent the goods or services you sell. # List all products Source: https://docs.kyrenpay.com/api-reference/products/list-all-products /openapi.yaml get /v1/products Returns a paginated list of your products. # Retrieve a product Source: https://docs.kyrenpay.com/api-reference/products/retrieve-a-product /openapi.yaml get /v1/products/{id} Retrieves the details of an existing product. # Update a product Source: https://docs.kyrenpay.com/api-reference/products/update-a-product /openapi.yaml patch /v1/products/{id} Updates an existing product. Only the provided fields will be updated. # Create a refund Source: https://docs.kyrenpay.com/api-reference/refunds/create-a-refund /openapi.yaml post /v1/orders/{orderId}/refunds Creates a full or partial refund for an eligible paid order created through the native KyrenPay API. Epay-source orders must be refunded through the Epay compatibility API. # Retrieve a refund Source: https://docs.kyrenpay.com/api-reference/refunds/retrieve-a-refund /openapi.yaml get /v1/refunds/{refundId} Retrieves a refund created for one of your orders.