# Authentication

> Sign every request with HMAC-SHA256, and verify every response and notification the same way.

## Authentication

All merchant-initiated requests to HansaPay must include these headers:

- `X-MerchantID`
- `X-Timestamp`
- `X-Nonce`
- `X-Sign`

Signature algorithm:

- `HMAC-SHA256`
- Output format: lowercase hex string

## Encoding and Request Format

- HTTP method: `POST`
- Content-Type: `application/json`
- The request body must be included in the signature
- Use the raw JSON body bytes when signing
- Do not prettify, trim, or reorder JSON fields before verifying

## Request Signing Rules

### String to Sign

HansaPay verifies signatures using:

```text
merchantID + "\n" + timestamp + "\n" + nonce + "\n" + rawBody
```

Example:

```text
M123456
1719200000
8f31a2bc9d4e6f70
{"payment_method":"CARD","merchant_order_no":"M202406240001","trans_amount":{"currency":"USD","value":"99.99"},"notify_url":"https://merchant.example.com/callback/payment","trade_info":{"goods_name":"VIP","description":"Monthly subscription"},"card":{"card_number":"4111111111111111","cardholder_name":"JOHN DOE","exp_month":12,"exp_year":2028,"cvc":"123"},"billing_address":{"country":"US","first_name":"John","last_name":"Doe","email":"john@example.com","phone":"15551234567","state":"CA","city":"San Francisco","address":"Market Street","street_number":"1355","postal_code":"94103"},"device_ip":"203.0.113.10","metadata":"biz=member"}
```

### Signature Calculation

Pseudo-code:

```text
sign = hex_lower( HMAC_SHA256(secret_key, sign_payload) )
```

Where:

- `merchantID`: merchant ID assigned by HansaPay
- `secret_key`: merchant API secret assigned by HansaPay
- `timestamp`: Unix timestamp in seconds
- `nonce`: random string, recommended length 16 to 32
- `rawBody`: raw HTTP request body string

### Java Example

```java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class SignDemo {
    public static String hmacSha256Hex(String data, String secret) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        mac.init(keySpec);
        byte[] raw = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte b : raw) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static void main(String[] args) throws Exception {
        String merchantId = "M123456";
        String timestamp = "1719200000";
        String nonce = "8f31a2bc9d4e6f70";
        String rawBody = "{\"order_no\":\"O202406240001\"}";
        String secret = "your_merchant_secret";

        String payload = merchantId + "\n" + timestamp + "\n" + nonce + "\n" + rawBody;
        String sign = hmacSha256Hex(payload, secret);
        System.out.println(sign);
    }
}
```

### PHP Example

```php
<?php

$merchantId = 'M123456';
$timestamp = '1719200000';
$nonce = '8f31a2bc9d4e6f70';
$rawBody = '{"order_no":"O202406240001"}';
$secret = 'your_merchant_secret';

$payload = $merchantId . "\n" . $timestamp . "\n" . $nonce . "\n" . $rawBody;
$sign = hash_hmac('sha256', $payload, $secret);

echo $sign . PHP_EOL;
```

### Go Example

```go
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
)

func main() {
	merchantID := "M123456"
	timestamp := "1719200000"
	nonce := "8f31a2bc9d4e6f70"
	rawBody := `{"order_no":"O202406240001"}`
	secret := "your_merchant_secret"

	payload := merchantID + "\n" + timestamp + "\n" + nonce + "\n" + rawBody
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(payload))
	sign := hex.EncodeToString(mac.Sum(nil))

	fmt.Println(sign)
}
```

### Example Headers

```http
POST /api/v1/payments/query HTTP/1.1
Host: api.example.com
Content-Type: application/json
X-MerchantID: M123456
X-Timestamp: 1719200000
X-Nonce: 8f31a2bc9d4e6f70
X-Sign: 7f7d6e3d2baf9b9bd0e4d8d9a5d2c8d9f7c4e1a2b3c4d5e6f708091011121314
```

## Verifying HansaPay System Responses

