PHP code example of mcore-services / teamleader-sdk

1. Go to this page and download the library: Download mcore-services/teamleader-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/ */

    

mcore-services / teamleader-sdk example snippets


// routes/web.php
use Illuminate\Http\Request;
use McoreServices\TeamleaderSDK\Facades\Teamleader;

Route::get('/teamleader/connect', function () {
    return Teamleader::authorize();
});

Route::get('/teamleader/callback', function (Request $request) {
    if (Teamleader::handleCallback($request->query('code'), $request->query('state'))) {
        return response('Connected to Teamleader. You can close this tab and run: php artisan teamleader:status');
    }

    return response('Connecting to Teamleader failed. Check storage/logs/laravel.log.', 500);
});

use McoreServices\TeamleaderSDK\Facades\Teamleader;

// 1. Redirect the user to Teamleader — a state is generated and remembered
return Teamleader::authorize();

// 2. Handle the callback — the state is checked, tokens are encrypted and stored
Teamleader::handleCallback($code, $state);

// 3. Check authentication status
if (Teamleader::isAuthenticated()) {
    // Ready to make API calls
}

$resource->list(array $filters = [], array $options = []);
$resource->info(string $id);
$resource->create(array $data);
$resource->update(string $id, array $data);
$resource->delete(string $id);

use McoreServices\TeamleaderSDK\Facades\Teamleader;

// List with filters, pagination and sideloading
$companies = Teamleader::companies()->list(
    ['status' => 'active'],
    ['page_size' => 50, 'sort' => 'name', '  => 'BE0123456789',
    'emails'                  => [['type' => 'primary', 'email' => '[email protected]']],
    'marketing_mails_consent' => true,
]);

// Upload a logo — base64 data URI, or null to remove
$logo = 'data:image/png;base64,'.base64_encode(file_get_contents('/path/to/logo.png'));
Teamleader::companies()->uploadLogo('company-uuid', $logo);

