Implement WHMCS Addon Dashboard with API for stats and integrate billing provider logic
Some checks failed
CI / Node — lint, typecheck, test, build (push) Failing after 10s
CI / Go — node-agent tests (push) Failing after 8s
CI / Go — edge-gateway build (push) Successful in 17s

This commit is contained in:
smueller
2026-06-26 15:11:29 +02:00
parent 15cf302afc
commit 4b20efe4bc
30 changed files with 1414 additions and 16 deletions

View File

@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
final class HexaGameCloudAddonApiClient
{
public function __construct(
private readonly string $baseUrl,
private readonly string $integrationId,
private readonly string $apiSecret,
) {
if ($this->baseUrl === '' || $this->integrationId === '' || $this->apiSecret === '') {
throw new RuntimeException('API URL, integration ID and secret are required');
}
}
public function health(): array
{
return $this->request('GET', '/api/v1/integrations/whmcs/health');
}
public function dashboardStats(): array
{
return $this->request('GET', '/api/v1/integrations/whmcs/dashboard/stats');
}
public function listAccounts(): array
{
return $this->request('GET', '/api/v1/integrations/whmcs/accounts');
}
public function listEvents(?string $cursor = null, int $limit = 50): array
{
$query = $cursor
? ('?cursor=' . rawurlencode($cursor) . '&limit=' . $limit)
: ('?limit=' . $limit);
return $this->request('GET', '/api/v1/integrations/whmcs/events' . $query);
}
public function acknowledgeEvents(array $eventIds, bool $deadLetter = false, ?string $reason = null): array
{
$payload = ['eventIds' => $eventIds, 'deadLetter' => $deadLetter];
if ($reason !== null) {
$payload['deadLetterReason'] = $reason;
}
return $this->request('POST', '/api/v1/integrations/whmcs/events/ack', $payload);
}
public function reconcileAll(array $payload = []): array
{
return $this->request(
'POST',
'/api/v1/integrations/whmcs/reconcile',
$payload,
'reconcile:all:' . date('Y-m-d-His')
);
}
private function request(string $method, string $pathWithQuery, array $body = [], ?string $idempotencySuffix = null): array
{
$pathParts = explode('?', $pathWithQuery, 2);
$path = $pathParts[0];
$canonicalQuery = '';
if (isset($pathParts[1]) && $pathParts[1] !== '') {
parse_str($pathParts[1], $queryParams);
ksort($queryParams);
$pairs = [];
foreach ($queryParams as $key => $value) {
$pairs[] = rawurlencode((string) $key) . '=' . rawurlencode((string) $value);
}
$canonicalQuery = implode('&', $pairs);
}
$bodyJson = $body === [] ? '' : json_encode($body, JSON_THROW_ON_ERROR);
$timestamp = (string) (int) (microtime(true) * 1000);
$nonce = bin2hex(random_bytes(16));
$idempotencyKey = $idempotencySuffix ?: $method . ':' . $path . ':' . $timestamp;
$signatureBase = implode("\n", [
strtoupper($method),
$path,
$canonicalQuery,
hash('sha256', $bodyJson),
$timestamp,
$nonce,
$idempotencyKey,
]);
$signature = hash_hmac('sha256', $signatureBase, $this->apiSecret);
$requestUrl = rtrim($this->baseUrl, '/') . $path . ($canonicalQuery !== '' ? ('?' . $canonicalQuery) : '');
$ch = curl_init($requestUrl);
if ($ch === false) {
throw new RuntimeException('Unable to initialize HTTP client');
}
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Accept: application/json',
'X-HGC-Integration-ID: ' . $this->integrationId,
'X-HGC-Timestamp: ' . $timestamp,
'X-HGC-Nonce: ' . $nonce,
'X-HGC-Idempotency-Key: ' . $idempotencyKey,
'X-HGC-Signature: ' . $signature,
],
CURLOPT_POSTFIELDS => $bodyJson,
]);
$responseBody = curl_exec($ch);
$statusCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($responseBody === false) {
throw new RuntimeException('GameCloud request failed: ' . $curlError);
}
$decoded = json_decode($responseBody, true);
if ($statusCode >= 400) {
$message = is_array($decoded)
? ($decoded['detail'] ?? $decoded['title'] ?? $responseBody)
: $responseBody;
throw new RuntimeException('GameCloud API error (' . $statusCode . '): ' . $message);
}
return is_array($decoded) ? $decoded : [];
}
}

View File

