> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gate.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> This guide covers the authentication mechanisms, security protocols, request signing, and callback verification required for integrating with the GatePay API.

## API Standards and Protocols

### Transport and Data Format

| Component           | Specification                             |
| ------------------- | ----------------------------------------- |
| Transport Protocol  | HTTPS with TLS 1.2 or above               |
| Data Format         | JSON for both request and response bodies |
| Content-Type Header | `application/json` (required)             |

### Signature and Verification

| Component             | Specification                                                                            |
| --------------------- | ---------------------------------------------------------------------------------------- |
| Signature Algorithm   | HMAC-SHA512                                                                              |
| Request Signing       | All merchant requests must be signed using the HMAC-SHA512 algorithm.                    |
| Callback Verification | All callbacks sent by GatePay must be verified by the merchant using the same algorithm. |

### Response Evaluation

Always evaluate API responses using this process:

1. Check the HTTP status code first
2. Then examine the `status`, `code`, `label`, and `errorMessage` fields in the response body
3. Extract business data from the `data` field if the request was successful

## Unified Response Structure

All GatePay API responses follow this standardized structure:

| Field          | Type                           | Description                                                                        |
| -------------- | ------------------------------ | ---------------------------------------------------------------------------------- |
| `status`       | string                         | Result status: `SUCCESS` indicates successful execution; `FAIL` indicates failure. |
| `code`         | string                         | Error code (empty in successful responses).                                        |
| `label`        | string                         | Error name or identifier (empty in successful responses).                          |
| `errorMessage` | string                         | Human-readable error description (empty in successful responses).                  |
| `data`         | object / array / string / null | Business data returned by the API. Empty in failed responses.                      |

## Request Parameter Standards

### Merchant Order Number (`merchantTradeNo`)

The merchant order number is a unique identifier you assign to each transaction:

| Property       | Specification                                                                                                    |
| -------------- | ---------------------------------------------------------------------------------------------------------------- |
| Character Set  | ASCII half-width characters only: letters (a-z, A-Z), digits (0-9), hyphen (-), underscore (\_)                  |
| Maximum Length | 100 characters                                                                                                   |
| Uniqueness     | Must be unique within your merchant account                                                                      |
| Retry Policy   | When retrying the same business transaction, you must reuse the original `merchantTradeNo` to ensure idempotency |

### Transaction Amount

| Property                     | Specification                             |
| ---------------------------- | ----------------------------------------- |
| Data Type                    | String (numeric value as a string)        |
| Decimal Precision            | Up to 6 decimal places                    |
| Minimum Per Transaction      | 0.0001                                    |
| Maximum Per Transaction      | 5,000,000                                 |
| Maximum QR Collection Amount | 10,000 (for personal QR code collections) |

### Timestamp Format

| Property | Specification                                 |
| -------- | --------------------------------------------- |
| Format   | Unix timestamp in milliseconds (UTC timezone) |

## Request Headers and Signing

### Required Request Headers

Every API request must include these headers:

| Header                           | Description                                                                                                                                                                                                                                                                              |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `X-GatePay-Certificate-ClientId` | Your `ClientId` as assigned when you created your application (see [Integration Overview](/essentials/version/100/en/common/overview)).                                                                                                                                                  |
| `X-GatePay-Timestamp`            | Current UTC timestamp in milliseconds when the request is created. Requests with a time drift greater than 10 seconds will be rejected.                                                                                                                                                  |
| `X-GatePay-Nonce`                | A random string to prevent replay attacks. Recommended length is 32 characters or less, containing only letters and digits.                                                                                                                                                              |
| `X-GatePay-Signature`            | The computed request signature (see Signature Generation steps below).                                                                                                                                                                                                                   |
| `X-GatePay-On-Behalf-Of`         | Institution delegated header. Use it on every institution API except `POST /merchant/open/institution/v1/accounts/create`, `GET /merchant/open/institution/v1/accounts/query`, and `GET /merchant/open/institution/v1/accounts/list`. Ordinary merchant APIs do not include this header. |

### Signature String Format

The signature is computed from a string containing three lines, each ending with a newline character (`\n`):

```
<request_timestamp>\n<request_nonce>\n<request_body>\n
```

Where:

* `<request_timestamp>` is the value of `X-GatePay-Timestamp`
* `<request_nonce>` is the value of `X-GatePay-Nonce`
* `<request_body>` is the raw JSON body of the request, or an empty string if there is no body

### Signature Generation Steps

Follow these steps to compute the `X-GatePay-Signature` header value:

1. Generate a unique `X-GatePay-Timestamp` (current UTC time in milliseconds)
2. Generate a random `X-GatePay-Nonce` (32 characters or less, letters and digits only)
3. Read the raw JSON request body as `request_body`; use an empty string if there is no body
4. Construct the signature string: `timestamp\nnonce\nbody\n`
5. Compute HMAC-SHA512 using your Payment API Secret as the key
6. Encode the result as a hexadecimal string
7. Place the computed signature into the `X-GatePay-Signature` header

### Example Request Structure

The following example is provided only to explain how the signing string is constructed. It is not a complete business-ready request body for a specific endpoint. For actual required fields, always follow the corresponding API Reference page and OpenAPI definition.

```json theme={null}
POST /v1/pay/checkout/order HTTP/1.1
Host: openplatform.gateapi.io
Content-Type: application/json
X-GatePay-Certificate-ClientId: your_client_id
X-GatePay-Timestamp: 1234567890000
X-GatePay-Nonce: abc123def456ghi789
X-GatePay-Signature: <computed_hmac_sha512_hex_signature>

{
  "merchantTradeNo": "order_12345",
  "orderAmount": "100.50",
  "currency": "USD"
}
```

## Payment Result Callbacks