Merchants should also verify signatures on HansaPay responses. Response headers use the same keys:

- `X-MerchantID`
- `X-Timestamp`
- `X-Nonce`
- `X-Sign`

Verification rule:

```text
merchantID + "\n" + timestamp + "\n" + nonce + "\n" + rawResponseBody
```

Notes:

- The response body must also be verified using the raw body string
- Do not deserialize and reserialize before verification
- If verification fails, the response should be treated as untrusted
- `401` and `403` authentication errors are not signed

## Signature Troubleshooting Checklist

When HansaPay returns the following errors, check the signing chain first:

- `401` with `Missing authentication headers` or `Merchant ID not found or invalid`
- `403` with `Invalid signature`

Recommended troubleshooting order:

### Is the Merchant ID Correct

- `X-MerchantID` must be the merchant ID assigned by HansaPay
- Do not send merchant name, login account, or internal user ID

### Is the Secret Correct

- Make sure you are using the merchant API secret, not the login password
- Make sure you are not mixing environments
- Test and production secrets are usually different

### Is the String to Sign Exactly the Same

HansaPay always verifies:

```text
merchantID + "\n" + timestamp + "\n" + nonce + "\n" + rawBody
```

Common mistakes:

- Missing line breaks
- Using `\r\n` instead of `\n`
- Wrong header order
- Trimming body content
- Signing a reserialized object instead of the raw body

### Are the JSON Field Names Correct

The merchant API uses snake_case, for example:

- `payment_method`
- `merchant_order_no`
- `notify_url`
- `trade_info.goods_name`

Do not mix old-style names such as:

- `paymentMethod`
- `merchantOrderNo`
- `goodsName`

### Was the JSON Reformatted

The signature must be based on the exact request body sent over the wire.

These two JSON payloads are business-equivalent but produce different signatures:

```json
{"order_no":"O1","status":"SUCCESS"}
```

```json
{
  "order_no": "O1",
  "status": "SUCCESS"
}
```

Therefore:

- Build the final request body first
- Sign that final body
- Do not modify spaces, indentation, or field order after signing

### Is the Timestamp Valid

- `X-Timestamp` must be a Unix timestamp in seconds
- Do not send milliseconds
- Do not send a formatted datetime string
- HansaPay may refuse a request whose `X-Timestamp` is more than a few minutes from the current time, with HTTP `401` and `Request expired`. Keep your server clock synchronised (NTP) and sign each request just before sending it
- Under the same check an `X-Nonce` can be used only once: a request sent again with the same nonce is refused with HTTP `401`. Sign every retry again with a new nonce

Valid example:

```text
1719200000
```

Invalid examples:

```text
1719200000123
2026-06-24T10:00:00+08:00
```

### Is `nonce` Empty

- `X-Nonce` must not be empty
- Recommended length: 16 to 32 random characters, at most 128
- Use a new nonce for every request, including retries (see [Is the Timestamp Valid](https://www.hansapay.io/docs/authentication#is-the-timestamp-valid))

### Is the HMAC Output Format Correct

HansaPay expects:

- Algorithm: `HMAC-SHA256`
- Output: lowercase hex string

Do not use:

- Base64
- Uppercase hex
- MD5
- RSA

### Is the Content-Type Correct

Use:

```text
Content-Type: application/json
```

### Suggested Logs When Verification Fails

Recommended local logs:

- `merchant_id`
- `timestamp`
- `nonce`
- `raw_body`
- `sign_payload`
- `received_sign`
- `expected_sign`

This is the fastest way to determine whether the issue comes from headers, body formatting, or the secret.

### Amount Limit Troubleshooting

If HansaPay returns:

- `2006`: collection amount does not satisfy channel limits
- `5008`: payout amount does not satisfy channel limits

Check:

1. Whether `trans_amount.value` is below the current minimum allowed by the available channel
2. Whether `trans_amount.value` is above the current maximum allowed by the available channel
3. Whether all enabled channels for the current payment method reject that amount
4. These errors are not signature-related, so `X-Sign` usually does not need investigation
