import { createHash, createHmac, randomUUID } from 'node:crypto'
const BASE = process.env.HUAY_BASE_URL // ได้จากทีม HuayEngine
const API_KEY = process.env.HUAY_API_KEY
const SECRET = process.env.HUAY_HMAC_SECRET
// canonical v2 → HMAC-SHA256 → hex ตัวพิมพ์เล็ก
export function sign(method, target, timestamp, requestId, idempotencyKey, rawBody) {
const quoted = [method, target, timestamp, requestId, idempotencyKey].map(v => JSON.stringify(v))
const digest = createHash('sha256').update(rawBody).digest('hex')
const canonical = ['huayengine-provider-v2', ...quoted, digest].join('\n')
return createHmac('sha256', SECRET).update(canonical).digest('hex')
}
export async function call(method, target, { body, idempotencyKey = '' } = {}) {
const rawBody = body === undefined ? '' : JSON.stringify(body) // แปลงครั้งเดียว ใช้ทั้งเซ็นและส่ง
const requestId = randomUUID() // ใหม่ทุกครั้ง แม้เป็นการ retry
const timestamp = new Date().toISOString() // RFC3339 UTC
const headers = {
'X-Api-Key': API_KEY,
'X-Request-Id': requestId,
'X-Timestamp': timestamp,
'X-Signature': sign(method, target, timestamp, requestId, idempotencyKey, rawBody),
}
if (rawBody) headers['Content-Type'] = 'application/json'
if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey
const res = await fetch(BASE + target, {
method, headers, body: rawBody || undefined, redirect: 'manual', signal: AbortSignal.timeout(8000),
})
const env = await res.json().catch(() => ({}))
if (!res.ok || env.error) {
const err = new Error(`HTTP ${res.status} ${env.error?.code ?? 'unknown'}`)
Object.assign(err, { status: res.status, code: env.error?.code, requestId: env.request_id ?? requestId })
throw err
}
return env.data
}
const games = await call('GET', '/api/v1/provider/games')
import hashlib, hmac, json, os, uuid
from datetime import datetime, timezone
import requests
BASE = os.environ["HUAY_BASE_URL"] # ได้จากทีม HuayEngine
API_KEY = os.environ["HUAY_API_KEY"]
SECRET = os.environ["HUAY_HMAC_SECRET"].encode()
def sign(method, target, timestamp, request_id, idem_key, raw_body: bytes) -> str:
quoted = [json.dumps(v) for v in (method, target, timestamp, request_id, idem_key)]
digest = hashlib.sha256(raw_body).hexdigest()
canonical = "\n".join(["huayengine-provider-v2", *quoted, digest])
return hmac.new(SECRET, canonical.encode(), hashlib.sha256).hexdigest()
def call(method, target, body=None, idem_key=""):
# แปลงครั้งเดียว ใช้ทั้งเซ็นและส่ง
raw = b"" if body is None else json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode()
request_id = str(uuid.uuid4())
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
headers = {
"X-Api-Key": API_KEY,
"X-Request-Id": request_id,
"X-Timestamp": timestamp,
"X-Signature": sign(method, target, timestamp, request_id, idem_key, raw),
}
if raw:
headers["Content-Type"] = "application/json"
if idem_key:
headers["Idempotency-Key"] = idem_key
res = requests.request(method, BASE + target, data=raw or None, headers=headers,
timeout=8, allow_redirects=False)
env = res.json()
if res.status_code >= 400 or env.get("error"):
code = (env.get("error") or {}).get("code")
raise RuntimeError(f"HTTP {res.status_code} {code} [req {env.get('request_id')}]")
return env["data"]
games = call("GET", "/api/v1/provider/games")
<?php
define('HUAY_BASE', getenv('HUAY_BASE_URL')); // ได้จากทีม HuayEngine
function huay_sign(string $secret, string $method, string $target, string $ts,
string $requestId, string $idemKey, string $rawBody): string
{
// ★ ต้องมี JSON_UNESCAPED_SLASHES ไม่งั้น "/" กลายเป็น "\/" แล้วลายเซ็นไม่ตรง
$q = fn(string $v): string => json_encode($v, JSON_UNESCAPED_SLASHES);
$canonical = implode("\n", [
'huayengine-provider-v2',
$q($method), $q($target), $q($ts), $q($requestId), $q($idemKey),
hash('sha256', $rawBody),
]);
return hash_hmac('sha256', $canonical, $secret);
}
function huay_call(string $method, string $target, ?array $body = null, string $idemKey = ''): array
{
$secret = getenv('HUAY_HMAC_SECRET');
$raw = $body === null ? '' : json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$requestId = bin2hex(random_bytes(16));
$ts = gmdate('Y-m-d\TH:i:s\Z');
$headers = [
'X-Api-Key: ' . getenv('HUAY_API_KEY'),
'X-Request-Id: ' . $requestId,
'X-Timestamp: ' . $ts,
'X-Signature: ' . huay_sign($secret, $method, $target, $ts, $requestId, $idemKey, $raw),
];
if ($raw !== '') $headers[] = 'Content-Type: application/json';
if ($idemKey !== '') $headers[] = 'Idempotency-Key: ' . $idemKey;
$ch = curl_init(HUAY_BASE . $target);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 8,
CURLOPT_FOLLOWLOCATION => false,
]);
if ($raw !== '') curl_setopt($ch, CURLOPT_POSTFIELDS, $raw);
$res = curl_exec($ch);
if ($res === false) {
throw new RuntimeException('network: ' . curl_error($ch)); // ไม่รู้ผล ห้ามถือว่าล้มเหลว
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
$env = json_decode($res, true) ?? [];
if ($status >= 400 || !empty($env['error'])) {
throw new RuntimeException(sprintf('HTTP %d %s [req %s]',
$status, $env['error']['code'] ?? 'unknown', $env['request_id'] ?? $requestId));
}
return $env['data'];
}
$games = huay_call('GET', '/api/v1/provider/games');
package huay
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
// Base ได้จากทีม HuayEngine
var Base = os.Getenv("HUAY_BASE_URL")
// Sign: %q ของ Go ให้ผลเดียวกับ JSON.stringify สำหรับค่า ASCII
func Sign(secret, method, target, ts, requestID, idemKey string, body []byte) string {
mac := hmac.New(sha256.New, []byte(secret))
fmt.Fprintf(mac, "huayengine-provider-v2\n%q\n%q\n%q\n%q\n%q\n%x",
method, target, ts, requestID, idemKey, sha256.Sum256(body))
return hex.EncodeToString(mac.Sum(nil))
}
var client = &http.Client{
Timeout: 8 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
func Call(apiKey, secret, method, target string, body []byte, idemKey string) (json.RawMessage, error) {
req, err := http.NewRequest(method, Base+target, bytes.NewReader(body))
if err != nil {
return nil, err
}
rid := make([]byte, 16)
if _, err := rand.Read(rid); err != nil {
return nil, err
}
requestID := hex.EncodeToString(rid) // ใหม่ทุกครั้ง แม้เป็นการ retry
ts := time.Now().UTC().Format(time.RFC3339)
req.Header.Set("X-Api-Key", apiKey)
req.Header.Set("X-Request-Id", requestID)
req.Header.Set("X-Timestamp", ts)
req.Header.Set("X-Signature", Sign(secret, method, req.URL.RequestURI(), ts, requestID, idemKey, body))
if len(body) > 0 {
req.Header.Set("Content-Type", "application/json")
}
if idemKey != "" {
req.Header.Set("Idempotency-Key", idemKey)
}
res, err := client.Do(req)
if err != nil {
return nil, err // ไม่รู้ผล ห้ามถือว่าล้มเหลว
}
defer res.Body.Close()
var env struct {
Data json.RawMessage `json:"data"`
Error *struct{ Code, Message string } `json:"error"`
RequestID string `json:"request_id"`
}
if err := json.NewDecoder(res.Body).Decode(&env); err != nil {
return nil, err
}
if res.StatusCode >= 400 || env.Error != nil {
code := ""
if env.Error != nil {
code = env.Error.Code
}
return nil, fmt.Errorf("HTTP %d %s [req %s]", res.StatusCode, code, env.RequestID)
}
return env.Data, nil
}
METHOD=POST
TARGET=/api/v1/provider/members
BODY='{"member_code":"AB000123","wallet_owner_id":7,"wallet_tenant_id":3}'
IDEM='' # route ที่ย้ายเงินต้องใส่ เช่น IDEM=$(uuidgen)
RID=$(uuidgen)
TS=$(date -u +%Y-%m-%dT%H:%M:%SZ)
DIGEST=$(printf '%s' "$BODY" | openssl dgst -sha256 -hex | awk '{print $NF}')
SIG=$(printf 'huayengine-provider-v2\n"%s"\n"%s"\n"%s"\n"%s"\n"%s"\n%s' \
"$METHOD" "$TARGET" "$TS" "$RID" "$IDEM" "$DIGEST" \
| openssl dgst -sha256 -hmac "$HUAY_HMAC_SECRET" -hex | awk '{print $NF}')
curl -s -X "$METHOD" "$HUAY_BASE_URL$TARGET" \
-H "X-Api-Key: $HUAY_API_KEY" -H "X-Request-Id: $RID" \
-H "X-Timestamp: $TS" -H "X-Signature: $SIG" \
-H 'Content-Type: application/json' \
${IDEM:+-H "Idempotency-Key: $IDEM"} \
--data-raw "$BODY"