$contacts = Teamleader::contacts()->list(
    ['marketing_mails_consent' => true],
    ['('contact-uuid', ['price_list_id' => 'price-list-uuid']);

$avatar = 'data:image/jpeg;base64,'.base64_encode(file_get_contents('/path/to/avatar.jpg'));
Teamleader::contacts()->uploadAvatar('contact-uuid', $avatar);

$deals = Teamleader::deals()->list(
    ['status' => ['open']],
    ['sort' => 'weighted_value', 'sort_order' => 'desc']
);

$deal = Teamleader::deals()->create([
    'title'           => 'New Business Deal',
    'lead'            => ['customer' => ['type' => 'company', 'id' => 'company-uuid']],
    'estimated_value' => ['amount' => 10000, 'currency' => 'EUR'],
]);

Teamleader::deals()->win($deal['data']['id']);

// create() drafts an invoice. listDrafts() lists existing drafts.
$invoice = Teamleader::invoices()->create([
    'department_id' => 'dept-uuid',
    'invoicee'      => ['customer' => ['type' => 'company', 'id' => 'company-uuid']],
    'payment_term'  => ['type' => 'after_invoice_date', 'days' => 30],
    'grouped_lines' => [[
        'line_items' => [[
            'quantity'    => 5,
            'description' => 'Consulting',
            'unit_price'  => ['amount' => 150.0, 'tax' => 'excluding'],
            'tax_rate_id' => 'tax-rate-uuid',
        ]],
    ]],
]);

$outstanding = Teamleader::invoices()->list(['status' => ['outstanding']]);

Teamleader::timeTracking()->create([
    'started_at'   => now()->toIso8601String(),
    'duration'     => 3600,
    'subject'      => ['type' => 'ticket', 'id' => 'ticket-uuid'],
    'work_type_id' => 'work-type-uuid',
]);

$entries = Teamleader::timeTracking()->betweenDates(
    '2026-08-01T00:00:00+02:00',
    '2026-08-31T23:59:59+02:00'
);

// Requests the upload link and sends the file to it
Teamleader::files()->uploadFile(storage_path('contract.pdf'), 'deal', 'deal-uuid', 'Contracts');

$files = Teamleader::files()->forDeal('deal-uuid');
$offers = Teamleader::files()->forDeal('deal-uuid', ['filters' => ['term' => 'offerte']]);
$some = Teamleader::files()->byIds(['file-uuid-1', 'file-uuid-2']);

// Downloads: the bytes, or straight onto a Laravel disk
$pdf = Teamleader::invoices()->downloadContents('invoice-uuid');
Teamleader::invoices()->downloadTo('invoice-uuid', 's3', 'invoices/2026-0042.pdf');

$field = Teamleader::customFields()->create([
    'label'   => 'VAT Number',
    'type'    => 'single_line',
    'context' => 'company',
]);

// Every definition, paging handled for you
$all = Teamleader::customFields()->all();

// A select field takes the option label, not the option id
$value = Teamleader::customFields()->selectValue('field-uuid', 'option-uuid-or-label');

Teamleader::companies()
    ->lazy(['status' => 'active'])
    ->each(function (array $company) {
        // one record at a time
    });

Teamleader::deals()->lazy(['status' => 'open'])->take(10)->all();   // one request

$stats = Teamleader::getRateLimitStats();
echo "Remaining: {$stats['remaining']} / {$stats['rate_limit']}";

use McoreServices\TeamleaderSDK\Exceptions\RateLimitExceededException;

try {
    Teamleader::deals()->list();
} catch (RateLimitExceededException $e) {
    $this->release($e->getRetryAfter());
}

$deals = Teamleader::deals()->list(
    ['status' => ['open']],
    ['  ->info('company-uuid');

// What does this resource actually accept?
$capabilities = Teamleader::companies()->getCapabilities();

// config/teamleader.php
'connections' => [
    'antwerp' => [
        'client_id' => env('TEAMLEADER_ANTWERP_CLIENT_ID'),
        'client_secret' => env('TEAMLEADER_ANTWERP_CLIENT_SECRET'),
    ],
],

Teamleader::connection('antwerp')->companies()->list();

// Any list to a file
Teamleader::bulk()
    ->export('contacts', ['tags' => ['customer']])
    ->toCsv(storage_path('contacts.csv'), ['id', 'first_name', 'last_name', 'emails.0.email']);

// Many writes: every row validated before the first is sent
$result = Teamleader::bulk()
    ->create('companies', $rows)
    ->continueOnError()
    ->run();

$result->succeeded();   // [row key => API response]
$result->failed();      // [row key => BulkFailure]

// Or on the queue, in chunks
Teamleader::bulk()->update('deals', $rows)->dispatch(chunk: 50);

Teamleader::fake([
    'deals.create' => ['data' => ['id' => 'deal-1', 'type' => 'deal']],
    'deals.info'   => Teamleader::response()->status(404),
]);

// … your code …

Teamleader::assertSent('deals.create', fn (array $body) => $body['title'] === 'Big deal');

use Illuminate\Support\Facades\Event;
use McoreServices\TeamleaderSDK\Events\TokenRefreshFailed;

Event::listen(function (TokenRefreshFailed $event) {
    if ($event->reauthorizationRequired) {
        // tell someone to reconnect $event->connection
    }
});

'recorders' => [
    \McoreServices\TeamleaderSDK\Pulse\Recorders\TeamleaderRequests::class => [
        'enabled' => env('PULSE_TEAMLEADER_REQUESTS_ENABLED', true),
        'sample_rate' => env('PULSE_TEAMLEADER_REQUESTS_SAMPLE_RATE', 1),
        'threshold' => env('PULSE_TEAMLEADER_REQUESTS_THRESHOLD', 1000),
        'ignore' => [],
        'connections' => ['ignore' => [], 'groups' => []],
    ],
    \McoreServices\TeamleaderSDK\Pulse\Recorders\TeamleaderCallers::class => [
        'enabled' => env('PULSE_TEAMLEADER_CALLERS_ENABLED', true),
        'sample_rate' => env('PULSE_TEAMLEADER_CALLERS_SAMPLE_RATE', 1),
        'ignore' => [],
    ],
    // …
],

Teamleader::webhooks()->register('https://your-app.com/webhooks/teamleader', [
    'invoice.booked',
    'invoice.peppolSubmissionSucceeded',
    'invoice.peppolSubmissionFailed',
    'deal.won',
]);

// Or a whole category at once
$types = Teamleader::webhooks()->getInvoiceEventTypes();
Teamleader::webhooks()->register('https://your-app.com/webhooks/teamleader', $types);

Route::post('/webhooks/teamleader', function (Request $request) {
    ProcessTeamleaderEvent::dispatch(
        $request->input('type'),
        $request->input('subject.id')
    );

    return response()->json(['status' => 'received']);
});

use McoreServices\TeamleaderSDK\Exceptions\AuthenticationException;
use McoreServices\TeamleaderSDK\Exceptions\NotFoundException;
use McoreServices\TeamleaderSDK\Exceptions\RateLimitExceededException;
use McoreServices\TeamleaderSDK\Exceptions\TeamleaderException;
use McoreServices\TeamleaderSDK\Exceptions\ValidationException;

try {
    $company = Teamleader::companies()->info('company-uuid');
} catch (NotFoundException $e) {
    // 404 — the record does not exist
} catch (ValidationException $e) {
    // 422 — the API rejected the payload
} catch (RateLimitExceededException $e) {
    // 429 — always thrown, never swallowed
    $this->release($e->getRetryAfter());
} catch (AuthenticationException $e) {
    // Includes ConnectionNeedsReauthorizationException — connect again
    return redirect('/teamleader/connect');
} catch (TeamleaderException $e) {
    logger()->error('Teamleader API error', ['message' => $e->getMessage()]);
}

Teamleader::timeTracking()->list(['updated_since' => '2026-08-01T00:00:00+02:00']);
// InvalidArgumentException: Unsupported filter key for timeTracking.list:
// updated_since. Supported: ids, user_id, started_after, ...
bash
php artisan vendor:publish --tag=teamleader-config
php artisan migrate
bash
php artisan teamleader:connections:add antwerp
bash
php artisan teamleader:describe deals
php artisan teamleader:list deals --filter='status[]=open' --sort=created_at:desc --fields=id,title
php artisan teamleader:export contacts --filter='tags[]=customer' --output=storage/customers.csv
php artisan teamleader:import companies companies.csv --dry-run
php artisan teamleader:call users.me