### Callback Overview

GatePay sends asynchronous payment notifications to your configured callback URL via HTTP POST requests. These notifications inform your system of payment status changes.

For comprehensive details on callback events and handling, refer to the [Notification](/essentials/version/100/en/common/notification) guide.

### Callback Payload Structure

The payload below is shown to explain the common callback envelope. The object carried in `data` varies by product and business type, so it should always be read together with the relevant product guide and callback reference.

GatePay will POST a JSON payload with the following structure:

```json theme={null}
{
  "bizType": "TRANSFER_ADDRESS",
  "bizId": "329782527190433792",
  "bizStatus": "TRANSFERRED_ADDRESS_DELAY",
  "client_id": "iVNJZdekOCMJIsmV",
  "data": "{\"merchantTradeNo\":\"1894789022551797760\"}"
}
```

Where:

| Field       | Type   | Description                                                                           |
| ----------- | ------ | ------------------------------------------------------------------------------------- |
| `bizType`   | string | The type of business event (e.g., `TRANSFER_ADDRESS`, `PAYMENT_ORDER`).               |
| `bizId`     | string | The unique identifier for the payment order or business transaction.                  |
| `bizStatus` | string | The current status of the transaction (e.g., `TRANSFERRED_ADDRESS_DELAY`, `SUCCESS`). |
| `client_id` | string | The `client_id` associated with the payment order.                                    |
| `data`      | string | Business-specific data as a JSON string. The structure depends on `bizType`.          |

### Expected Callback Response

Your callback endpoint must respond with a JSON object indicating successful processing:

| Field           | Values              | Description                                                                                      |
| --------------- | ------------------- | ------------------------------------------------------------------------------------------------ |
| `returnCode`    | `SUCCESS` \| `FAIL` | `SUCCESS` indicates the callback was processed successfully; `FAIL` indicates processing failed. |
| `returnMessage` | string              | Human-readable message explaining the result (empty string for success).                         |

**Success Response Example:**

```json theme={null}
{
  "returnCode": "SUCCESS",
  "returnMessage": ""
}
```

**Failure Response Example:**

```json theme={null}
{
  "returnCode": "FAIL",
  "returnMessage": "Database connection failed"
}
```

### Callback Verification Steps

Every callback you receive must be verified to ensure it originated from GatePay and has not been tampered with:

1. Extract the `X-GatePay-Timestamp` header from the incoming callback request
2. Extract the `X-GatePay-Nonce` header from the incoming callback request
3. Extract the `X-GatePay-Signature` header from the incoming callback request
4. Read the raw JSON callback request body
5. Construct the signature string using the format: `timestamp\nnonce\nbody\n`
6. Compute HMAC-SHA512 using your Payment API Secret as the key
7. Compare the computed signature with the `X-GatePay-Signature` header value
8. Only process the callback if the signatures match exactly

**Important:** If the signatures do not match, reject the callback as it may be fraudulent or corrupted.

### Callback Request Headers

When GatePay sends a callback to your endpoint, it includes these headers:

| Header                | Description                                    |
| --------------------- | ---------------------------------------------- |
| `X-GatePay-Timestamp` | The timestamp when GatePay sent the callback.  |
| `X-GatePay-Nonce`     | A random string included in the signature.     |
| `X-GatePay-Signature` | The HMAC-SHA512 signature computed by GatePay. |

## Time Window Clarification

Two different time windows appear in this documentation, and they apply to different scenarios:

| Scenario                            | Time Window             | Meaning                                                                                                                                  |
| ----------------------------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Merchant-initiated API request      | 10 seconds              | GatePay request-acceptance window for the request timestamp. Requests outside this drift may be rejected.                                |
| Merchant-side callback verification | 5 minutes (recommended) | Recommended local anti-replay validation window for incoming callbacks. It is not the same as the platform request-acceptance threshold. |

Read them as follows:

* `10 seconds` applies to requests you send to GatePay.
* `5 minutes` is a recommended merchant-side validation window when verifying callbacks.
* If your security model requires a stricter callback window, you can reduce it as long as normal network delay is still tolerated.

## Tools and Resources

### Signature Verification Tool

GatePay provides an online tool to help you debug and verify signatures during development:

[GatePay Signature Verification Tool](https://www.gate.com/zh/gatepay/public/signUtil)

This tool allows you to:

* Test signature generation with sample data
* Verify computed signatures match expected values
* Debug signature-related integration issues

## Error Handling

For a comprehensive list of error codes and best practices for handling API errors, see the [Error Codes and Best Practices](/essentials/version/100/en/common/error) guide.

## Security Best Practices

1. **Secure Key Storage:** Store your Payment API Secret and Authorization Secret securely on your server. Never expose these secrets in client-side code or version control.

2. **Nonce Uniqueness:** Ensure each request uses a unique nonce to prevent replay attacks.

3. **Timestamp Validation:** Keep merchant-initiated request timestamps within the 10-second acceptance window, and use a local callback-validation window such as 5 minutes for anti-replay checks.

4. **Signature Verification:** Always verify callback signatures before processing any sensitive operations.

5. **HTTPS Only:** All communication with GatePay must use HTTPS with TLS 1.2 or above.

6. **Callback Idempotency:** Design your callback handler to be idempotent, as GatePay may retry callbacks if it does not receive a successful response.

7. **Error Messages:** Do not expose sensitive information (such as keys or internal system details) in error messages returned to the client.

## Related Documentation

* [Integration Overview](/essentials/version/100/en/common/overview) - App configuration and credential setup
* [Notification](/essentials/version/100/en/common/notification) - Detailed callback event handling
* [Error Codes and Best Practices](/essentials/version/100/en/common/error) - Error code reference and troubleshooting
