PHP code example of brightleaf-digital / asana-client

1. Go to this page and download the library: Download brightleaf-digital/asana-client 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/ */

    

brightleaf-digital / asana-client example snippets


// Webhooks - Real-time notifications
$webhook = $client->webhooks()->createWebhook([
    'resource' => $projectGid,
    'target' => 'https://example.com/webhook'
]);

// Events - Poll for changes
$events = $client->events()->getEvents($resourceGid);

// Teams - Manage teams
$teams = $client->teams()->getTeams($workspaceGid);
$team = $client->teams()->createTeam(['name' => 'Engineering', 'workspace' => $workspaceGid]);

// Portfolios - Organize projects
$portfolios = $client->portfolios()->getPortfolios($workspaceGid);
$portfolio = $client->portfolios()->createPortfolio(['name' => 'Q1 Projects', 'workspace' => $workspaceGid]);

// Goals - Track objectives
$goals = $client->goals()->getGoals(['workspace' => $workspaceGid]);
$goal = $client->goals()->createGoal(['name' => 'Increase Revenue', 'workspace' => $workspaceGid]);

// Time Tracking - Log time entries
$entry = $client->timeTrackingEntries()->createTimeTrackingEntry($taskGid, [
    'entered_on' => '2026-10-01',
    'duration_minutes' => 120,
    'assignee' => $userGid,
]);

// Project Templates - Standardize workflows
$templates = $client->projectTemplates()->getProjectTemplates($workspaceGid);
$project = $client->projectTemplates()->instantiateProject($templateGid, ['name' => 'New Project']);

// Batch API - Optimize multiple requests
$responses = $client->batch()->submitBatch([
    ['method' => 'GET', 'relative_path' => '/tasks/12345'],
    ['method' => 'GET', 'relative_path' => '/projects/67890']
]);

// Status Updates - Project communication
$statusUpdate = $client->statusUpdates()->createStatusUpdate([
    'parent' => $projectGid,
    'text' => 'Project is on track',
    'status_type' => 'on_track'
]);

// User Task Lists - Personal task management
$myTasks = $client->userTaskLists()->getUserTaskList($userTaskListGid);

$entry = $client->timeTrackingEntries()->updateTimeTrackingEntry($entryGid, ['assignee' => $userGid]);
$entries = $client->timeTrackingEntries()->getTimeTrackingEntries([
    'assignee' => $userGid,
    'workspace' => $workspaceGid,
    'entered_on_start_date' => '2026-10-01',
    'entered_on_end_date' => '2026-10-31',
    'opt_fields' => 'assignee,assignee.name,created_by,duration_minutes,entered_on',
]);

$directoryClient = AsanaClient::withPAT($serviceAccountToken, tokenStorage: false);
$page = $directoryClient->scim()->getUsers(['startIndex' => 1, 'count' => 100]);
$users = $page['Resources'];
if (!empty($page['nextCursor'])) {
    $nextPage = $directoryClient->scim()->getUsers(['cursor' => $page['nextCursor'], 'count' => 100]);
}
$groups = $directoryClient->scim()->getGroups(['count' => 100]);
$matchingUsers = $directoryClient->scim()->getUsers(['filter' => 'userName eq "[email protected]"']);



use BrightleafDigital\AsanaClient;

$personalAccessToken = 'your-personal-access-token';
$client = AsanaClient::withPAT($personalAccessToken);

// Get user information
$me = $client->users()->getCurrentUser();

// Create a task
$taskData = [
    'name' => 'My new task',
    'notes' => 'Task description',
    'projects' => ['12345678901234'] // Project GID
];
$task = $client->tasks()->createTask($taskData);

use BrightleafDigital\AsanaClient;
use BrightleafDigital\Auth\Scopes;

$clientId = 'your-client-id';
$clientSecret = 'your-client-secret';
$redirectUri = 'https://your-app.com/callback';

// Bootstrap with defaults (uses an internal container and file token storage)
$client = AsanaClient::OAuth($clientId, $clientSecret, $redirectUri, __DIR__ . '/token.json');

// Request specific scopes and get URL + state + PKCE verifier
$auth = $client->getSecureAuthorizationUrl([
    Scopes::TASKS_READ,
    Scopes::PROJECTS_READ,
    Scopes::USERS_READ
]);

// Store $auth['state'] and $auth['codeVerifier'] in the session, then redirect to $auth['url']

// In your callback handler:
$code = $_GET['code'];
$pkceVerifier = $_SESSION['oauth2_pkce_verifier'] ?? null;
$client->handleCallback($code, $pkceVerifier); // Token is saved automatically via TokenManager

// Then use the client
$me = $client->users()->getCurrentUser();

use BrightleafDigital\AsanaClient;

// Initialize the client (automatically loads/saves to token.json)
$asanaClient = AsanaClient::OAuth($clientId, $clientSecret, $redirectUri, __DIR__ . '/token.json', null, $salt);

// Optional: Subscribe to refresh events for additional logging or custom logic
$asanaClient->subscribeToTokenRefresh(function ($newToken) {
    // Note: You DON'T need to call save() here; the library already did it!
    echo "Token refreshed successfully!";
});

// Example API call that triggers a token refresh if the token is expired
$userInfo = $asanaClient->users()->getCurrentUser();

// Use memory storage (false) so no files are written
$client = AsanaClient::withAccessToken($clientId, $clientSecret, $tokenData, false);

// Subscribe to refresh events to keep your DB in sync
$client->subscribeToTokenRefresh(function($newToken) use ($db) {
    $db->update('users')->set(['token' => json_encode($newToken)])->execute();
});

use BrightleafDigital\Http\HttpClientInterface;

// Opt in to an early-access feature (Asana-Enable)
$client->enableFeatureFlag(HttpClientInterface::FLAG_AI_TEAMMATE_ACTORS);

// Opt out of a deprecation whose default has already flipped (Asana-Disable)
$client->disableFeatureFlag(HttpClientInterface::FLAG_INCLUDE_ASANA_CREATED_CUSTOM_TYPES);

// Only projects of one custom type
$client->projects()->getProjects('12345', null, ['custom_type' => '67890']);

// Only projects with no custom type assigned
$client->projects()->getProjects('12345', null, ['custom_type' => '']);