PHP code example of goal-api / sdk

1. Go to this page and download the library: Download goal-api/sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

goal-api / sdk example snippets


use GoalApi\GoalApi;

$goal = new GoalApi(getenv('GOAL_API_KEY'));

foreach ($goal->fixtures->live()['data'] as $match) {
    printf(
        "%s %d-%d %s\n",
        $match['homeTeam']['name'],
        $match['homeScore'],
        $match['awayScore'],
        $match['awayTeam']['name'],
    );
}

$goal = new GoalApi(
    apiKey: getenv('GOAL_API_KEY'),
    timeout: 15.0,                 // per attempt, seconds; default 30
    maxRetries: 3,                 // 429 + 5xx + network errors; default 2
    headers: ['X-My-App' => 'scoreboard'],
);

$goal = new GoalApi(
    apiKey: $key,
    httpHandler: function (string $method, string $url, array $headers, ?string $body): array {
        $response = $myClient->request($method, $url, [...]);
        return [$response->getStatusCode(), $normalisedHeaders, (string) $response->getBody()];
    },
);

$goal->status->get();                                  // no API key needed
$goal->countries->list(['search' => 'spa']);
$goal->leagues->list(['isActive' => true, 'limit' => 100]);
$goal->leagues->standings($leagueId);
$goal->leagues->topScorers($leagueId, ['limit' => 10]);
$goal->teams->get($teamId, [''half' => '1half']);
$goal->standings->form($leagueId);
$goal->players->search('haaland', ['limit' => 5]);
$goal->players->compare([$playerA, $playerB]);
$goal->players->top('goals', ['limit' => 20]);
$goal->coaches->byTeam($teamId);
$goal->h2h->stats($teamA, $teamB);
$goal->results->today();
$goal->videos->recent(['leagueId' => $leagueId, 'limit' => 10]);
$goal->odds->list(['bookmaker' => 'bet365']);
$goal->predictions->list(['matchId' => $matchId]);

$page = $goal->teams->list(['leagueId' => $leagueId, 'limit' => 50]);
$page['data'];                  // array of teams
$page['pagination']['hasMore']; // bool
$page['source'];                // 'cache' | 'database'

$status = $goal->status->get();
$status['status'];      // 'operational'
$status['components'];  // array of ['name', 'status', 'uptime']

foreach ($goal->paginate(fn (array $p) => $goal->leagues->teams($leagueId, $p)) as $team) {
    echo $team['name'], "\n";
}

// Or collect, with a cap. /results accepts limit up to 500:
$recent = $goal->collect(
    fn (array $p) => $goal->results->list(['leagueId' => $leagueId, ...$p]),
    pageSize: 500,
    maxItems: 500,
);

use GoalApi\Exceptions\{GoalApiException, NotFoundException, RateLimitException, ValidationException};

try {
    $fixture = $goal->fixtures->get($fixtureId);
} catch (NotFoundException) {
    $fixture = null;
} catch (RateLimitException $error) {
    logger()->warning("Quota exhausted ({$error->rateLimitType}), retry in {$error->retryAfter}s");
    throw $error;
} catch (ValidationException $error) {
    logger()->error('Server rejected the request', ['details' => $error->details]);
    throw $error;
} catch (GoalApiException $error) {
    logger()->error($error->getMessage(), [
        'code' => $error->errorCode,
        'correlationId' => $error->correlationId,
    ]);
    throw $error;
}

$goal->fixtures->live();

$quota = $goal->rateLimit();
$quota->remaining;   // ?int
$quota->reset;       // unix seconds
$quota->type;        // 'DAILY' | 'MONTHLY'

$live = $goal->live();

$live->on('match_update', function (array $message) {
    echo $message['data']['id'], PHP_EOL;
});

$live->connect();           // returns once auth_success arrives
$live->subscribe($matchId);
$live->run();               // blocks

$live->connect();
$live->subscribe($matchId);

while (($message = $live->receive(timeout: 1.0)) !== null) {
    // ... your own work between messages
}

// GET /api/live-token  (behind your own auth)
$token = $goal->mintConnectToken();

return response()->json([
    'url' => $goal->webSocketUrl(),   // wss://api.goal-api.com/v1/ws
    'token' => $token['token'],
    'expiresIn' => $token['expiresIn'],
]);

use GoalApi\Webhook;
use GoalApi\Exceptions\WebhookSignatureException;

try {
    $event = Webhook::verify(
        file_get_contents('php://input'),
        $_SERVER[Webhook::SIGNATURE_HEADER] ?? null,
        getenv('GOAL_WEBHOOK_SECRET'),
    );
} catch (WebhookSignatureException) {
    http_response_code(400);
    exit;
}

match ($_SERVER[Webhook::EVENT_HEADER] ?? '') {
    Webhook::EVENT_GOAL_SCORED => handleGoal($event),
    Webhook::EVENT_MATCH_FINISHED => handleFinished($event),
    default => null,
};

http_response_code(200);   // ack fast; retries are ~1m, 5m, 25m, 2h, 10h

$data = $goal->request('/some/new/endpoint', ['limit' => 10]);
bash
GOAL_API_KEY=...        php examples/live-worker.php
GOAL_API_KEY=...        php examples/live-token.php
GOAL_WEBHOOK_SECRET=... php -S localhost:3100 examples/webhook-receiver.php
GOAL_API_KEY=...        php examples/bulk-export.php > countries.csv