## 4 API Authentication Overview All merchant APIs (prefix /v1/acquiring) must carry the following headers: | Header | Example | Description | | --- | --- | --- | | Date | Tue, 21 Jan 2025 12:00:00 GMT | GMT format server time | | Authorization | Signature keyId="xxx"... | HMAC signature authentication header | ### 4.2 Signing String The signing string format is as follows: ``` {keyId} {METHOD} {path} date: {GMT_time} ``` Example: ``` merchant-001 POST /v1/acquiring/order date: Tue, 21 Jan 2025 12:00:00 GMT ``` ### 4.3 Signature Calculation Method (HMAC-SHA256) Use the merchant's secret_key to perform HMAC-SHA256 calculation on the signing_string and Base64 encode it: ```python signature = base64.b64encode( hmac.new(secret_key, signing_string.encode(), hashlib.sha256).digest() ).decode() ``` Algorithm definition: ``` signature = Base64( HMAC_SHA256(secret_key, signing_string) ) ``` ### 4.4 Authorization Header Format Complete Authorization Header: ``` Authorization: Signature keyId ="{keyId}", algorithm = "hmac-sha256", headers = "@request-target date",signature = "{signature}" ``` Example: ``` Authorization: Signature keyId = "merchant-001", algorithm = "hmac-sha256", headers= "@request-target date", signature = "F0k29e...=" ``` #### Common Client Examples ##### Python ```python class InfiniClient: def __init__(self, key_id, secret_key, base_url="https://openapi.infini.money"): self.key_id = key_id self.secret_key = secret_key.encode() if isinstance(secret_key, str) else secret_key self.base_url = base_url def _sign_request(self, method, path): gmt_time = datetime.now(timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT') signing_string = f"{self.key_id}\n{method} {path}\ndate: {gmt_time}\n" signature = base64.b64encode( hmac.new(self.secret_key, signing_string.encode(), hashlib.sha256).digest() ).decode() return { "Date": gmt_time, "Authorization": f'Signature keyId="{self.key_id}",algorithm="hmac-sha256",' f'headers="@request-target date",signature="{signature}"' } def request(self, method, path, json=None): headers = self._sign_request(method, path) if json is not None: headers["Content-Type"] = "application/json" response = requests.request(method, f"{self.base_url}{path}", json=json, headers=headers) response.raise_for_status() return response.json() ``` ##### Node.js ```javascript const crypto = require("crypto"); const axios = require("axios"); class InfiniClient { constructor(keyId, secretKey, baseUrl = "https://openapi.infini.money") { this.keyId = keyId; this.secretKey = secretKey; this.baseUrl = baseUrl; } _signRequest(method, path) { const gmtTime = new Date().toUTCString(); const signingString = `${this.keyId}\n` + `${method.toUpperCase()} ${path}\n` + `date: ${gmtTime}\n`; const signature = crypto .createHmac("sha256", this.secretKey) .update(signingString) .digest("base64"); return { "Date": gmtTime, "Authorization": `Signature keyId="${this.keyId}",algorithm="hmac-sha256",headers="@request-target date",signature="${signature}"` }; } async request(method, path, json = null) { const headers = this._signRequest(method, path); if (json !== null) { headers["Content-Type"] = "application/json"; } const resp = await axios({ method, url: `${this.baseUrl}${path}`, data: json, headers, }); return resp.data; } } module.exports = InfiniClient; ``` ##### Golang ```go package infiniclient import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "io" "net/http" "strings" "time" ) type InfiniClient struct { KeyID string SecretKey string BaseURL string Client *http.Client } func NewInfiniClient(keyID, secretKey string, baseURL string) *InfiniClient { if baseURL == "" { baseURL = "https://openapi.infini.money" } return &InfiniClient{ KeyID: keyID, SecretKey: secretKey, BaseURL: baseURL, Client: &http.Client{Timeout: 15 * time.Second}, } } func (c *InfiniClient) signRequest(method, path string) (map[string]string, error) { gmtTime := time.Now().UTC().Format("Mon, 02 Jan 2006 15:04:05 GMT") signingString := fmt.Sprintf( "%s\n%s %s\ndate: %s\n", c.KeyID, strings.ToUpper(method), path, gmtTime, ) mac := hmac.New(sha256.New, []byte(c.SecretKey)) mac.Write([]byte(signingString)) signature := base64.StdEncoding.EncodeToString(mac.Sum(nil)) authHeader := fmt.Sprintf( `Signature keyId="%s",algorithm="hmac-sha256",headers="@request-target date",signature="%s"`, c.KeyID, signature, ) return map[string]string{ "Date": gmtTime, "Authorization": authHeader, }, nil } func (c *InfiniClient) Request(method, path string, payload interface{}) (map[string]interface{}, error) { // Sign headers, err := c.signRequest(method, path) if err != nil { return nil, err } // Encode JSON body if provided var body io.Reader if payload != nil { b, err := json.Marshal(payload) if err != nil { return nil, err } body = bytes.NewBuffer(b) headers["Content-Type"] = "application/json" } // Build request req, err := http.NewRequest(method, c.BaseURL+path, body) if err != nil { return nil, err } // Set headers for k, v := range headers { req.Header.Set(k, v) } // Send resp, err := c.Client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() // Check status if resp.StatusCode < 200 || resp.StatusCode >= 300 { bodyBytes, _ := io.ReadAll(resp.Body) return nil, fmt.Errorf("request failed: %s, body=%s", resp.Status, string(bodyBytes)) } // Decode JSON var data map[string]interface{} if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { return nil, err } return data, nil } ``` ### 4.5 Clock Skew Requirement The Date in the request header must be within **±300 seconds** of the server time; otherwise, it will return: ``` 401 Unauthorized ``` Please ensure the server is synchronized with NTP. ### 4.6 Webhook Signature Verification When Infini pushes order status callbacks to merchants, it includes a signature. Merchants need to verify the signature to confirm the message source is trustworthy and prevent content tampering. Webhook requests contain the following headers: | Header | Description | | --- | --- | | X-Webhook-Timestamp | Unix timestamp | | X-Webhook-Event-Id | Unique event ID | | X-Webhook-Signature | HMAC-SHA256 signature value | #### 4.6.1 Webhook Signing Content Format Signature string format: ``` {timestamp}.{event_id}.{payload_body} ``` Example: ``` 1700000000.1234.{"event":"order.completed", "order_id":"xxx"} ``` Calculation method: ``` expected_signature = HMAC_SHA256(webhook_secret, signing_content) ``` Verify legitimacy: ``` X-Webhook-Signature == expected_signature ``` #### 4.6.2 Webhook Verification Example (Python) ```python @app.route('/webhook', methods=['POST']) def handle_webhook(): signature = request.headers.get('X-Webhook-Signature') timestamp = request.headers.get('X-Webhook-Timestamp') event_id = request.headers.get('X-Webhook-Event-Id') if not all([signature, timestamp, event_id]): return {"error": "Missing required headers"}, 400 payload = request.get_data(as_text=True) signed_content = f"{timestamp}.{event_id}.{payload}" expected_sig = hmac.new( WEBHOOK_SECRET.encode(), signed_content.encode(), hashlib.sha256 ).hexdigest() if expected_sig != signature: return {"error": "Invalid signature"}, 401 # Process webhook payload return {"status": "ok"} ``` ### 4.7 Security Best Practices - Private key (secret_key) is only displayed once and should be backed up immediately and securely. - Secret Key must not be exposed in web pages, JS, Apps, or public repositories. - It is recommended to use KMS / Secret Manager to manage keys. - IP whitelist can be enabled when creating keys to restrict access sources. - Webhook callbacks must use HTTPS. - Regular key rotation is recommended.