# NihaoPay API Documentation (en) - full text Base URL: https://api.nihaopay.com/v1.2 Index: https://docs.nihaopay.com/llms.txt # Version > **API Version** ```shell /v1.2 ``` As with all of our products and services, our API is constantly being improved to better suit our customers’ needs. To help our customers track changes, we include versions in our API. We are currently on Version 1.2 (`v1.2`). To specify a version, simply add `/v1.2` namespace to the base endpoint before the resource namespace. For example, to use Version 1.2, the full endpoint for the transactions resource would be: `https://api.nihaopay.com/v1.2/transactions` # Authentication > **Sample Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions \ -H "Authorization: Bearer " ``` > Replace \ with your bearer token generated in the [TMS](https://tms.nihaopay.com). See [Authentication](#authentication) for more information. Each request must be made over HTTPS and authenticated using your merchant credentials. Authentication is handled through the Authorization header with a Bearer token. You can view your bearer token in [TMS](https://tms.nihaopay.com) by logging in and going to Settings -> Certificate. Header | Description ------ | ----------- **Authorization**
Required|Set authentication type as `Bearer` with a token obtained from the [TMS](https://tms.nihaopay.com). If you believe either your merchant ID, secret key, or bearer token have been compromised, please regenerate your secret key in the TMS. Once you have a new secret key, a bearer token will be automatically regenerated. Please allow 15 minutes for the new bearer token to propagate through the system. # API Description ## Payment Mode NihaoPay supports five payment models: SecurePay, CardPay, In-APP payment, Show QRcode and Scan QRcode.

SecurePay

In Securepay, users will be redirected to the payment tunnel and finish rest of payment steps in the official payment page.

APP Payment

In-APP Payment will ask merchants to call the selected payment model while users are checking out.

Show QRcode

Our API will return a QRcode URL containing information merchant requested. Merchants will be able to show this URL on mobiles or PC web browsers, thereby enabling users to scan the QR code and pay.

Scan QRcode

In the Scan QRcode, merchants are able to sacn user's QRcode to finish the transaction. ### For the following products, please refer to [MuskPay API Documentation](https://docs.muskpay.io/)

CardPay

In CardPay, we require merchants' websites to have PCI certification. Merchants will collect users' credit card information and send request to API to finish the order. ## How to use || AliPay| WechatPay | UnionPay | |------------------------------|--------------------|-----------------------|---------------- | |PC Browser
`terminal=ONLINE`| [Standard SecurePay](./securepay#create-a-standard-securepay) | [Standard SecurePay](./securepay#create-a-standard-securepay)
[Generate QRcode](./securepay#generate-a-payment-qrcode) | [SecurePay](./securepay#create-a-standard-securepay)
[CardPay](https://docs.muskpay.io/) | |Mobile Browser
`terminal=WAP`| [Standard SecurePay](./securepay#create-a-standard-securepay) | [Wechat H5 payment](./securepay#create-a-standard-securepay)
Please contact BD to enable this feature | [SecurePay](./securepay#create-a-standard-securepay)
[CardPay](https://docs.muskpay.io/) | |Wechat Browser
`terminal=WAP`| NA | [Standard SecurePay](./securepay#create-a-standard-securepay)
| [SecurePay](./securepay#create-a-standard-securepay)
[CardPay](https://docs.muskpay.io/) | |In-APP|[In-APP Payment](./securepay#in-app-payment)| [In-APP Payment](./securepay#in-app-payment) |[In-APP Payment](./securepay#in-app-payment)| |WeChat Mini-Program | NA| [Mini-Program Payment](./securepay#wechat-mini-program-payment) | NA | |In-Store
Have Scanner|[Scan QRcode](./offline#scan-qrcode)| [Scan QRcode](./offline#scan-qrcode) |[Scan QRcode](./offline#scan-qrcode)
U.S. merchants only| |In-Store|[Show QRcode](./offline#show-qrcode)
[Static QRcode](./offline#static-omni-channel-qrcode)| [Show QRcode](./offline#show-qrcode)
[Static QRcode](./offline#static-omni-channel-qrcode) | [Show QRcode](./offline#show-qrcode)
U.S. merchants only | ## Parameters Description ### 1.Amount Amount as a positive integer of the minor unit of the currency. For Example, $10.50 in USD would be 1050, ¥100 in JPY would be 100. ### 2.Currency Currently, NihaoPay supported currencies: | Currency | Currency Code | Minor unit | | ----------------- | --------------- | ----------- | | US Dollar | USD | 2 | | Japanese Yen | JPY | 0 | | Hong Kong Dollar | HKD | 2 | | Euro | EUR | 2 | | Canadian Dollar | CAD | 2 | | Pound Sterling | GBP | 2 | | Singapore Dollar | SGD | 2 | | Australian Dollar | AUD | 2 | ### 3. RMB Amount Use this parameter to replace `amount` if merchants wish to price their product in RMB. NihaoPay will return an amount in merchant’s settlement currency when payment is successful. | Request | Response | Description | | ------------------------------ | -------------------- | ----------------------- | | `rmb_amount=10000`
`currency=USD`| `rmb_amount=10000`
`amount=1441`
`currency=USD` | Order amount is 100.00 Chinese Yuan
Settlement amount is 14.41 US Dollars| | `amount=10000`
`currency=USD`| `amount=10000`
`currency=USD` | Order amount and Settlement amount
are 100.00 US Dollars | ### 4.Reference An alphanumeric string up to 30 characters that must be unique to each of your transactions. ### 5. Order Product Information > **Form request parameter example** ```shell items[0][name]=T-Shirt&items[0][unitAmount]=500&items[0][quantity]=1&items[1][name]=Hat&items[1][unitAmount]=500&items[1][quantity]=2 ``` `items` is an array, each element represents a product. Each element in the array contains the following fields: | Field name | Description | | ---------- | ----------- | | **items** | **Product information list**, containing one or more product objects. | | **items[n].name**
`Required` | **Product name**. | | **items[n].unitAmount**
`Required` | **Product unit price**, corresponding to the order currency. The amount is the smallest unit in the corresponding currency. See [Parameters Description](#parameters-description) for details. | | **items[n].quantity**
`Required` | **Quantity of goods**. | The total amount of goods should be equal to the total amount of the order: `amount = (items[0].unitAmount * items[0].quantity + items[1].unitAmount * items[1].quantity + ...)` ### 6.Vendor Currently, NihaoPay accepts three vendors are `unionpay`, `alipay`, and `wechatpay`. ### 7. Callback URL `callback_url` and `ipn_url` must be accessible on the Internet and can't be intranet address (for example `localhost`) or intranet IP. By default, only successful payments will redirect to `callback_url`. If merchants want other payment statuses to trigger redirection, please add the `accept` parameter to the `callback_url`, for example `callback_url?accept=pending,failure` indicates that payment failure or cancellation will also redirect to `callback_url`. ### 8.Terminal Currently, acceptable values are `ONLINE` and `WAP`. > **System Reserve** ```shell sys_reserve = {"vendor_id":"4200000117201806013734875340"} ``` ### 9. System Reserved sys_reserve, NihaoPay system reserved, used for return vendor's transaction id or customer's info. Currently, includes: Key | Value -------- | ----------- **vendor_id**| Vendor's transaction id, usually showed on customer's payment receipt. ## Instant Payment Notification ### Asynchronous Response After payment completed, NihaoPay will return a transaction object to `ipn_url` using the `POST` method. **Whenever possible, transaction data should be recorded from the IPN URL instead of the callback URL.** When executing the IPN notification, please note: * `ipn_url` must be accessible on the Internet and can't be intranet address (for example `localhost`) or intranet IP * The IPN notification may arrive ahead of browser callback. * The duplicated IPN notifications. * NihaoPay returns to `ipn_url` using the `POST` method. * After the program is executed, The merchant should return HTTP status code 200 upon successful processing. If not, NihaoPay server will keep re-sending notification. * Generally, there will be 8 notifications within 2 hours (**Frequency: 0m,1m,2m,4m,8m,20m,30m**). * After the program is executed, there should not be any redirecting operation on the page. > **Asynchronous Response** ```shell id = 20170519103602011338 amount = 2 currency = USD rmb_amount = 12 reference = 20170519103456437807 sys_reserve = {"vendor_id":"4200000117201806013734875340"} status = success time = 2017-05-19T10:36:32Z note = null verify_sign = 46072c81e3c6140d6bc92655196b247f ``` ### Asynchronous Response message Property | Description ------- | ----------- **id**
`string` | Transaction ID. **status**
`string` | Transaction status. In SecurePay scenario, only `success`. **amount**
`int` | The settlement amount uses foreign currency. **rmb_amount**
`int` | Payment Renminbi Amount. Same with the Request, If the request is null, payment amount will be returned. **currency**
`string` | The 3-letter currency code. **time**
`string` | Timestamp of the transaction in UTC. Ex: `2015-01-01T01:01:00Z` is Jan 1, 2015 1:01:00 UTC. **reference**
`string` | AlphaNumeric string set in request to correspond transaction ID with your original transaction request. **note**
`string` | If set in request, your transaction note to self. Else if not set, this will be `null`. **sys_reserve**
`json` | NihaoPay system reservation, it's json string, See [Parameters Description](#parameters-description). **verify_sign**
`string` | Signature value. > **Sign method** ```shell verify_sign = MD5(key1=value1&key2=value2&...&keyn=valuen&MD5(TOKEN)) ``` ### Verify signature When the asynchronous notification returns, NihaoPay will do the MD5 signature on the return message. After the merchant receives asynchronous notification, it will verify that the returned information is tampered with by the signature method. Signature method: A. The connection method between the critical message pair and the cooperative key message pair is: * The indication method for a single pair is key = value. If the value corresponding to the key is null, not include the key. * The connection method for multiple pairs is key1=value1&key2=&key3=value3. Sort pairs in the signature in an ascending order in accordance with key values. * The connection method of cooperative key messages is key1=value1&key2=&key3=value3&MD5(Token), The token, after MD5 calculation, is connected to the end of the pair. B. Signature method verify_sign = MD5(key1=value1&key2=&key3=value3...&keyn=value&MD5(Token)) Note: * NihaoPay uses UTF-8 as charset. * Parameters without a value can be excluded from sign; * The MD5's output is lowercase when comparing signatures, please ignore case. # SecurePay ## Create a Standard SecurePay > **Definition** ```shell POST https://api.nihaopay.com/v1.2/transactions/securepay ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/securepay \ -H "Authorization: Bearer " \ -d rmb_amount=100 \ -d currency="USD" \ -d vendor="alipay" \ -d reference="20171023191505118594" \ -d items[0].name="T-Shirt Test" \ -d items[0].unitAmount=100 \ -d items[0].quantity=1 \ -d ipn_url="https://demo.nihaopay.com/ipn" \ -d callback_url="https://demo.nihaopay.com/callback" ``` ```shell $ curl https://api.nihaopay.com/v1.2/transactions/securepay \ -H "Authorization: Bearer " \ -d rmb_amount=100 \ -d currency="USD" \ -d vendor="wechatpay" \ -d reference="20171023191505118594" \ -d items[0].name="T-Shirt Test" \ -d items[0].unitAmount=100 \ -d items[0].quantity=1 \ -d ipn_url="https://demo.nihaopay.com/ipn" \ -d in_wechat="false" \ -d callback_url="https://demo.nihaopay.com/callback" ``` > **json response example 1** ```json { "url": "https://openapi.alipay.com/gateway.do?app_id=2019031263534265" } ``` > **json response example 2** ```json { "form": { "actionUrl": "https://www.nihaopay.com/", "method": "POST", "target": "_self", "params": { "bizType": "000201", "backUrl": "https://bgw.nihaopay.com/payBackResp/44e4af32d6494c71aaafe2eaf6c05910", "orderId": "u20230827102153QvCEZp", "txnSubType": "01" } } } ``` SecurePay transactions will redirect users to the vendor’s payment page, where users can enter payment information. Upon successful transaction, users will be redirected to the callback URL. These redirects are accomplished through the use of a JavaScript enabled form. Due to the nature of redirects and users being able to close their browsers before the redirect can happen, an instant payment notification (IPN) URL is used to provide transaction data. A reference string is also required to keep track of transactions as the Transaction object will not respond directly to the request but rather in the asynchronous call to your IPN URL. When you receive the Transaction object, you will need to match the reference against your records in order to determine which transaction IDs correspond to which requests. ### Request Property | Description -------- | ----------- **currency**
`Required`| The 3-letter currency code. See [Parameters Description](./apirule#parameters-description) for acceptable currencie. **amount**
`Conditional` | Amount as a positive integer of the minor unit of the currency. If amount is not null, it means the transaction uses foreign currency. See [Parameters Description](./apirule#parameters-description). **rmb_amount**
`Conditional` | Amount as a positive integer of the minor unit of the currency. Use this parameter to replace amount if merchant wish to price their product in RMB. If amount is used, rmb_amount should not be set. They are mutual exclusive. See [Parameters Description](./apirule#parameters-description). **vendor**
`Required`| Transaction vendor. Currently, acceptable vendors are `unionpay`, `alipay`, `wechatpay`, and PayPal `paypal`. **payment_source**
`Optional`| PayPal payment source. Defaults to the PayPal wallet. Pass `crypto` for PayPal Crypto payments. Pass `ACDC` for PayPal card payments when the merchant creates an order using the PayPal JavaScript SDK [Reference code](https://docs.nihaopay.com/api/v1.2/paypal-acdc.html). **given_name**
`Conditional` | Payer's given name. Required when `vendor=paypal` and `payment_source=crypto`. **surname**
`Conditional` | Payer's surname. Required when `vendor=paypal` and `payment_source=crypto`. **reference**
`Required` | An alphanumeric string up to 30 characters that must be unique to each of your transactions. This allows you to keep track of transactions when data comes back through IPN and Callback URLs. See [Parameters Description](./apirule#parameters-description). **items**
`Conditional` | Order product item list, see [Parameters Description](./apirule#parameters-description). **ipn_url**
`Required` | Instant Payment Notification URL. Called by the API to update you on transaction information. This is where the response goes to. See [Instant Payment Notification](./apirule#instant-payment-notification). **callback_url**
`Required` | URL the browser will be redirected to upon completing the transaction. **description**
`Optional`| Arbitrary string that you can set to be displayed on the card charge. **note**
`Optional`| Arbitrary string as note to self regarding the transaction. **terminal**
`Optional`
Default: ONLINE | Specifies whether payment is submitted on desktop (`ONLINE`) or mobile (`WAP`). **timeout**
`Optional`
Default: 120 | Specifies amount of minutes card holders have before payment page times out. Once the page times out without a successful payment, the transaction is automatically closed. Acceptable values are `1 - 1440`. **in_wechat**
`Optional`
| When the current payment scenario is WeChat built-in browser, pass `true`, otherwise pass `false` and it is valid only when vendor=`wechatpay`. when in_wechat=`false`,if you have enabled WeChat H5 payment,use [WeChat H5 payment](https://pay.weixin.qq.com/doc/global/v3/en/4012356554) otherwise downgrade For [scanning code](https://pay.weixin.qq.com/doc/global/v3/en/4012356478),use [JSAPI to pay](https://pay.weixin.qq.com/doc/global/v3/en/4012356496) when in_wechat=`true`. **response_format**
`Optional`
Default: HTML | Specifies whether the returned data is in (`JSON`) format or (`HTML`) format. ### JSON response (when `response_format` as `JSON`) Property | Description -------- | ----------- **id**
`string` | Transaction ID. **url**
`Optional`| Redirect url, when the interface returns url, the caller can directly redirect to this url after getting the url. **orderId**
`Optional` | PayPal Order Id, used when the merchant creates an order using the PayPal JavaScript SDK [Reference code](https://docs.nihaopay.com/api/v1.2/paypal-acdc.html). **form**
`Optional`| form form object, and url are mutually exclusive, when the url does not exist, the form object exists. **form.actionUrl**
`Required`| The action attribute of the form form. **form.method**
`Required` | The method attribute of the form form **form.target**
`Required` | The target attribute of the form form **form.params**
`Required`| The parameters of the form form, in map format, key is the parameter name, and value is the parameter value. ### Synchronous HTML Response 1. HTML format response >The API returns a synchronous message to the merchant. The message is a form that should be displayed in the browser. The form will submit automatically to the vendor's payment portal, redirecting the user to complete the transaction. 2. Response in JSON format (when `response_format` as `JSON`) >The returned json data returns a form object or url (not both). If the url is returned, the caller can directly redirect to this url after getting the url. If the return is a form object, the caller needs to use the fields in the form object to construct a form form by itself, and write the form form to In the current webpage request, the page will jump to the payment page after submission. ### PayPal Crypto Payment PayPal Crypto uses the standard SecurePay endpoint. When creating an order, pass `vendor=paypal`, `payment_source=crypto`, `given_name`, and `surname`. Redirect the browser to the returned `url` so the buyer can complete payment on the PayPal Crypto page. Use the browser `callback_url` and server-side `ipn_url` to determine the payment result. > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/securepay \ -H "Authorization: Bearer " \ -d amount=100 \ -d currency="USD" \ -d vendor="paypal" \ -d payment_source="crypto" \ -d given_name="Jane" \ -d surname="Doe" \ -d reference="paypal-crypto-001" \ -d ipn_url="https://merchant.example.com/payment-ipn" \ -d callback_url="https://merchant.example.com/payment-callback" \ -d response_format="JSON" ``` > **Asynchronous Response** ```shell id = 20170519103602011338 amount = 2 currency = USD rmb_amount = 12 reference = 20170519103456437807 sys_reserve = {"vendor_id":"4200000117201806013734875340"} status = success time = 2017-05-19T10:36:32Z note = null verify_sign = 46072c81e3c6140d6bc92655196b247f ``` ### Asynchronous Response After completion of a securepay, API will return a transaction object to `callback_url` using the `GET` method, returns to `ipn_url` using the `POST` method. Transaction IDs can be used to retrieve details, request cancellations, and create refunds. **Whenever possible, transaction data should be recorded from the IPN URL instead of the callback URL.** Property | Description ------- | ----------- **id**
`string` | Transaction ID. **status**
`string` | Transaction status. In SecurePay scenario, only `success`. **amount**
`int` | The settlement amount uses foreign currency. **rmb_amount**
`int` | Payment Renminbi Amount. Same with the Request, If the request is null, payment amount will be returned. **currency**
`string` | The 3-letter currency code. **time**
`string` | Timestamp of the transaction in UTC. Ex: `2015-01-01T01:01:00Z` is Jan 1, 2015 1:01:00 UTC. **reference**
`string` | AlphaNumeric string set in request to correspond transaction ID with your original transaction request. **note**
`string` | If set in request, your transaction note to self. Else if not set, this will be `null`. **sys_reserve**
`json` | NihaoPay system reservation, it's json string, See [Parameters Description](./apirule#parameters-description). **verify_sign**
`string` | Signature value. ## Generate a Payment QRcode > **Definition** ```shell POST https://api.nihaopay.com/v1.2/transactions/qrcode ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/qrcode \ -H "Authorization: Bearer " \ -d amount=100 \ -d vendor="wechatpay" \ -d currency="USD" \ -d reference="jkh25jh1348fd89sg" \ -d ipn_url="http://website.com/ipn" ``` Merchant's backend system requests payment QRcode API in order to generate an advance transaction and gets code_url. Merchant's backend creates a QR Code based on `code_url` which can be displayed on website or printed on the checkout bill. The cardholder opens "Scan" in WeChat or UnionPay QuickPass, scans the QR Code, enters his or her payment password and completes the transaction. Upon transaction completion, the API will return asynchronous message to the IPN URL. Merchant can request [Look up a transaction](./manage#look-up-a-transaction) if no message is received. **The asynchronous message returned to IPN URL is the same with SecurePay.** ### Request Property | Description -------- | ----------- **currency**
`Required`| The 3-letter currency code. See [Parameters Description](./apirule#parameters-description) for acceptable currencie. **amount**
`Conditional` | Amount as a positive integer of the minor unit of the currency. If amount is not null, it means the transaction uses foreign currency. See [Parameters Description](./apirule#parameters-description). **rmb_amount**
`Conditional` | Amount as a positive integer of the minor unit of the currency. Use this parameter to replace amount if merchant wish to price their product in RMB. If amount is used, rmb_amount should not be set. They are mutual exclusive. See [Parameters Description](./apirule#parameters-description). **vendor**
`Required`| Transaction vendor. Currently, acceptable vendors are `unionpay` and `wechatpay`. **reference**
`Required` | An alphanumeric string up to 30 characters that must be unique to each of your transactions. This allows you to keep track of transactions when data comes back through IPN and Callback URLs. **items**
`Conditional` | Order product item list, see [Parameters Description](./apirule#parameters-description). **ipn_url**
`Required` | Instant Payment Notification URL. Called by the API to update you on transaction information. This is where the response goes to. See [Instant Payment Notification](./apirule#instant-payment-notification). **timeout**
`Optional`
Default: 120 | Specifies amount of minutes card holders have before payment page times out. Once the page times out without a successful payment, the transaction is automatically cancelled. Acceptable values are `1 - 1440`. **description**
`Optional` | Arbitrary string that you can set to be displayed on the card charge. **note**
`Optional`| Arbitrary string as note to self regarding the transaction. > **Response** ```json { "id": "20160829075820003759", "code_url": "weixin://wxpay/bizpayurl?pr=1dVyJZF", "timeout": 90, "amount": 100, "currency": "USD", "reference": "jkh25jh1348fd89sg", "time": "2017-05-19T09:38:28Z" } ``` ### Response Returns a QRcode object. Property | Description ------- | ----------- **code_url**
`string` | The string of QR code url. **id**
`string` | Transaction ID. **amount**
`int` | Amount of the transaction in the minor unit of the currency. For example, cents in USD. **currency**
`string` | The 3-letter currency code. **timeout**
`int`
| Within the specified minutes, code url will time out. If you did not provide this, default value will be returned to you. **reference**
`string` | AlphaNumeric string set in request to correspond transaction ID with your original transaction request. **time**
`string` | Timestamp of the transaction in UTC. Ex: `2015-01-01T01:01:00Z` is Jan 1, 2015 1:01:00 UTC. ## In-App Payment > **Definition** ```shell POST https://api.nihaopay.com/v1.2/transactions/apppay ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/apppay \ -H "Authorization: Bearer " \ -d amount=100 \ -d currency="USD" \ -d vendor="alipay" \ -d reference="alipay20170503000300" \ -d ipn_url="http://website.com/ipn" ``` For more information about In-App payment, see NihaoPay [IOS demo](https://github.com/nihaopay/NihaoPay-IOSDemo) or [Andriod demo](https://github.com/nihaopay/nihaopay-as-demo) ### Request Property | Description -------- | ----------- **currency**
`Required`| The 3-letter currency code. See [Parameters Description](./apirule#parameters-description) for acceptable currencie. **amount**
`Conditional` | Amount as a positive integer of the minor unit of the currency. If amount is not null, it means the transaction uses foreign currency. See [Parameters Description](./apirule#parameters-description). **rmb_amount**
`Conditional` | Amount as a positive integer of the minor unit of the currency. Use this parameter to replace amount if merchant wish to price their product in RMB. If amount is used, rmb_amount should not be set. They are mutual exclusive. See [Parameters Description](./apirule#parameters-description). **reference**
`Required` | An alphanumeric string up to 30 characters that must be unique to each of your transactions. This allows you to keep track of transactions when data comes back through IPN and Callback URLs. **items**
`Conditional` | Order product item list, see [Parameters Description](./apirule#parameters-description). **vendor**
`Required`| Transaction vendor. Currently, acceptable vendors are `alipay`,`wechatpay` and `unionpay`. **app_id**
`Conditional` | APPID approved by [WeChat Open Plarform](https://open.weixin.qq.com/). Required when vendor = `wechatpay` **ipn_url**
`Required` | Instant Payment Notification URL. Called by the API to update you on transaction information. This is where the response goes to. See [Instant Payment Notification](./apirule#instant-payment-notification). **description**
`Optional` | Arbitrary string that you can set to be displayed on the card charge. **note**
`Optional`| Arbitrary string as note to self regarding the transaction. **timeout**
`Optional`
Default: 120 | Specifies amount of minutes card holders have before payment page times out. Once the page times out without a successful payment, the transaction is automatically cancelled. Acceptable values are `1 - 1440`. **ostype**
`Required` | Specifies whether the payment page should be displayed on an Android phone (`ANDROID`) or an iphone (`IOS`). > **Response** ```json { "orderInfo": "orderinfo string.....", "redirectUrl": "https://wallet.com/xxx?xxx=xx....." } ``` ### Response > At the same time, only one of orderInfo and redirectUrl will be returned, and orderInfo is used first. Property | Description ------- | ----------- **orderInfo**
`string` | Used to call the vendor SDK if not empty,. For more information, see NihaoPay [IOS demo](https://github.com/nihaopay/NihaoPay-IOSDemo) or [Andriod demo](https://github.com/nihaopay/nihaopay-as-demo). If you need WeChatPay In-app, please contact us for help. **redirectUrl**
`string` | The payment URL that redirects users to a WAP or Web page in the browser or in the WebView,see NihaoPay [IOS demo](https://github.com/nihaopay/NihaoPay-IOSDemo) or [Andriod demo](https://github.com/nihaopay/nihaopay-as-demo). ## Alipay A+ > Wallet Support: AlipayHK,GCASH,DANA,KaKaoPay,TNG,TrueMoney > **Definition** ```shell POST https://api.nihaopay.com/v1.2/transactions/aplus ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/aplus \ -H "Authorization: Bearer " \ -d amount=100 \ -d currency="USD" \ -d reference="alipay20170503000300" \ -d ipn_url="http://website.com/ipn" \ -d callback_url="http://website.com/callback" ``` Property | Description -------- | ----------- **currency**
`Required`| The 3-letter currency code. See [Parameters Description](./apirule#parameters-description) for acceptable currencie. **amount**
`Conditional` | Amount as a positive integer of the minor unit of the currency. If amount is not null, it means the transaction uses foreign currency. See [Parameters Description](./apirule#parameters-description). **rmb_amount**
`Conditional` | Amount as a positive integer of the minor unit of the currency. Use this parameter to replace amount if merchant wish to price their product in RMB. If amount is used, rmb_amount should not be set. They are mutual exclusive. See [Parameters Description](./apirule#parameters-description). **reference**
`Required` | An alphanumeric string up to 30 characters that must be unique to each of your transactions. This allows you to keep track of transactions when data comes back through IPN and Callback URLs. See [Parameters Description](./apirule#parameters-description). **items**
`Conditional` | Order product item list, see [Parameters Description](./apirule#parameters-description). **ipn_url**
`Required` | Instant Payment Notification URL. Called by the API to update you on transaction information. This is where the response goes to. See [Instant Payment Notification](./apirule#instant-payment-notification). **callback_url**
`Conditional` | URL the browser will be redirected to upon completing the transaction, Required when terminal=`ONLINE` or terminal=`WAP`. **description**
`Optional`| Arbitrary string that you can set to be displayed on the card charge. **note**
`Optional`| Arbitrary string as note to self regarding the transaction. **terminal**
`Optional`
Default: ONLINE | Specifies whether payment is submitted on desktop (`ONLINE`) or mobile (`WAP`) or mobile application (`APP`) or mini program(`MICRO`). **timeout**
`Optional`
Default: 10 | Order timeout time, after NihaoPay receives the order request, if the customer fails to pay within the time specified by timeout (minutes), the order will be closed `1 - 10`. **ostype**
`Conditional` | Specifies whether the payment page should be displayed on an Android phone (`ANDROID`) or an iphone (`IOS`), Required when terminal=`WAP` or terminal=`APP` or terminal=`MICRO`. **wallet**
`Optional` | Default:`CONNECT_WALLET`, available options are `ALIPAY_CN`,`ALIPAY_HK`,`TRUEMONEY`,`TNG`,`GCASH`,`DANA`,`KAKAOPAY`,`CONNECT_WALLET`, `CONNECT_WALLET` means that all the available wallets will be displayed to the user, and the user can choose any wallet to pay. > **Response** ```json { "amount": 10, "timeout": 10, "currency": "USD", "reference": "1657808342862", "id": "20220714221903000379", "time": "2022-07-14T22:19:03Z", "redirectUrl": "https://alipay.com/connect.html?code=281666040098ZTL79hJiG7" } ``` ### Response Property | Description ------- | ----------- **amount**
`int` | Order amount. **timeout**
`int` | Order timeout time(minutes). **currency**
`string` | Order currency. **reference**
`string` | Your transactions id. **id**
`string` | Nihaopay transactions id. **time**
`string` | Order create time. **redirectUrl**
`string` | The payment URL that redirects users to a WAP or Web page in the browser. ## WeChat Mini-Program Payment ```shell POST https://api.nihaopay.com/v1.2/transactions/micropay ``` Please send the WeChat Mini-program APPID to our support team before development. Merchant can ask prePay request at the mini-program, and use the function [wx.requestpayment()](https://developers.weixin.qq.com/miniprogram/en/dev/api/payment/wx.requestPayment.html) to call WeChatPay if the variable of request is generated successfully. NihaoPay will send IPN announcement to the IPN_url of merchant as long as the order has been placed successfully. Following figures illustrates the development process. ![Mini Program Flow](/images/miniprogram-flow.png) > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/micropay \ -H "Authorization: Bearer " \ -d amount=100 \ -d currency="USD" \ -d reference="wechatpay20171109000300" \ -d ipn_url="http://website.com/ipn" \ -d open_id="oSC6Tw7--mfjTCpIr-72rWloA8TU" \ -d client_ip="180.167.25.154" ``` ### Request Property | Description -------- | ----------- **currency**
`Required`| The 3-letter currency code. See [Parameters Description](./apirule#parameters-description) for acceptable currencie. **amount**
`Conditional` | Amount as a positive integer of the minor unit of the currency. If amount is not null, it means the transaction uses foreign currency. See [Parameters Description](./apirule#parameters-description). **rmb_amount**
`Conditional` | Amount as a positive integer of the minor unit of the currency. Use this parameter to replace amount if merchant wish to price their product in RMB. If amount is used, rmb_amount should not be set. They are mutual exclusive. See [Parameters Description](./apirule#parameters-description). **reference**
`Required` | An alphanumeric string up to 30 characters that must be unique to each of your transactions. This allows you to keep track of transactions when data comes back through IPN and Callback URLs. **items**
`Conditional` | Order product item list, see [Parameters Description](./apirule#parameters-description). **app_id**
`Required` | WeChat Mini-Program APPID. **ipn_url**
`Required` | Instant Payment Notification URL. See [Instant Payment Notification](./apirule#instant-payment-notification). **client_ip**
`Required` | Customer IP **open_id**
`Required` | The openid for a WeChat user that mini programs obtained after a wx.login() call. For get openid in mini programs please see [here](https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html). **description**
`Optional`| Arbitrary string that you can set to be displayed on the card charge. **note**
`Optional` | Arbitrary string as note to self regarding the transaction. **timeout**
`Optional`
Default: 120 | Specifies amount of minutes card holders have before payment page times out. Once the page times out without a successful payment, the transaction is automatically cancelled. Acceptable values are `1 - 1440`. > **Success response** ```json { "timeStamp": "1510341967363", "nonceStr": "a611bda03d544b9f941393c48c2e517f", "wechatPackage": "prepay_id=wx201711110326070ccf2a7f060678638664", "signType": "MD5", "paySign": "09E5BE5B9D93080E3B7DD05C8F41049E" } ``` ### Response Property | Description ------- | ----------- **timeStamp**
`string` | Time Stamp **nonceStr**
`string` | Random string **wechatPackage**
`string` | Data package include prepay_id=**** **signType**
`string` | Signature type, default MD5 **paySign**
`string` | Signature ## PayPal ACDC Order Capture ```shell POST https://api.nihaopay.com/v1.2/transactions/paypal/capture/{transaction_id} ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/paypal/capture/{transaction_id} \ -H "Authorization: Bearer " \ ``` Merchants call this api to capture funds for PayPal ACDC orders, i.e., orders created using the PayPal Javascript SDK [Reference code](https://docs.nihaopay.com/api/v1.2/paypal-acdc.html). ### Request `transaction_id` as URL parameter. > **Success response** ```json { "paypal_order_id": "80J3567205747094K", "paypal_capture_id": "0CW443673C1190047", "id": "20251215131749104834", "status": "success" } ``` ### Response Property | Description ---------|----------- **id**
`string`| Original transaction id **paypal_order_id**
`string`| PayPal order id **paypal_capture_id**
`string`| PayPal transaction id **status**
`string`| Request result, including: success `success`, failure `failure` **processor_response_code**
`string`|Response code from PayPal or card org processor. # In-Store Payment ## Scan QRcode Face-to-face merchant may scan the QRcode or Barcode on customer's phone to get paid for an order instead of having the customer to pay by cash or card. Merchant can use scanning guns, mobile devices with app or mPOS terminals with camera for scanning. The figure illustrates the work flow of the Scan QRcode payment solution. ![Scan QRcode](/images/scanqrcode.png) ```shell POST https://api.nihaopay.com/v1.2/transactions/scanqrcode ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/scanqrcode \ -H "Authorization: Bearer " \ -d amount=100 \ -d currency="USD" \ -d vendor="alipay" \ -d reference="alipay201705030002" \ -d buyer_identity_code="288463639882104202" \ -d client_ip="184.167.25.158" \ -d note="alipay" \ -d description="Scan AliPay QrCode" ``` ### Request Property | Description -------- | ----------- **currency**
`Required`| The 3-letter currency code. Currently, acceptable currencies are `USD` and `JPY`. **amount**
`Required` | Amount as a positive integer of the minor unit of the currency. See [Parameters Description](./apirule#parameters-description). **vendor**
`Required`| Transaction vendor. Currently, acceptable vendors are `alipay` , `unionpay`and `wechatpay`. **reference**
`Required` | An alphanumeric string up to 30 characters that must be unique to each of your transactions. This allows you to keep track of transactions when data comes back through IPN and Callback URLs. See [Parameters Description](./apirule#parameters-description). **items**
`Conditional` | Order product item list, see [Parameters Description](./apirule#parameters-description). **buyer_identity_code**
`Required` | Identification of Customer's QRcode or barcode. **client_ip**
`Required` | Terminal IP, The IP of Merchant terminal device **description**
`Optional` | Arbitrary string that you can set to be displayed on the card charge. **note**
`Optional` | Arbitrary string as note to self regarding the transaction. > **Response** ```json { "amount": 12, "id": "20170519093105011337", "time": "2017-05-19T09:31:05Z", "status": "success", "sys_reserve": "{'vendor_id':'2018031421001004970502155891'}", "note": "123456789", "reference": "alipay201705030004", "currency": "USD" } ``` ### Response Returns a transaction object. Property | Description ------- | ----------- **id**
`string` | Transaction ID. **status**
`string` | Transaction status. Either `success`, `failure`, or `pending`. **sys_reserve**
`string` | NihaoPay reserved. json format. If status is success, return verdor's transaction id. **amount**
`int` | Amount of the transaction in the minor unit of the currency. For example, cents in USD. **currency**
`string` | The 3-letter currency code. **time**
`string` | Timestamp of the transaction in UTC. Ex: `2015-01-01T01:01:00Z` is Jan 1, 2015 1:01:00 UTC **reference**
`string` | A reference number to track each transactions. If you did not provide this, a reference will be generated and returned to you. **note**
`string` | If set in request, your transaction note to self. Else if not set, this will be null. ## Show QRcode Merchant's backend system request show QRcode API in order to generate an advance transaction and gets code_url. Merchant's backend creates a QR Code based on `code_url` and show on wetsite or other devices. The customer scans the QR Code, enters their payment password and completes the transaction. Upon completing the transaction, the API will return asynchronous message to the IPN url. Merchant can request [Look up a transaction](./manage#look-up-a-transaction) if no message is received. The figure illustrates the work flow of the Show QRcode payment solution. ![Show QRcode](/images/showqrcode.png) **The asynchronous message return to IPN URL is same with SecurePay.** ```shell POST https://api.nihaopay.com/v1.2/transactions/showqrcode ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/showqrcode \ -H "Authorization: Bearer " \ -d amount=100 \ -d currency="USD" \ -d vendor="alipay" \ -d reference="jkh25jh1348fd89sg" \ -d ipn_url="http://website.com/ipn" ``` ### Request Property | Description -------- | ----------- **amount**
`Required` | Amount as an integer of the minor unit of the currency. See [Parameters Description](./apirule#parameters-description). **currency**
`Required`| The 3-letter currency code. Currently, acceptable currencies are `USD` and `JPY`. **reference**
`Required` | An alphanumeric string up to 30 characters that must be unique to each of your transactions. This allows you to keep track of transactions when data comes back through IPN and Callback URLs. **items**
`Conditional` | Order product item list, see [Parameters Description](./apirule#parameters-description). **vendor**
`Required`| Transaction vendor. Currently, acceptable vendors are `alipay` , `unionpay`and `wechatpay`. **ipn_url**
`Required` | Instant Payment Notification URL. Called by the API to update you on transaction information. This is where the response goes to. See [Instant Payment Notification](./apirule#instant-payment-notification). **timeout**
`Optional`
Default: 120 | Specifies amount of minutes card holders have before payment page times out. Once the page times out without a successful payment, the transaction is automatically cancelled. Acceptable values are `1 - 1440`. **description**
`Optional`| Arbitrary string that you can set to be displayed on the card charge. **note**
`Optional`
| Arbitrary string as note to self regarding the transaction. > **Response** ```json { "code_url": "https://qr.alipay.com/bax02617gyevjsjqxgoz2038", "id": "20170519093828105112", "timeout": 120, "currency": "USD", "amount": 100, "reference": "20170427-137-0011", "time": "2017-05-19T09:38:28Z" } ``` ### Response Returns a QRcode object. Property | Description ------- | ----------- **code_url**
`string` | The string of QR code url. **id**
`string` | Transaction ID. **amount**
`int` | Amount of the transaction in the minor unit of the currency. For example, cents in USD. **currency**
`string` | The 3-letter currency code. **timeout**
`int`
| Within the specified minutes, code url will time out. If you did not provide this, default value will be returned to you. **reference**
`string` | AlphaNumeric string set in request to correspond transaction ID with your original transaction request. **time**
`string` | Timestamp of the transaction in UTC. Ex: `2015-01-01T01:01:00Z` is Jan 1, 2015 1:01:00 UTC ## Static Omni-Channel QRcode ### Create a Static Omni-Channel QRcode ```shell POST https://api.nihaopay.com/v1.2/merchantqrcode ``` The payment solution is making use of a static QR code to represent the account of a merchant. In this solution, the customer needs to scan and the input the amount to complete the payment of transaction. Merchant requests static QRcode API in order to generate a static QRcode. Merchant creates a QR Code based on `qrcode`, then prints and posts the QRcode image in merchant's store. The customer scans the QRcode, enters payment amount and completes the transaction on his or her phone. Upon transaction completion, the API will return an asynchronous message to the IPN url. **The asynchronous message return to IPN URL is the same with SecurePay.** > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/merchantqrcode \ -H "Authorization: Bearer " \ -d ipn_url="http://website.com/ipn" \ -d trade_currency="USD" \ -d seller_name="NihaoPay" \ -d store_name="LA Branch" \ -d store_no="B001" ``` ### Request Property | Description -------- | ----------- **trade_currency**
`Required`| The 3-letter currency code. Currently, acceptable currencies are `USD` and `JPY`. **ipn_url**
`Optional` | Instant Payment Notification URL. Called by the API to update you on transaction information. This is where the response goes to. See [Instant Payment Notification](./apirule#instant-payment-notification). **seller_name**
`Required`| Seller name, Displayed on payment page. **store_name**
`Required` | Store name **store_no**
`Required` | Store number > **Response** ```json { "seller_name": "NihaoPay", "store_name": "LA Branch", "store_no": "B001", "qrcode_img_url": "https://apitest.nihaopay.com/merqrcode/9b2487be23a3434b9eb62870fcb73680", "qrcode": "https://apitest.nihaopay.com/topayment/9b2487be23a3434b9eb62870fcb73680" } ``` ### Response Property | Description ------- | ----------- **seller_name**
`string` | Seller name **store_name**
`string` | Store name **store_no**
`string` | Store number **qrcode_img_url**
`string` | QRcode image url. **qrcode**
`string`
| QRcode url. ### ### Static QRcode Payment ```shell POST https://api.nihaopay.com/v1.2/transactions/staticqrcode ``` NihaoPay provides standard payment page for Omni-channel QRcode. In order for merhcants to display their brands on payment page, NihaoPay supports the merchant build H5 payment page corresponding to the QRcode. When customer confirms payment, the following payment interface will wake up WechatPay or AliPay wallet. > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/staticqrcode \ -H "Authorization: Bearer " \ -d amount=100 \ -d vendor="alipay" \ -d reference="201705030002" \ -d qrcode="https://apitest.nihaopay.com/topayment/9b2487be23a3434b9eb62870fcb73680" \ -d callback_url="https://nihaopay.com" \ -d description="static QrCode" ``` ### Request Property | Description -------- | ----------- **amount**
`Required` | Amount as a positive integer of the minor unit of the currency. If amount is not null, it means the transaction uses foreign currency. See [Parameters Description](./apirule#parameters-description). **vendor**
`Required`| The payment method is determined based on the APP used by the customer to scan the QR code. If WeChat APP, it's `wechatpay`,If AliPay wallet,it's `alipay`. **qrcode**
`Required` | QRcode url,It's returned by `Create a Static Omni-Channel QrCode`. **reference**
`Optional` | An alphanumeric string up to 30 characters that must be unique to each of your transactions. This allows you to keep track of transactions when data comes back through IPN and Callback URLs. See [Parameters Description](./apirule#parameters-description). **items**
`Conditional` | Order product item list, see [Parameters Description](./apirule#parameters-description). **callbacl_url**
`Optional` | URL the browser will be redirected to upon completing the transaction. **description**
`Optional` | Arbitrary string that you can set to be displayed on the card charge. > **Response** ```json { "redirect_url": "https://wxcode.nihaopay.com/wechatpay/openid?txnId=20180314095142025479" } ``` ### Response When request is successful, the interface will return a page redirect url, redirecting page to this address, and automatically wakes up the payment function by APP. Property | Description ------- | ----------- **redirect_url**
`string` | redirect url. ## Static AliPay QRcode ```shell POST https://api.nihaopay.com/v1.2/merchantqrcode ``` The payment solution makes use of a static QR code to represent the account of a merchant. In this solution, the customer needs to scan and then input the amount to complete the payment of transaction. Merchant's requests static QRcode API in order to generate a static QRcode. Merchant creates a QR Code based on `qrcode`, then prints and posts the QRcode image in merchant's store. The customer scans the QRcode use AliPay APP, enters payment amount and completes the transaction on his or her phone. Upon transaction completion, the API will return an asynchronous message to the IPN url. **The asynchronous message returned to IPN URL is same with SecurePay.** > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/merchantqrcode \ -H "Authorization: Bearer " \ -d ipn_url="http://website.com/ipn" \ -d trade_currency="USD" \ -d seller_name="NihaoPay" \ -d store_name="LA Branch" \ -d store_no="B001" ``` ### Request Property | Description -------- | ----------- **trade_currency**
`Required`| The 3-letter currency code. Currently, acceptable currencies are `USD` and `JPY`. **vendor**
`Required`| Only: `alipay`. **ipn_url**
`Optional` | Instant Payment Notification URL. Called by the API to update you on transaction information. This is where the response goes to. See [Instant Payment Notification](./apirule#instant-payment-notification). **seller_name**
`Required`| Seller name, Displayed on payment page. **store_name**
`Required` | Store name **store_no**
`Required` | Store number > **Response** ```json { "seller_name": "NihaoPay", "store_name": "LA Branch", "store_no": "B001", "qrcode_img_url": "https://mobilecodec.alipay.com/show.htm?code=ocx09459xspxxdajnvzik3d", "qrcode": "https://qr.alipay.com/ocx09459xspxxdajnvzik3d" } ``` ### Response Property | Description ------- | ----------- **seller_name**
`string` | Seller name **store_name**
`string` | Store name **store_no**
`string` | Store number **qrcode_img_url**
`string` | QRcode image with AliPay logo **qrcode**
`string`
| QRcode url. # Customs Declaration Customs declaration is needed for products shipped directly to China from international merchants. ## Declaration API Customs declaration service currenly supports orders paid with UnionPay, AliPay and WeChatPay. If you want to use this service for WeChatPay, please [contact us](mailto:tech_support@nihaopay.com) first for technical support. ```shell POST https://api.nihaopay.com/v1.2/customs/declaration/{transaction_id} ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/customs/declaration/20180529073648029764 \ -H "Authorization: Bearer " \ -d request_no=20180529073648029702 \ -d customs=ningbo \ -d merchant_customs_code=440316T004 \ -d merchant_customs_name=财付通支付科技有限公司 \ -d customs_amount=1284 \ -d split=true \ -d product_amount=1284 \ -d transport_amount=0 \ -d sub_order_id=20180529073648029701 ``` ### Request Property | Description -------- | ----------- **request_no**
String(36) `Required`| Request order number **customs**
String(64) `Required` | Customs to send declaration to **merchant_customs_code**
String(32) `Required` | The merchant customs recordation number **merchant_customs_name**
String(64) `Required`| The merchant customs recordation name **customs_amount**
Int `Required` | The declaration amount in RMB "fen (cent)", If the order is splitted, this field cannot be empty. **duty_amount**
Int `Optional` | Customs duty in RMB "fen (cent)". Required by some customs **split**
bool `Required`
Default: `true` | Splitting order? Default: true **sub_order_id**
String(64) `Required` | Merchant's sub order number. **product_amount**
Int `Conditional` | Product's value in RMB "fen(cent)". If the order is splitted, this field cannot be empty **transport_amount**
Int `Conditional` | Shipping cost. If the order is splitted, this field cannot be empty **cert_type**
String(16) `Required`| Certification type. Only supports Chinese Mainland ID for now. Default: `ID_CARD` **cert_name**
String(64) `Required`| Name on certificate **cert_no**
String(32) `Required`| Chinese mainland ID number (please captalize the trailling X) ### Request parameter desciption You can declare through the following customs: * ZONGSHU:General Administration of Customs * BEIJING:Beijing Customs * HANGZHOU:Hangzhou Customs * NINGBO:Ningbo Customs * GUANGZHOU:Guangzhou Customs * GUANGZHOU_HUANGPU:Guangzhou Huangpu Customs * SHENZHEN:Shenzhen Customs * NANSHA:Nansha Guo Jian * ZHENGZHOU:Zhenzhou Customs(Henan bonded logistics center) * XINZHENG:Xinzheng comprehensive free trade zone (Airport) * CHONGQING:Chongqing Customs * SHANGHAI:Shanghai Customs * XIAN:Xi'an Customs * TIANJING:Tianjin Customs * XIAMEN: Xiamen Customs > **Response** ```json { "id": "20180529084416000000", "status": "pending", "transaction_id": "20180529073648029764", "pay_transaction_id": "2019011122001376840500835544", "ver_dept": 2, "pay_code": "312226T001", "cert_check": "UNCHECKED" } ``` ### Response Property | Description ------- | ----------- **id**
`string` | Serial number for customs declaration, generated by NihaoPay **status**
`string` | Customs declaration status: `success`, `failure`, `pending`. **transaction_id**
`string` | Transaction ID **pay_transaction_id**
`string` | A unique number assigned by payment provider **ver_dept**
`int` | The organization that verifies the transaction can be: 0-UnionPay,1-NetsUnion,2-Other **pay_code**
`string` | The customs registration number of payment provider. **cert_check**
`string` | Verification result of the purchaser and payer identity information. `SAME` - Identity information is matched; `DIFFERENT` - Identity information is not matched; `UNCHECKED` - Unchecked or no purchaser identification information provided. ### Customs code UnionPay's customs registration info: * Customs Name:中国银联股份有限公司 * Customs code:312228034U WeChatPay's customs registration info: * Customs Name:财付通支付科技有限公司 * Customs Code:4403169D3W AliPay's customs registration info: * Customs Name:支付宝(中国)网络技术有限公司 Customs | Customs Code ------- | ----------- ZONGSHU | 31222699S7 SHANGHAI | 31222699S7 NINGBO | 31222699S7 ZHENGZHOU | 31222699S7 XINZHENG | P460400005 HANGZHOU | ZF14021901 GUANGZHOU | C000010000416158 TIANJIN | Q12150016000019 ## Declaration query ```shell GET https://api.nihaopay.com/v1.2/customs/{request_no} ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/customs/20180529073648029702 \ -H "Authorization: Bearer " ``` ### Request Property | Description -------- | ----------- **request_no**
`Required` | Request order number > **Response** ```json { "id": "20180529084416000000", "request_no": "20180529073648029702", "status": "pending", "vendor_id": "4200000112201805292728213273", "customs": "NINGBO", "split": true, "customs_amount": 1284, "product_amount": 1284, "transport_amount": 0, "transaction_id": "20180529073648029764", "sub_order_id": "20180529073648029701", "pay_transaction_id": "2019011122001376840500835544", "ver_dept": 2, "pay_code": "312226T001" } ``` ### Response Property | Description ------- | ----------- **id**
`string`| Declaration status request ID **transaction_id**
`string`| Original transaction ID **vendor_id**
`string`| Vendor's serial number of original transaction **status**
`string`| Customs declaration status: `success`, `failure`, `pending`. **customs**
`string` | Customs the declaration is sent to **customs_amount**
`int` | Same with request **duty_amount**
`int` | Same with request **split**
`bool` | Splitting order **sub_order_id**
`string` | Same with request **product_amount**
`int` | Same with request **transport_amount**
`int` | Same with request **pay_transaction_id**
`string` | A unique number assigned by payment provider **ver_dept**
`int` | The organization that verifies the transaction can be: 0-UnionPay,1-NetsUnion,2-Other **pay_code**
`string` | The customs registration number of payment provider. ## Redeclaration ```shell POST https://api.nihaopay.com/v1.2/customs/redeclaration/{request_no} ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/customs/redeclaration/20210810150833001421 \ -H "Authorization: Bearer " ``` ### Request Property | Description -------- | ----------- **request_no**
`Required` | Request order number > **Response** ```json { "transaction_id": "20210810150833001421", "cert_check": "DIFFERENT", "ver_dept": 3, "request_no": "20210810150833001421", "pay_code": "31222699S7", "pay_transaction_id": "2021081011082640020055578", "merchant_id": "M001100001", "id": "20210810150935000155", "status": "success" } ``` ### Response Property | Description ------- | ----------- **request_no**
`string` | Request order number **id**
`string`| Declaration status request ID **merchant_id**
`string`| NihaoPay Merchant ID **transaction_id**
`string`| Original transaction ID **status**
`string`| Customs declaration status: `success`, `failure`, `pending`. **pay_transaction_id**
`string` | A unique number assigned by payment provider **ver_dept**
`int` | The organization that verifies the transaction can be: 0-UnionPay,1-NetsUnion,2-Other **pay_code**
`string` | The customs registration number of payment provider. **cert_check**
`string` | Verification result of the purchaser and payer identity information. `SAME` - Identity information is matched; `DIFFERENT` - Identity information is not matched; `UNCHECKED` - Unchecked or no purchaser identification information provided. ## Error code for Customs Declaration code|label|message -------|-------|----------- 400|31| Transaction reference number must be unique. Please re-submit. 402|61| Transaction not found. 500|81| Merchant config error 500|82| Merchant unavailable 400|90| The field not valid. 500|91| Signature error 500|92| The {0} field is required. 500|96| Timeout 500|97| Inner error 500|98| Vendor error 500|99| System error 401|301| Invalid merchant credentials provided 402|100| Transaction retransmission fail, Please try it after 5 minutes. 402|101| Customs not supported. 402|102| Customs infomation changed. 402|103| Certification not correct. 402|104| Split amount not correct. 402|105| Can not be modified as it is on declaration. 402|106| Same customs declare once. 402|107| Your request has been submitted, please confirm that it has taken effect. 402|108| The original customs does not exist 402|109| The declaration is not allowed for refunded orders # Auto Debit ## Auto Debit Description After completing the contract with the user, funds can be directly deducted from the user's contracted wallet. ## Auto Debit Rules 1. The same contract can only be signed once per user. Repeated signing will return a failure. 2. Both the merchant and user can terminate the contract after signing. 3. Full refund after deduction will not return the remaining deduction times within the cycle. 4. Auto debit currently only supports WeChat Pay. 5. WeChat auto debit limits (please contact Business Development for specific limit details) ## Auto Debit API ### 1. Auto Debit Signing #### Request Parameters | Parameter | Required | Type | Description | Example | |------------------|----------|------------|--------------------------------------|---------------------------------| | appId | No | string | App ID, required if multiple apps are enabled for differentiation | wx123567 | | agreementId | Yes | string | Contract ID, plan_id in WeChat scenario | 202301010001 | | username | Yes | string(32) | Name of signing user for display, no URL encoding needed, parameter value does not support UTF8 non-3-byte encoded characters | Zhang San | | vendor | Yes | string(16) | Payment channel, e.g. `wechatpay` | wechatpay | | currency | Yes | string(3) | Currency code, e.g. `USD` | USD | | notifyUrl | Yes | string | Async notification URL for receiving signing results | https://api.example.com/notify | | returnUrl | No | string | Sync return URL, required for (`H5`, `JSAPI`) after signing | https://api.example.com/return | | userId | No | string | User identifier, required when vendor=wechatpay for `JSAPI`, `MINI_APP` | oSC6Tw6SrhMMzMguby9cCqVzOo | | platform | Yes | string | Platform type: `WEB`/`H5` (web), `APP` (mobile app), `MINI_APP` (mini program), `JSAPI` (WeChat official account) | WEB | | clientIp | No | string | Client IP address for risk control,required when vendor=wechatpay for `H5` | 127.0.0.1 | | reference | Yes | string(64) | Merchant unique identifier for this signing request | 202301010001 | | remark | No | string | Remarks for additional signing info | Test signing | #### Response Parameters | Parameter | Required | Type | Description | Example | |------------------|----------|------------|--------------------------------------|---------------------------------| | code | Yes | string | Return code, `00` for success, others for failure | 00 | | label | Yes | string | Return code label | 00 | | message | Yes | string | Return message describing operation result | success | | agreementId | Yes | string | Contract ID, plan_id in WeChat scenario | 202301010001 | | contractNo | Yes | string | Contract number, unique identifier for nihaopay contract | 202301010001 | | signId | Yes | string | Signing URL, returns signId for APP/mini program, signUrl for WEB/H5 | 202501111159364508440 | | signUrl | Yes | string | Signing ID, returns signId for APP/mini program, signUrl for WEB/H5 | https://api.example.com/sign | >**Request Example** >**Scenario 1: WEB Signing** ```shell curl --location 'https://api.nihaopay.com/v1.2/contract/sign' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "appId": "your appId", "agreementId": "your agreementId", "usersame": "your customer name", "vendor": "wechatpay", "currency": "USD", "notifyUrl": "https://YOUR_HOST/notify", "returnUrl": "https://YOUR_HOST/callback", "platform": "WEB", "clientIp": "127.0.0.1", "reference":"your unique reference", "remark": "remark" }' ``` >**Failed Response Example** ```json { "code": "01", "label": "01", "message": "failed" } ``` >**Successful Response Example** >**Scenario 1: APP/Mini Program** ```json { "code": "00", "label": "00", "message": "success", "agreementId": "your agreementId", "contractNo": "our contractNo", "signId": "xxxxxxxx" } ``` >**Scenario 2: JSAPI/WEB/H5** ```json { "code": "00", "label": "00", "message": "success", "agreementId": "your agreementId", "contractNo": "our contractNo", "signUrl": "https://api.mch.weixin.qq.com/global/papay/contracts/login?os_session_id=xxx#wechat_pay" } ``` ### 2. Auto Debit Termination #### Request Parameters | Parameter | Required | Type | Description | |------------------|----------|------------|--------------------------------------| | agreementId | Optional | string | Contract ID, plan_id in WeChat scenario | | reference | Optional | string(64) | Merchant unique identifier | | reason | Yes | string | Termination reason | | contractNo | Optional | string | Contract number, unique identifier for nihaopay contract, reference+agreementId and contractNo cannot be empty at the same time | #### Response Parameters | Parameter | Required | Type | Description | |------------------|----------|------------|--------------------------------------| | code | Not null | string | Return code, `00` for success | | label | Not null | string | Return code label | | message | Not null | string | Return message | | contractId | Not null | string | Contract ID | | contractNo | Not null | string | Contract number, unique identifier for nihaopay contract | | reference | Not null | string | Merchant unique identifier | >**Request Example** >**Using agreementId + reference** ```shell curl --location 'https://api.nihaopay.com/v1.2/contract/terminate' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "agreementId": "your agreementId", "reference": "your unique reference", "reason": "your terminate reason" }' ``` >**Using contractNo** ```shell curl --location 'https://api.nihaopay.com/v1.2/contract/terminate' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "contractNo": "d649252400014ea7a8a890704cc600d6", "reason": "your terminate reason" }' ``` >**Successful Response Example** ```json { "code": "00", "label": "00", "message": "success", "contractId": "contract id", "contractNo": "our contract number", "reference": "your unique reference" } ``` >**Failed Response Example** ```json { "code": "01", "label": "01", "message": "failed" } ``` ### 3. Auto Debit Contract Query #### Request Parameters | Parameter | Required | Type | Description | |------------------|----------|------------|--------------------------------------| | agreementId | Optional | string | Contract ID, plan_id in WeChat scenario | | reference | Optional | string(64) | Merchant unique identifier | | contractNo | Optional | string | Contract number, unique identifier for nihaopay contract, reference+agreementId and contractNo cannot be empty at the same time | #### Response Parameters | Parameter | Required | Type | Description | |------------------|----------|------------|--------------------------------------| | code | Not null | string | Return code, `00` for success | | label | Not null | string | Return code label | | message | Not null | string | Return message | | contractId | Not null | string | Contract ID | | contractNo | Not null | string | Contract number, unique identifier for nihaopay contract | | contractStatus | Not null | string | Contract status: `Signed` (signed), `Terminated` (terminated), `Processing` (pending signing), `FAIL` (signing failed) | | signedTime | May be null | string | Signing time | | terminateTime | May be null | string | Termination time | | terminateMode | May be null | string | Termination mode: `USER` (user initiated), `MERCHANT` (merchant initiated), `PLATFORM` (platform initiated) | >**Request Example** >**Scenario: agreementId + reference** ```shell curl --location 'https://api.nihaopay.com/v1.2/contract/query' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "agreementId": "your agreementId", "reference": "your unique reference" }' ``` >**Scenario: contractNo** ```shell curl --location 'https://api.nihaopay.com/v1.2/contract/query' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "contractNo": "d649252400014ea7a8a890704cc600d6" }' ``` >**Response Example** ```json { "code": "00", "label": "00", "message": "success", "contractId": "contract id", "contractNo": "our contract number", "contractStatus": "Signed/Terminated", "signedTime": "2025-01-15 19:15:14", "terminateTime": "2025-01-15 19:15:14", "terminateMode": "USER/MERCHANT/PLATFORM", } ``` ### 4. Initiate Deduction #### Request Parameters | Parameter | Required | Type | Description | |------------------|----------|------------|--------------------------------------| | amount | Not null | string | Deduction amount | | currency | Not null | string(3) | Currency code, e.g. USD | | note | Optional | string | Order remarks | | description | Not null | string | Deduction description (visible to user) | | ipn_url | Not null | string | Async notification URL | | reference | Not null | string(64) | Merchant unique identifier | | vendor | Not null | string(16) | Payment channel, e.g. wechatpay | | contract_id | Not null | string | Contract ID, can be obtained from signing callback or query API | #### Response Parameters | Parameter | Required | Type | Description | |------------------|----------|------------|--------------------------------------| | status | Not null | string | Transaction status: `success`/`failure` | | reference | Not null | string | Merchant order number | | currency | Not null | string(3) | Transaction currency, e.g. USD | | amount | Not null | decimal | Transaction amount | | rmb_amount | Not null | decimal | RMB amount | | id | Not null | string | Transaction ID | | note | May be null | string | Order remarks | | time | Not null | string | Transaction time in UTC format | | message | Not null | string | Transaction result description | >**Request Example** ```shell curl --location 'https://api.nihaopay.com/v1.2/transactions/autodebit' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "amount": "1", "currency": "USD", "note": "your order note", "description": "", "ipn_url": "", "reference": "", "vendor": "wechatpay", "contract_id": "" }' ``` >**Successful Response Example** ```json { "status": "success", "reference": "", "currency": "USD", "amount": 1, "rmb_amount": 0, "id": "20250111220054100012", "note": "autodebit test", "time": "2025-01-11T22:00:54Z", "message": "" } ``` >**Failed Response Example** ```json { "status": "failure", "reference": "", "currency": "USD", "amount": 1, "rmb_amount": 0, "id": "20250111220054100012", "note": "autodebit test", "time": "2025-01-11T22:00:54Z", "message": "User account payment limit reached" } ``` ## Contract Status Async Notification ### Notification Parameters | Parameter | Required | Type | Description | |------------------|----------|------------|--------------------------------------| | agreementId | Not null | string | Contract ID, plan_id in WeChat scenario | | userId | Not null | string | User ID, open_id in WeChat scenario | | contractId | Not null | string | Contract ID, required for initiating deductions | | contractNo | Not null | string | Contract number, unique identifier for nihaopay contract | | reference | Not null | string | Merchant unique identifier | | contractStatus | Not null | string | Status: `Signed` (signed), `Terminated` (terminated), `Processing` (pending signing), `FAIL` (signing failed) | | signedAt | May be null | string | Signing time, required for signing notifications | | terminateAt | May be null | string | Termination time, required for termination notifications | | terminateMode | May be null | string | Termination mode, required for termination notifications: `USER` (user initiated), `MERCHANT` (merchant initiated), `PLATFORM` (platform initiated) | >**Signing Notification Example** ```shell curl -X POST ${YOUR_NOTIFY_URL} \ --header 'Content-Type: application/json' \ --header 'Signature: ${signature}' \ --data '{ "agreementId": "your agreementId", "userId": "contract user id", "contractId": "contract id", "contractNo": "our contract number", "reference": "your unique reference", "contractStatus": "Signed/Terminated", "signedAt": "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ", "terminateAt": "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ", "terminateMode": "USER/MERCHANT/PLATFORM", }' ``` ### Signing Notification Signature `signature = MD5(body + '&' + MD5(token))` ### Callback Notification Retry Mechanism 1. Maximum of 7 notifications 2. Notification intervals: 0m,1m,2m,4m,8m,20m,30m # Profit Sharing ## Description of Profit Sharing Feature The profit sharing feature transfers part of a payment order's amount to other recipient merchants. There are two kinds of profit sharing: - **Order profit sharing**: shares a specific payment order (with `relationTxnId`). - **Global profit sharing**: without `relationTxnId`, automatically shares every payment order cleared from then on according to the configuration. A profit sharing request is not executed immediately. It is executed in the daily settlement run, and the result is sent through the [callback](#profit-sharing-callback). You can also get it from [Query Current Profit Sharing Execution Result](#query-current-profit-sharing-execution-result). ## Profit Sharing Rules 1. **Currency**: The sharing currency must equal the settlement currency of the payment order. Cross-currency profit sharing is not supported. For global profit sharing, the currency must be a settlement currency of the source merchant. 2. **Recipient**: The recipient merchant (`targetMerCode`) must be an active merchant with a settlement account in the sharing currency. The source merchant and the recipient cannot be the same. 3. **Channel**: Only payment orders of self-collected channels support profit sharing. Order profit sharing on other channels is rejected, and global profit sharing skips those orders. Contact BD to confirm which channels are supported. 4. **Global profit sharing**: Only one active global profit sharing is allowed for the same source merchant, recipient and currency. It applies only to payment orders cleared in the daily run while the configuration is active, and is not applied to orders that were already cleared. 5. **No stacking**: A payment order can use either global profit sharing or order profit sharing, not both. An order that has been shared by a global configuration cannot be shared again by an order profit sharing request; global profit sharing skips orders that have a pending order profit sharing request. 6. **Amount**: Profit sharing can be executed multiple times for a payment order, but the cumulative sharing amount cannot exceed the available amount of the payment order (net settlement amount minus refunded and already shared amounts). Sharing amounts are rounded to the currency precision, and a sharing amount below 0.01 fails. 7. **Execution time**: Profit sharing is executed every day starting at 15:00 UTC (23:00 Beijing time). Order profit sharing is executed only after the payment order has been cleared and stays "Pending" until then. After a successful execution the status changes to "Success"; on failure it changes to "Failed". 8. **Cancel**: Pending order profit sharing and active global profit sharing can be canceled. **Cancel is not allowed between 15:00 and 18:00 UTC (23:00 to 02:00 Beijing time) while profit sharing is being executed**; use a reversal after the execution finishes. Successful profit sharing cannot be canceled, only reversed. 9. **Reversal**: You can only reverse successful profit sharing initiated by yourself; pending profit sharing cannot be reversed. A reversal can be full or partial, and partial reversals can be done multiple times, but the cumulative reversed amount cannot exceed the amount received from the original profit sharing. 10. **Fees**: Profit sharing and reversal are charged at the initiator's profit sharing rate and reversal rate, rounded to the currency precision. If the original profit sharing rate is configured to return fees, a reversal returns the original fee in proportion to the reversed amount. Profit sharing fails if no profit sharing rate is configured; contact BD to enable it. 11. As profit sharing incurs fees, the cumulative total of profit sharing or reversal cannot exceed the amount of the original payment order or profit sharing **after deducting fees**. You might consider setting the fee to be deducted from the source account. 12. **Permission**: Merchants can only initiate profit sharing for their own payment orders. Platform-type merchants can initiate profit sharing for the payment orders of their associated merchants (specify the merchant with `sourceMerCode`); see [Query Delegated Merchants](#query-delegated-merchants). 13. **Limits**: A payment order can be shared at most 50 times, and each profit sharing can be reversed at most 10 times. ## Explanation of the Actual Effect of Profit Sharing ### Prerequisites 1. Payment order amount: 100 USD 2. Platform fee collected: 2 USD 3. Actual settlement to Merchant A: 98 USD 4. Merchant A initiates profit sharing of 10% to Merchant B (the base amount is the net settlement amount of the payment order, 98 USD). 5. Payment processing fee rate: 2% 6. Profit sharing fee rate: 2% 7. Fees are rounded to cents: 9.80 × 2% = 0.196, recorded as 0.20. ### Scenario 1: Handling fee deducted from the transaction | Account | Profit Sharing Amount | Handling Fee | Amount Received | | ---------- | --------------------- | ------------ | --------------- | | Merchant A | -9.80 | 0.00 | -9.80 | | Merchant B | 9.80 | 0.20 | 9.60 | ### Scenario 2: Handling fee deducted from the source account | Account | Profit Sharing Amount | Handling Fee | Amount Received | | ---------- | --------------------- | ------------ | --------------- | | Merchant A | -9.80 | 0.20 | -10.00 | | Merchant B | 9.80 | 0.00 | 9.80 | ## Explanation of the Actual Effect of Reversing Profit Sharing ### Prerequisites 1. Payment order amount: 100 USD 2. Platform fee collected: 2 USD 3. Actual settlement to Merchant A: 98 USD 4. Merchant A initiates profit sharing of 10% to Merchant B with a fee of 2%. 5. Merchant A initiates a full reversal (without `splitMethod`/`splitValue`). The reversed amount is the amount received from the original profit sharing (Note: The original profit sharing might not be reversed in full because of the deducted fees). 6. Payment processing fee rate: 2% 7. Profit sharing fee rate: 2% 8. Reversal fee rate: 2%; the original profit sharing rate does not return fees. 9. `feeFrom` of a reversal is set in the reversal request. In both scenarios below, the reversal uses the same `feeFrom` as the original profit sharing. ### Scenario 1: Handling fee deducted from the transaction | Account | Profit Sharing Amount | Handling Fee | Amount Received | | ---------- | --------------------- | ------------ | --------------- | | Merchant A | -9.80 | 0.00 | -9.80 | | Merchant B | 9.80 | 0.20 | 9.60 | | Merchant A | 9.60 | 0.19 | 9.41 | | Merchant B | -9.60 | 0.00 | -9.60 | ### Scenario 2: Handling fee deducted from the source account | Account | Profit Sharing Amount | Handling Fee | Amount Received | | ---------- | --------------------- | ------------ | --------------- | | Merchant A | -9.80 | 0.20 | -10.00 | | Merchant B | 9.80 | 0.00 | 9.80 | | Merchant A | 9.80 | 0.00 | 9.80 | | Merchant B | -9.80 | 0.20 | -10.00 | ## Explanation of Fixed Amount Profit Sharing 1. For common currencies such as JPY, KRW, VND, where the smallest unit is the base unit, the splitValue unit is in the base unit. For example, splitValue=1000 means a profit sharing of 1000 units. 2. For common currencies such as USD, CNY, where the smallest unit is cents, the splitValue unit is in cents. For example, splitValue=1023 means a profit sharing of 10.23 USD. 3. Amount fields in query results and callbacks also use the smallest currency unit. ## Parameter Explanation | Parameter | Mandatory | Type | Explanation | | --------------- | ----------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **reference** | Required | string(240) | The unique identifier of the profit sharing initiator, used to check uniqueness of profit sharing configurations. Only letters, digits and `_` `.` `:` `-` are allowed. | | **sharingType** | Required | int | 0: Profit Sharing, 2: Reversal of Profit Sharing | | splitMethod | Conditional | int | 0: Percentage-based profit sharing, 1: Fixed amount profit sharing. Required for profit sharing; optional for a reversal (full reversal if omitted). | | splitValue | Conditional | int | When splitMethod=0, the profit sharing percentage with a precision of ten thousandths, from 1 to 9999. For example, splitValue=1023 means 10.23%
When splitMethod=1, the actual profit sharing amount (the smallest unit of the currency) [Currency Rules](#explanation-of-fixed-amount-profit-sharing).
Required for profit sharing; for a reversal, pass it together with splitMethod. | | targetMerCode | Conditional | string(11) | The recipient merchant. Required for profit sharing. Not needed for a reversal (same as the original profit sharing). | | sourceMerCode | Optional | string(11) | The funding source merchant. If not provided, the current merchant is used. For order profit sharing it must be the merchant of the payment order. To share for another merchant, the current merchant must be its platform merchant. | | currency | Conditional | string(3) | Sharing currency, such as USD, CNY. Required for profit sharing and must equal the settlement currency of the payment order. Not needed for a reversal (same as the original profit sharing). | | relationTxnId | Conditional | string(21) | The ID of the payment order to share, which is nihaopay's transactionId. Omitting it for profit sharing creates a global profit sharing configuration; use with caution in production. Required for a reversal. | | remark | Optional | string(128) | Remarks that appear in the order description when viewing the order. Only letters, digits, `_` `.` `:` `-` and Chinese characters are allowed; spaces and punctuation are not. | | feeFrom | Optional | int | 0: The handling fee is deducted from the transaction (paid by the recipient)
1: The handling fee is deducted from the source account
Default: 0 | | baseFrom | Optional | int | Base amount for percentage-based calculation:
0: Net settlement amount of the original payment order
1: Amount of the original profit sharing (reversal only)
2: Order amount of the original payment order
Default: 0. For a partial percentage reversal you usually need 1. | | originConfId | Conditional | string(21) | Required for a reversal: the ID of the original profit sharing configuration to reverse. | | notifyUrl | Optional | string(256) | The callback URL for profit sharing results. Both success and failure are notified. [Data format](#profit-sharing-callback). Must be an http or https URL reachable from the public internet. | ## Profit Sharing Interface [postman setting download](https://docs.nihaopay.com/api/sharing.postman.json) > Scenario: Initiate Global Percentage-based Profit Sharing ```shell curl --location 'https://api.nihaopay.com/v1.2/sharing/apply' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "sharingType": 0, "splitMethod": 0, "splitValue": 10, "reference": "20211111153109001472", "targetMerCode": "M001000001", "currency": "USD", "remark": "test_remark", "notifyUrl": "https://www.nihaopay.com/sharing/notify" }' ``` > Scenario: Initiate Percentage-based Profit Sharing for a Specific Order ```shell curl --location 'https://api.nihaopay.com/v1.2/sharing/apply' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "relationTxnId": "20211111153109001472", "sharingType": 0, "splitMethod": 0, "splitValue": 1000, "targetMerCode": "M001000001", "reference": "20211111153109001472", "remark": "test_remark", "notifyUrl": "https://www.nihaopay.com/sharing/notify", "currency": "USD" }' ``` > Scenario: Initiate Fixed Amount Profit Sharing for a Specific Order ```shell curl --location 'https://api.nihaopay.com/v1.2/sharing/apply' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "relationTxnId": "20211111153109001472", "sharingType": 0, "splitMethod": 1, "splitValue": 100, "targetMerCode": "M001000001", "reference": "20211111153109001472", "remark": "test_remark", "notifyUrl": "https://www.nihaopay.com/sharing/notify", "currency": "USD" }' ``` > Scenario: Partially Reverse Profit Sharing (50% of the original sharing amount) ```shell curl --location 'https://api.nihaopay.com/v1.2/sharing/apply' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "relationTxnId": "20211111153109001472", "sharingType": 2, "splitMethod": 0, "splitValue": 5000, "baseFrom": 1, "reference": "20211111153109001473", "remark": "test_remark", "notifyUrl": "https://www.nihaopay.com/sharing/notify", "originConfId": "20211111153109001472" }' ``` > Scenario: Fully Reverse Profit Sharing ```shell curl --location 'https://api.nihaopay.com/v1.2/sharing/apply' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "relationTxnId": "20211111153109001472", "sharingType": 2, "reference": "20211111153109001474", "remark": "test_remark", "notifyUrl": "https://www.nihaopay.com/sharing/notify", "originConfId": "20211111153109001472" }' ``` > Profit Sharing Initiation Success Response ```json { "confId": "20230804021118097285" } ``` > Profit Sharing Initiation Failure Response ```json { "code": 400, "label": "N/A", "message": "sharing config already exist" } ``` Common failure reasons when applying: | message | Explanation | | --------------------------------------------------------------- | -------------------------------------------------------------------------- | | reference is invalid / remark is invalid / notifyUrl is invalid | Parameter format is invalid | | relation transaction currency not match | Sharing currency differs from the settlement currency of the payment order | | source merchant has no settlement account in sharing currency | The source merchant of a global configuration has no account in the currency | | target merchant has no settlement account in sharing currency | The recipient has no settlement account in the currency | | targetMerCode not exist / targetMerCode is not active | The recipient does not exist or is not active | | channel provider not support sharing | The payment channel does not support profit sharing (not self-collected) | | transaction already shared by global sharing config | The order was shared by a global configuration and cannot be shared again | | no transaction sharing permission | No permission to share for this merchant | | sharing config already exist | Duplicate profit sharing configuration | | reverse amount exceed available amount | The reversal amount exceeds the reversible amount | ## Query Current Profit Sharing Configuration Returns profit sharing configurations initiated by the current merchant with status Pending (`APPLY`) or Success/Active (`SUCCESS`), up to 50 records. Canceled and failed configurations are not returned; get failure reasons from [Query Current Profit Sharing Execution Result](#query-current-profit-sharing-execution-result) or the callback. | Parameter | Mandatory | Type | Explanation | | ------------- | --------- | ---------- | -------------------------------------------------- | | relationTxnId | Optional | string(21) | Payment order ID | | originConfId | Optional | string(21) | Original profit sharing configuration ID (reversals) | | reference | Optional | string | Initiator's reference | | sharingType | Optional | int | 0: Profit Sharing, 2: Reversal | | currency | Optional | string(3) | Sharing currency | > Query all profit sharing configurations ```shell curl --location 'https://apitest.nihaopay.com/v1.2/sharing/query' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{}' ``` > Query profit sharing configurations of a payment order ```shell curl --location 'https://apitest.nihaopay.com/v1.2/sharing/query' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "relationTxnId": "20230804021118097285" }' ``` > Profit sharing configuration success response ```json { "sharingConfItems": [ { "confId": "20230804021822097288", "reference": "9200", "originConfId": "", "relationTxnId": "20230804021118097285", "sourceMerCode": "M001000001", "targetMerCode": "M001000002", "sharingType": 0, "splitMethod": 0, "splitValue": 22, "sharingCurrency": "USD", "txnStatus": "SUCCESS", "failReason": "", "feeFrom": 0, "baseFrom": 0, "remark": "test", "notifyUrl": "https://www.nihaopay.com/sharing/notify" } ] } ``` > No matching configuration ```json { "sharingConfItems": [] } ``` ## Query Current Profit Sharing Execution Result Queries the execution result of a profit sharing configuration on a payment order. Both `relationTxnId` and `confId` are required; a global configuration is executed on many orders, so pass the specific payment order ID. Results may be cached for up to 1 hour. | Parameter | Mandatory | Type | Explanation | | ------------- | --------- | ---------- | -------------------------------- | | relationTxnId | Required | string(21) | Payment order ID | | confId | Required | string(21) | Profit sharing configuration ID | > Request Example ```shell curl --location 'https://apitest.nihaopay.com/v1.2/sharing/detail' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "relationTxnId": "20230804021118097285", "confId": "20230804021822097288" }' ``` > Success Response Example (profit sharing succeeded) ```json { "txnType": "SHARE_PROFIT", "sharingStatus": "SUCCESS", "reference": "9200", "sharingType": 0, "relationTxnId": "20230804021118097285", "sharingConfId": "20230804021822097288", "sourceMerCode": "M001000001", "targetMerCode": "M001000002", "sharingCurrency": "USD", "txnCurrency": "USD", "exchangeRate": 1.0, "baseAmount": 13075, "sourceSharingTxnAmount": -29, "targetSharingTxnAmount": 29, "sourceServiceFee": 0, "targetServiceFee": 1, "feeRate": { "refundReturn": false, "rateAlgorithm": 0, "percentage": 2, "fixedAmount": 0, "minAmount": 0, "maxAmount": 0, "extraRefundFee": 0 } } ``` > Success Response Example (profit sharing failed) ```json { "txnType": "SHARE_PROFIT", "sharingStatus": "FAIL", "reference": "9200", "sharingType": 0, "relationTxnId": "20230804021118097285", "sharingConfId": "20230804021822097288", "sourceMerCode": "M001000001", "targetMerCode": "M001000002", "sharingCurrency": "USD", "failReason": "sharing amount more than available amount" } ``` > Failure Response Example (not executed yet or not found) ```json { "code": 400, "label": "N/A", "message": "sharing history not exist" } ``` Response fields: | Field | Explanation | | ----------------------------------------------- | ------------------------------------------------------------------------------------------- | | txnType | SHARE_PROFIT: profit sharing, SHARE_REVERSE: reversal | | sharingStatus | SUCCESS or FAIL | | baseAmount | Base amount for percentage-based calculation (smallest currency unit) | | sourceSharingTxnAmount / targetSharingTxnAmount | Sharing amount of the source merchant / recipient (smallest currency unit, negative = debit) | | sourceServiceFee / targetServiceFee | Fee paid by the source merchant / recipient (smallest currency unit) | | feeRate | The rate applied; percentage is in % | | originSharingConfId | Reversal only: the original profit sharing configuration ID | | failReason | Failure only: see common failure reasons in [Profit Sharing Callback](#profit-sharing-callback) | ## Cancel Profit Sharing Pending order profit sharing and active global profit sharing can be canceled. Cancel is not allowed between 15:00 and 18:00 UTC (23:00 to 02:00 Beijing time) while profit sharing is being executed. Successful profit sharing can only be reversed. > Request ```shell curl --location 'https://apitest.nihaopay.com/v1.2/sharing/cancel' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{ "confId": "20230719002724096890" }' ``` > Success Response ```json { "confId": "20230719002724096890", "reason": "", "txnStatus": "SUCCESS" } ``` > Failure Response ```json { "confId": "20230719002724096890", "reason": "sharing config not exist", "txnStatus": "FAIL" } ``` Common failure reasons (`reason`): | reason | Explanation | | ------------------------------------------------------ | ------------------------------------------------------------------- | | sharing config not exist | The configuration does not exist | | sharing config not belong to merchant | The configuration was not initiated by the current merchant | | cancel is not allowed between 23:00 and 02:00 ... | Profit sharing is being executed; reverse after it finishes | | sharing operation was success,cannot cancel | Profit sharing succeeded; it can only be reversed | | operation failed, please check the transaction status. | The configuration status has changed (e.g. already canceled or failed) | ## Query Delegated Merchants Platform-type merchants query the associated merchants on whose behalf they can initiate profit sharing. > Request ```shell curl --location 'https://apitest.nihaopay.com/v1.2/sharing/merchants' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ' \ --data '{}' ``` > Response ```json { "merchants": [ { "merCode": "M001000001" }, { "merCode": "M001000002" } ] } ``` ## Profit Sharing Callback After each profit sharing is executed (success or failure), a JSON POST is sent to `notifyUrl`: 1. The notification is sent once and is not retried. The request times out after 10 seconds and redirects are not followed. 2. An HTTP 2xx response is treated as a successful notification. 3. `notifyUrl` must be reachable from the public internet; private network addresses are not notified. 4. The callback is not signed. After receiving it, confirm the result with [Query Current Profit Sharing Execution Result](#query-current-profit-sharing-execution-result). 5. Amount fields are in the smallest unit of the settlement currency; `rate.percentage` is in %. 6. For a reversal, `txnType` is `SHARE_REVERSE`, `sourceMerCode` is the recipient of the original profit sharing (the party being debited), `targetMerCode` is the source merchant of the original profit sharing, and `originSharingConfId`, `originSharingType` and `originRate` are also returned. > Profit Sharing Success Callback ```json { "sharingStatus": "SUCCESS", "txnType": "SHARE_PROFIT", "sharingType": 0, "reference": "TEST_20230803211516007112", "sharingConfId": "20230803211516007112", "relationTxnId": "20230803211516007111", "sourceMerCode": "M001100001", "targetMerCode": "M086100129", "txnCurrency": "USD", "stlCurrency": "USD", "sharingCurrency": "USD", "exchangeRate": 1.0, "baseAmount": 2496, "sourceSharingTxnAmount": -499, "targetSharingTxnAmount": 499, "sourceServiceFee": 0, "targetServiceFee": 10, "rate": { "minAmount": 0, "percentage": 2, "txnCurrency": "USD", "refundReturn": 0, "fixedAmount": 0, "maxAmount": 0 } } ``` > Profit Sharing Failure Callback ```json { "sharingStatus": "FAIL", "txnType": "SHARE_PROFIT", "sharingType": 0, "reference": "TEST_20230803211516007112", "sharingConfId": "20230803211516007112", "relationTxnId": "20230803211516007111", "sourceMerCode": "M001100001", "targetMerCode": "M086100129", "txnCurrency": "USD", "stlCurrency": "USD", "sharingCurrency": "USD", "failReason": "sharing amount more than available amount" } ``` Common failure reasons during execution (`failReason`): | failReason | Explanation | | ------------------------------------------------------------- | ------------------------------------------------------------------ | | rate not found | No profit sharing rate is configured for the initiator; contact BD | | sharing amount more than available amount | The sharing amount exceeds the remaining shareable amount | | sharing amount less than minimum amount | The sharing amount is below 0.01 | | sharing currency not match settlement currency | Sharing currency differs from the order's settlement currency | | transaction already shared by global sharing config | The order was already shared by a global configuration | | target merchant is not active / target merchant not exist | The recipient is not active or does not exist | | target merchant has no settlement account in sharing currency | The recipient has no settlement account in the currency | | sharing reverse amount more than origin sharing amount | The reversal amount exceeds the remaining reversible amount | # Refund/Query/Others ## Retrieve a SecurePay > **Definition** ```shell GET https://api.nihaopay.com/v1.2/transactions/merchant/{reference} ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/merchant/{reference} \ -H "Authorization: Bearer " ``` Provide reference that was requested for a SecurePay transactions in order to retrieve corresponding transaction’s details. Applicable to SecurePay transactions that do not receive asynchronous notifications ### Request `reference` as URL parameter. > **Response** ```json { "id": "bn2345nb53454kjb", "status": "success", "type": "charge", "amount": 1111, "currency": "USD", "time": "2015-01-01T01:01:01Z", "reference": "jkh25jh1348fd89sg", "note": "sample note" } ``` ### Response Returns a transaction object. Property | Description ------- | ----------- **id**
`string` | Transaction ID. **status**
`string` | Transaction status. Either `success`, `failure`, or `pending`. **type**
`string` | Transaction type. Either `charge`, `authorization`, or `capture`. **vendor**
`string` | Payment method. Include: `unionpay`, `alipay`, `wechatpay` or `alipayhk`. **vendor_id**
`string` | Vendor’s transaction id, usually showed on customer’s payment receipt. **amount**
`int` | Amount of the transaction in the minor unit of the currency. For example, cents in USD. **currency**
`string` | The 3-letter currency code. **time**
`string` | Timestamp of the transaction in UTC. Ex: `2015-01-01T01:01:00Z` is Jan 1, 2015 1:01:00 UTC. **reference**
`string` | AlphaNumeric string set in request to correspond transaction ID with your original transaction request. **note**
`string/null` | If set in request, your transaction note to self. Else if not set, this will be null. ## Look up a transaction > **Definition** ```shell GET https://api.nihaopay.com/v1.2/transactions/{transaction_id} ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/{transaction_id} \ -H "Authorization: Bearer " ``` Returns details of a previously created transaction. Provide a unique transaction ID that was returned from a previous response in order to retrieve corresponding transaction’s details. Only SecurePay transaction details can be found through this endpoint. For details on Released, Cancelled, and Refunded transactions, please use [TMS](https://tms.nihaopay.com). ### Request `transaction_id` as URL parameter. > **Response** ```json { "id": "bn2345nb53454kjb", "status": "success", "type": "charge", "amount": 1111, "currency": "USD", "time": "2015-01-01T01:01:01Z", "reference": "jkh25jh1348fd89sg", "note": "sample note" } ``` ### Response Returns a transaction object. Property | Description ------- | ----------- **id**
`string` | Transaction ID. **status**
`string` | Transaction status. Either `success`, `failure`, or `pending`. **type**
`string` | Transaction type. Either `charge`, `authorization`, or `capture`. **vendor**
`string` | Payment method. Include: `unionpay`, `alipay`, `wechatpay` or `alipayhk`. **vendor_id**
`string` | Vendor’s transaction id, usually showed on customer’s payment receipt. **amount**
`int` | Amount of the transaction in the minor unit of the currency. For example, cents in USD. **currency**
`string` | The 3-letter currency code. **time**
`string` | Timestamp of the transaction in UTC. Ex: `2015-01-01T01:01:00Z` is Jan 1, 2015 1:01:00 UTC. **reference**
`string` | AlphaNumeric string set in request to correspond transaction ID with your original transaction request. **note**
`string/null` | If set in request, your transaction note to self. Else if not set, this will be null. ## Refund a transaction > **Definition** ```shell POST https://api.nihaopay.com/v1.2/transactions/refund/{transaction_id} ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/refund/{transaction_id} \ -H "Authorization: Bearer " \ -d amount=100 \ -d currency="USD" \ -d reference="refund-001" \ -d ipn_url="https://merchant.example.com/refund-ipn" ``` To issue a full or partial refund, you must create a Refund Object based on an existing transaction. Full refunds can only be created once per transaction by specifying amount as the full amount of the transaction. Partial refunds can be created multiple times untill total refund amount reaches amount of the Transaction. You cannot refund more than the amount of the original transaction. PayPal refunds, including PayPal Crypto refunds, may be processed asynchronously. When `ipn_url` is provided, the synchronous response may return `status=pending` and `refunded=false`. Use the subsequent refund IPN or Refund Query status as the final result. Existing requests without `ipn_url` retain their original synchronous-success response behavior. ### Request `transaction_id` as URL Parameter. Property | Description -------- | ----------- **currency**
`Required`| The 3-letter currency code. Currency must match the original transaction's currency. **amount**
`Conditional` | Amount to be funded in the minor unit of the currency.
Must be equal to or less than the amount of the original transaction. **rmb_amount**
`Conditional` | If original transaction Amount as a positive integer of the minor unit of the currency. Use this parameter to replace amount if merchant wish to price their product in RMB. If amount is used, rmb_amount should not be set. They are mutual exclusive. See [Parameters Description](./apirule#parameters-description). **reason**
`Optional`|Arbitrary string detailing the reason for refund. **reference**
`Optional` | Merchant refund reference. Use a unique value for each refund to support merchant-side idempotency; it cannot be reused by the same merchant. **ipn_url**
`Optional` | URL that receives asynchronous refund notifications. PayPal asynchronous refunds require this field to return `pending` and receive subsequent refund IPNs. > **Response** ```json { "id": "bn2345nb53454kjb", "status": "success", "refunded": true, "transaction_id": "jkh25jh1348fd89sg" } ``` > **Asynchronous Refund Response (PayPal with `ipn_url`)** ```json { "id": "20260910114323034765", "status": "pending", "refunded": false, "transaction_id": "20260910114042101626" } ``` ### Response Returns a refund object. Property|Description ---------|----------- **id**
`string`|Refund ID. **status**
`string`| Refund status: `success`, `failed`, or `pending`. `pending` is returned only for PayPal refunds when the request includes `ipn_url`. **refunded**
`bool` | Whether the refund completed successfully. `true` for `status=success`; `false` for `status=pending`. **transaction_id**
`string`|ID of the transaction that was refunded. ### Refund IPN For PayPal asynchronous refunds with an `ipn_url`, NihaoPay sends refund status notifications to this URL using HTTP POST. A notification may contain `pending` and will be sent again when the status changes to `success` or `failed`. Use the refund transaction ID `id` together with the status for idempotent processing. The signature follows the [Instant Payment Notification](./apirule#instant-payment-notification) rules. Return HTTP 200 after successfully processing the notification. > **Refund IPN Example** ```shell id = 20260910114323034765 status = success currency = USD amount = 100 time = 2026-09-10T11:45:12Z reference = refund-001 verify_sign = ``` Property | Description ------- | ----------- **id**
`string` | NihaoPay refund transaction ID. **status**
`string` | Refund status: `pending`, `success`, or `failed`. **currency**
`string` | Original payment transaction currency. **amount**
`int` | Refund amount in the minor unit of the currency. **time**
`string` | Notification creation time in UTC. **reference**
`string` | Merchant refund reference from the refund request. **verify_sign**
`string` | Notification signature. ## Refund Query ```shell GET https://api.nihaopay.com/v1.2/transactions/refunds/{transaction_id}/ ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/refunds/{transaction_id}/ \ -H "Authorization: Bearer " ``` ### Request `transaction_id` Original transaction ID as URL parameter. > **Response** ```json { "note": null, "amount": 2, "type": "charge", "refunded_amount": 2, "refunds": [ { "refund_time": "2021-11-29T05:42:33Z", "refund_id": "20211129054233008405", "refunded_amount": 1, "status": "success" }, { "refund_time": "2021-11-29T05:41:55Z", "refund_id": "20211129054155008404", "refunded_amount": 1, "status": "success" } ], "reference": "20211129134105329326", "vendor": "unionpay", "vendor_id": "512111291341178330258", "currency": "USD", "id": "20211129054117043676", "time": "2021-11-29T05:41:17Z", "status": "success" } ``` ### Response Property | Description ------- | ----------- **id**
`string` | Transaction ID. **status**
`string` | Transaction status. Either `success`, `failure`, `pending` or `closed` **type**
`string` | Transaction type. Either `charge`, `authorization`, or `capture`. **amount**
`int` | Amount of the transaction in the minor unit of the currency. For example, cents in USD. **currency**
`string` | Transaction currency. **time**
`string` | Timestamp of the transaction in UTC. **reference**
`string` | Merchant order number. **note**
`string` | If set in request, your transaction note to self. Else if not set, this will be null. **vendor**
`string` | Payment method. Include: `unionpay`, `alipay`, `wechatpay` or `alipayhk`. **vendor_id**
`string` | Vendor’s transaction id, usually showed on customer’s payment receipt. **refunded_amount**
`int` | Total refunded amount **refunds**
`list` | Refund records **refund_time**
`string` | Refund time **refund_id**
`string` | Refund ID. **refunded_amount**
`int` | refund amount **status**
`string` | Refund status: `success`, `failed`, or `pending`. ## List transactions > **Definition** ```shell GET https://api.nihaopay.com/v1.2/transactions/ ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/transactions/?starting_after=2015-01-01T01:01:00Z \ -H "Authorization: Bearer " ``` Returns a list of previously created transactions. Transactions are returned with the most recent transactions appearing first. By default, only 10 transactions are returned at a time. This can be adjusted by providing a `limit` argument. Only SecurePay transactions can be returned. For details on Released, Cancelled, and Refunded transactions, please use [TMS](https://tms.nihaopay.com). By providing `starting_after` argument, you can retrieve transactions that were processed after the specified time. By providing `ending_before` argument, you can retrieve transactions that were processed before the specified time. By providing both, `starting_after` and `ending_before` arguments, you can retrieve transactions that were processed within the specified range. ### Request Properties as URL GET parameters. Property | Description -------- | ----------- **limit**
`Optional`
Default: 10|Number of transactions returned for each request. Limit can range between 1 and 100. **starting_after**
`Optional`|Time in UTC format yyyy-mm-ddThh:mm:ssZ. Used to retrieve transactions processed after the specified time. **ending_before**
`Optional`|Time in UTC format yyyy-mm-ddThh:mm:ssZ. Used to retrieve transactions processed before the specified time. > **Response** ```json { "transactions": [ { "id": "bn2345nb53454kjb", "status": "success", "type": "charge", "amount": 1111, "currency": "USD", "time": "2015-01-01T01:05:0Z", "reference": "jkh25jh1348fd89sg", "note": "sample note" }, { "id": "16zfmK2eZvKYlo2C6X3", "status": "success", "type": "authorization", "amount": 1111, "currency": "USD", "time": "2015-01-01T01:01:01Z", "reference": "6LJDMbC6Ybqlt7fd", "note": "sample note" } ] } ``` ### Response Returns a transactions array of transaction objects. If no transactions are available, returns an empty array. Property | Description ------- | ----------- **id**
`string` | Transaction ID. **status**
`string` | Transaction status. Either `success`, `failure`, or `pending`. **type**
`string` | Transaction type. Either `charge`, `authorization`, or `capture`. **amount**
`int` | Amount of the transaction in the minor unit of the currency. For example, cents in USD. **currency**
`string` | The 3-letter currency code. **time**
`string` | Timestamp of the transaction in UTC. Ex: `2015-01-01T01:01:00Z` is Jan 1, 2015 1:01:00 UTC. **reference**
`string` | AlphaNumeric string set in request to correspond transaction ID with your original transaction request. **note**
`string/null` | If set in request, your transaction note to self. Else if not set, this will be null. ## Query exchange rate ```shell GET https://api.nihaopay.com/v1.2/exchangerate ``` Exchange rate updates 10:30am China Standard Time(UTC+8), once a day (Frequency limit: 1 time per minute, it is recommended to query only once a day). > **Response** ```shell $ curl https://api.nihaopay.com/v1.2/exchangerate/?rate_date=20170308¤cy=USD \ -H "Authorization: Bearer " ``` ### Request Properties as URL GET parameters. Property | Description -------- | ----------- **rate_date**
`Required`| Rate date, formatted as YYYYMMDD **currency**
`Required`| Foreign currency,acceptable are `USD`, `JPY`, `HKD`, `GBP`,`EUR` **vendor**
`Optional`| Vendor, acceptable are `alipay`, `wechatpay`, `unionpay` > **Response** ```json { "rates": [ { "rate_date": "20170308", "currency": "usd", "vendor": "unionpay", "rate": "6.948700" }, { "rate_date": "20170308", "currency": "usd", "vendor": "alipay", "rate": "6.921791" }, { "rate_date": "20170308", "currency": "usd", "vendor": "wechatpay", "rate": "6.921911" } ] } ``` ### Response Returns exchange rate list. Property | Description -------- | ----------- **rate_date**
`string`| Rate date, formatted as YYYYMMDD **currency**
`string`| Foreign currency **vendor**
`string`| `alipay`, `wechatpay` or `unionpay` **rate**
`string`| Foreign currency to Renminbi(RMB) exchange rate ## Download transactions ```shell GET https://api.nihaopay.com/v1.2/download/transactions ``` This interface enables the merchants to download the transaction list in a specific time span to reconcile transactions. > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/download/transactions/?start_date=20170101&end_date=20170105 \ -H "Authorization: Bearer " ``` ### Request Properties as URL GET parameters. Note: The starting and end dates should be within a 10-day interval. Property | Description -------- | ----------- **start_date**
`Required`| The start date, formatted as YYYYMMDD **end_date**
`Required`| The end date , formatted as YYYYMMDD ### Response Currently the interface only supports .CSV file to be downloaded. ## Download billing file ```shell GET https://api.nihaopay.com/v1.2/billing ``` This interface enables the merchants to download the transaction list in a specific time span to reconcile the transactions. Closed, failed or cancelled transactions do not appear in the download file. > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/billing/?start_date=20170101&end_date=20170105 \ -H "Authorization: Bearer " ``` ### Request Properties as URL GET parameters. Note: The starting and end dates should be within a 10-day interval. Property | Description -------- | ----------- **start_date**
`Required`| The start date, formatted as YYYYMMDD **end_date**
`Required`| The end date , formatted as YYYYMMDD ### Response Currently the interface only supports .CSV file to be downloaded. # Account / Withdrawal ## Inquiry account balance ```shell GET https://api.nihaopay.com/v1.2/accounts ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/accounts \ -H "Authorization: Bearer " ``` ### Request Properties as URL GET parameters. > **Response** ```json { "accounts": [ { "balance": "100.00", "currency": "USD", "pending_amount": "12.40", "freeze_amount": "0.00" } ] } ``` ### Response Returns merchant account object. Property | Description ------- | ----------- **currency**
`string` | Account currency **balance**
`string` | Currently account balance **pending_amount**
`string` | Currently unsettled purchase amount **freeze_amount**
`string` | Currently unsettled refund amount ## Inquiry withdrawal history ```shell GET https://api.nihaopay.com/v1.2/withdrawal/history ``` > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/withdrawal/history/?start_date=20170101&end_date=20170105 \ -H "Authorization: Bearer " ``` ### Request Properties as URL GET parameters. Property | Description -------- | ----------- **start_date**
`Required`| Start date, formatted as YYYYMMDD. **end_date**
`Required`| End date, formatted as YYYYMMDD. > **Response** ```json { "withdrawal": [ { "id": "bn2345nb53454kjb", "status": "completed", "amount": "100.00", "currency": "USD", "fee": "0.30", "fee_currency":"USD", "date": "20170101" } ] } ``` ### Response Return an array of withdrawal object. If no transactions are available, returns an empty array. Property | Description ------- | ----------- **id**
`string` | NihaoPay withdrawal ID **status**
`string` | Withdrawal status. Included `processing` and `completed`. **amount**
`int` | Withdrawal amount **currency**
`string` | Withdrawal currency **fee**
`string` | Withdrawal fee **fee_currency**
`string` | Withdrawal fee currency type. **date**
`string` | Withdrawal date, formatted as YYYYMMDD ## Withdrawal Details ```shell GET https://api.nihaopay.com/v1.2/withdrawal/detail/{withdrawal_id} ``` According to the withdrawal_id to get the corresponding data > **Request** ```shell $ curl https://api.nihaopay.com/v1.2/withdrawal/detail/{withdrawal_id} \ -H "Authorization: Bearer " ``` ### Request `withdrawal_id` : ID generated by 'Apply Withdrawal' request, and send this ID as parameter. ### Resonse Convert return data to a CSV file which conclude all the data. # Testing > **Testing Endpoint** ```shell https://apitest.nihaopay.com ``` We have two environments for our API: Testing and Production. These two environments and their endpoints are identical, with the exception that no real money is transferred in the Testing environment. You can use the Testing endpoints as substitutes for the Production endpoints during integration. For example, transactions in the Testing environment would be: `https://apitest.nihaopay.com/v1.2/transactions` To access the [TMS](https://tms.nihaopay.com) for transactions processed in the testing environment, please use the [Testing TMS](http://betatms.aurfy.com). While using the Testing environment, bank issued cards cannot be used. We provide test credentials for you to use to simulate transactions. **To start testing, apply for a test account [here](https://www.nihaopay.com/apply)** ## UnionPay Test Cards While using the Testing environment, bank issued cards will not work. We provide Test Cards below for you to use to simulate transactions. ### UnionPay Credit Card 1 | | | |---|---| Card Number | 6250 9470 0000 0014 CVV | 123 EXP | 12/2033 Phone # | 852-11112222 Verification Code | 111111 ### UnionPay Debit Card | | | |---|---| Card Number | 6226 0900 0000 0048 PIN | 123456 Phone # | 1810000000 Verification Code | 111111 ## Alipay Test Accounts We do not provide Alipay test accounts; however, you may use your real Alipay account to simulate transactions. If the payment is successful, please call [Refund](./manage#refund-a-transaction) to get your money back. ## WechatPay Test Info We do not provide Wechat Test accounts; however, you may use your real Wechat account to simulate transactions. If the payment is successful, please call [Refund](./manage#refund-a-transaction) to get your money back. ## PayPal Test Account | | | |---|---| Account | sb-s47aho8657191@personal.example.com Login Password | J^Fby/5@ ### PayPal ACDC Test Card The following card details are provided in the NihaoPay PayPal ACDC merchant guide. Use them only in the NihaoPay/PayPal testing environment; do not use them in production. | | | |---|---| Card Number | 4111 1111 1111 1111 EXP | 12/35 CVV | 123 PayPal's current [sandbox card testing guide](https://developer.paypal.com/sandbox-testing/card-testing) lists other static test card numbers and a card generator. If this NihaoPay ACDC test card is not accepted in your sandbox setup, use a test card from PayPal's guide. # Errors > **Error** ```json { "code": 409, "label": "64", "message": "Refund or capture currency does not match the original transaction currency." } ``` When an API request fails, NihaoPay will return an error object. NihaoPay errors follow conventional HTTP status codes. A `2xx` code indicates request success; therefore, you will not see any of these codes in the error object. A `4xx` code indicates an error in the information provided. These could be anything from a malformed request, an unauthenticated request, or an unknown endpoint. A `5xx` code indicates NihaoPay’s internal server error. There are certain features that are not yet available but are documented in this API Reference. Requesting those features from the API will result in a `501` error. Feel free to contact our tech support team at tech_support@nihaopay.com if you encounter errors. ## Error Object Property|Description ---------|----------- **code**
`int`|HTTP status code. **label**
`string`|Label of the error generated by NihaoPay. Support team may ask for this to help with integration questions. **message**
`string`|A human readable message as to the cause of the encountered error. ## Error List code|label|message -------|-------|----------- 200|00| Success 402|01| Transaction failed. Please try again. 402|02| Cardholder input an incorrect card number. 402|03| Cardholder\'s issuing bank prevented the transaction. 402|06| Customer input an expired card number. 402|11| Customer has insufficient funds available. 402|14| Cardholder input an incorrect expiration date. 402|15| Cardholder authentication failed. Please verify cardholder\'s information. 402|21| Cardholder authentication failed. Please verify cardholder\'s information. 402|22| Card state is incorrect. 402|30| The amount exceeds transaction limit placed. 400|31| Transaction reference number must be unique. Please re-submit. 400|32| This payment channel is restricted. Please contact NihaoPay customer service. 409|33| Transaction failed. Information submitted in a repeat transaction must match the original attempted transaction exactly. 402|36| Transaction exceeds the cardholder\'s credit limit. 429|39| Too many transactions attempts by cardholder. 402|56| Cardholder\'s chosen payment card is not supported in this Gateway. 402|57| Cardholder has not activated online payments with their issuing bank. 404|59| Failed. Transaction have refund or chargeback. 404|60| Transaction has been cleared, please request refund. 402|61| Transaction not found. 402|62| Transaction is not within the acceptance time range. 402|63| The original transaction failed. You cannot refund, cancel, capture, or release an unsuccessful transaction. 409|64| Refund or capture currency does not match the original transaction currency. 409|65| Transaction has previously been cancelled. 409|66| Failed to refund transaction. Transaction has previously been fully refunded. 402|67| Failed to refund transaction. Refund amount exceeds original transaction amount or remaining transaction balance . 402|68| Failed to capture transaction. Transaction has previously been released. 402|69| Failed to capture transaction. Transaction has previously been captured. 402|70| Failed to capture transaction. Capture amount exceeds authorization amount. 402|71| Buyer not exist or buyer account info error 402|72| Transaction amount is exceed the limit 500|81| Merchant config error 500|82| Merchant unavailable 500|83| QRcode has expired 500|84| Service is not activated for this account 402|86| Withdrawal amount exceeds account balance 402|87| Withdrawal amount less than the minimum withdrawal amount 402|88| Invalid application, it's only available for manually withdrawal merchant 400|90| The field not valid. 500|91| Signature error 500|92| The {0} field is required. 404|93| The Exchange rate not found. 500|96| Timeout 500|97| Inner error 500|98| Vendor error 500|99| System error 401|301| Invalid merchant credentials provided # API Change Log ### 2026-11-17 * Profit sharing rule updates: sharing currency must equal the settlement currency; the recipient needs a settlement account in that currency; only self-collected channels are supported; global and order profit sharing cannot be stacked; cancel is not allowed 15:00-18:00 UTC; format validation for reference/remark/notifyUrl; partial reversals return fees proportionally. Add the delegated merchants query, and correct the query, execution result and callback examples. ### 2026-09-15 * Add PayPal Crypto to SecurePay with `vendor=paypal` and `payment_source=crypto`. * Add `ipn_url` asynchronous refund notifications for PayPal, including Crypto. Refunds in progress return `pending`; use the refund IPN or Refund Query for the final status. ### 2025-01-16 * add autodebit api ### 2023-08-23 * SecurePay supports returning data in json format ### 2023-08-05 * Add Profit Sharing Interface [ProfitSharing](./sharing#profit-sharing) ### 2022-07-18 * Add interface [Alipay A+](./securepay#alipay-a) ### 2020-09-01 * Update currencies list * Support UnionPay customs declaration ### 2018-06-01 * Add customs declaration * Add vendor's transaction in IPN ### 2018-05-17 * In-App payment support WeChatPay. * Scan QRcode support UnionPay QRcode, U.S. merchants only. ### 2018-03-15 * Add interface `Static Omni-Channel QRcode` * Add interface `Static AliPay QRcode` ### 2017-11-10 * Add interface `WeChat Mini-program payment` ### 2017-08-21 * Add interface `Download transactions` * Add interface `Static QRcode` * Add interface `Inquiry account balance` * Add interface `Apply withdrawal` * Add interface `Inquiry withdrawal history` ### 2017-05-25 * Add In-Store Payment API * Add In-App Payment API * Add verify signature in IPN notification * Change IPN notification frequency ### 2017-04-10 * Update Error list * Add parameter `rmb_amount` in SecurePay and ExpressPay request field list. ### 2017-03-07 * Add Chinese document * Add parameter `client_ip` in ExpressPay request field list * Add interface `Query Exchange Rate` * Add interface `Download Billing` ### 2017-01-01 * Upgrade to `v1.2`