@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
final class HexaGameCloudEventPoller
{
public function __construct(
private readonly HexaGameCloudAddonApiClient $client,
private readonly HexaGameCloudModuleStorage $storage,
private readonly int $limit = 50,
) {
}
public function pollAndAcknowledge(): array
{
$cursor = $this->storage->getSyncCursor();
$response = $this->client->listEvents($cursor, $this->limit);
$events = $response['events'] ?? [];
$ackIds = [];
$stored = 0;
foreach ($events as $event) {
$remoteId = (string) ($event['id'] ?? '');
$eventType = (string) ($event['eventType'] ?? 'unknown');
$payload = is_array($event['payload'] ?? null) ? $event['payload'] : [];
if ($remoteId === '') {
continue;
}
$this->storage->storeRemoteEvent($remoteId, $eventType, $payload);
$stored++;
if ($this->shouldAutoAck($eventType)) {
$ackIds[] = $remoteId;
}
}
if ($ackIds !== []) {
$this->client->acknowledgeEvents($ackIds);
}
if (!empty($response['nextCursor'])) {
$this->storage->updateSyncCursor((string) $response['nextCursor']);
} elseif ($events !== []) {
$last = $events[count($events) - 1];
if (!empty($last['id'])) {
$this->storage->updateSyncCursor((string) $last['id']);
}
}
return [
'fetched' => count($events),
'stored' => $stored,
'acknowledged' => count($ackIds),
'nextCursor' => $response['nextCursor'] ?? null,
];
}
private function shouldAutoAck(string $eventType): bool
{
return in_array($eventType, ['usage_period_ready', 'usage_period_closed'], true);
}
}

View File

@@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
use WHMCS\Database\Capsule;
final class HexaGameCloudModuleStorage
{
public function recordOperation(string $operation, string $status, array $metadata = []): void
{
Capsule::table('mod_hexagamecloud_operations')->insert([
'operation' => $operation,
'status' => $status,
'metadata' => json_encode($metadata, JSON_THROW_ON_ERROR),
'created_at' => gmdate('Y-m-d H:i:s'),
]);
}
public function setLastError(string $message): void
{
Capsule::table('mod_hexagamecloud_installations')->updateOrInsert(
['id' => 1],
[
'last_error' => $message,
'updated_at' => gmdate('Y-m-d H:i:s'),
]
);
}
public function getLastError(): ?string
{
$row = Capsule::table('mod_hexagamecloud_installations')->where('id', 1)->first();
return $row?->last_error;
}
public function updateSyncCursor(?string $cursor): void
{
Capsule::table('mod_hexagamecloud_sync_cursors')->updateOrInsert(
['id' => 1],
[
'events_cursor' => $cursor,
'last_poll_at' => gmdate('Y-m-d H:i:s'),
'updated_at' => gmdate('Y-m-d H:i:s'),
]
);
}
public function getSyncCursor(): ?string
{
$row = Capsule::table('mod_hexagamecloud_sync_cursors')->where('id', 1)->first();
return $row?->events_cursor;
}
public function storeRemoteEvent(string $remoteId, string $eventType, array $payload, string $status = 'pending'): void
{
$existing = Capsule::table('mod_hexagamecloud_events')
->where('remote_event_id', $remoteId)
->first();
if ($existing) {
return;
}
Capsule::table('mod_hexagamecloud_events')->insert([
'remote_event_id' => $remoteId,
'event_type' => $eventType,
'payload' => json_encode($payload, JSON_THROW_ON_ERROR),
'status' => $status,
'created_at' => gmdate('Y-m-d H:i:s'),
]);
}
public function listLocalEvents(int $limit = 50): array
{
return Capsule::table('mod_hexagamecloud_events')
->orderBy('id', 'desc')
->limit($limit)
->get()
->map(static fn ($row) => (array) $row)
->all();
}
public function countLocalEventsByStatus(string $status): int
{
return (int) Capsule::table('mod_hexagamecloud_events')->where('status', $status)->count();
}
public function getLocalEvent(int $id): ?array
{
$row = Capsule::table('mod_hexagamecloud_events')->where('id', $id)->first();
return $row ? (array) $row : null;
}
public function updateLocalEventStatus(int $id, string $status): void
{
Capsule::table('mod_hexagamecloud_events')->where('id', $id)->update([
'status' => $status,
'processed_at' => gmdate('Y-m-d H:i:s'),
]);
}
public function saveReconciliationRun(array $result, string $mode): void
{
$issues = $result['issues'] ?? [];
Capsule::table('mod_hexagamecloud_reconciliation')->insert([
'run_id' => (string) ($result['runId'] ?? ''),
'mode' => $mode,
'issue_count' => is_array($issues) ? count($issues) : 0,
'payload' => json_encode($result, JSON_THROW_ON_ERROR),
'created_at' => gmdate('Y-m-d H:i:s'),
]);
}
public function listReconciliationRuns(int $limit = 20): array
{
return Capsule::table('mod_hexagamecloud_reconciliation')
->orderBy('id', 'desc')
->limit($limit)
->get()
->map(static fn ($row) => (array) $row)
->all();
}
}