PHP code example of drchrono / php-sdk

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

    

drchrono / php-sdk example snippets


use DrChrono\DrChronoClient;

// Create client with access token
$client = DrChronoClient::withAccessToken('your_access_token');

// Get current user
$user = $client->getCurrentUser();
echo "Authenticated as: {$user['first_name']} {$user['last_name']}";

// List patients
$patients = $client->patients->list();
foreach ($patients as $patient) {
    echo "{$patient['first_name']} {$patient['last_name']}\n";
}

use DrChrono\DrChronoClient;

// Initialize client with OAuth credentials
$client = DrChronoClient::withOAuth(
    clientId: 'your_client_id',
    clientSecret: 'your_client_secret',
    redirectUri: 'https://yourapp.com/callback'
);

// Step 1: Redirect user to authorization URL
$authUrl = $client->auth()->getAuthorizationUrl(
    scopes: ['patients:read', 'appointments:read', 'appointments:write']
);
header("Location: {$authUrl}");

// Step 2: Exchange code for tokens (in your callback handler)
$tokens = $client->auth()->exchangeAuthorizationCode($_GET['code']);

// Step 3: Use access token
$client->getConfig()->setAccessToken($tokens['access_token']);
$patients = $client->patients->list();

use DrChrono\DrChronoClient;
use Illuminate\Support\Facades\Http;

Http::fake();

$client = app(DrChronoClient::class);
$patients = $client->patients->list();

$client->patients        // Patient management
$client->appointments    // Appointment scheduling
$client->clinicalNotes   // Clinical documentation
$client->documents       // Document management
$client->offices         // Office locations
$client->users           // Doctors and staff
$client->tasks           // Task management
$client->prescriptions   // Medication prescriptions
$client->labOrders       // Laboratory orders
$client->labResults      // Lab results
$client->insurances      // Insurance information
$client->allergies       // Patient allergies
$client->medications     // Patient medications
$client->problems        // Problem list
$client->vitals          // Vital signs
$client->immunizations   // Vaccination records
$client->billing         // Billing and transactions
$client->appointmentProfiles    // Appointment types
$client->appointmentTemplates   // Recurring blocks
$client->patientPayments        // Payment records
$client->patientMessages        // Patient communications
$client->inventoryCategories    // Inventory organization
$client->patientVaccineRecords  // Immunization tracking
$client->taskTemplates          // Reusable task templates
$client->taskCategories         // Task organization
$client->taskStatuses           // Custom task statuses
$client->taskNotes              // Task documentation
$client->doctors                // Provider directory
$client->userGroups             // Permission groups
$client->prescriptionMessages   // Pharmacy communications
$client->commLogs               // Communication audit trail

// Get patient with full insurance details
$patient = $client->patients->getWithInsurance($patientId);
echo "Insurance: {$patient['primary_insurance']['insurance_payer_name']}\n";
echo "Policy #: {$patient['primary_insurance']['insurance_id_number']}\n";

// Get appointment with clinical data (vitals, notes, etc.)
$appointment = $client->appointments->getWithClinicalData($appointmentId);
echo "BP: {$appointment['vitals']['blood_pressure_1']}/{$appointment['vitals']['blood_pressure_2']}\n";

// Get clinical note with full section content
$note = $client->clinicalNotes->getWithSections($noteId);
foreach ($note['clinical_note_sections'] as $section) {
    echo "{$section['section_name']}: {$section['section_content']}\n";
}

// List patients with insurance details
// Note: Page size limited to 50 (vs 250 default)
$patients = $client->patients->listWithInsurance(['doctor' => 123456]);

// Manual verbose mode (low-level)
$appointments = $client->appointments->list(['verbose' => 'true']);

// Get first page
$patients = $client->patients->list(['page_size' => 50]);

echo "Page count: {$patients->count()}\n";
echo "Has more: " . ($patients->hasNext() ? 'Yes' : 'No') . "\n";

// Iterate through items
foreach ($patients as $patient) {
    // Process patient
}

// Auto-iterate all pages (memory efficient)
foreach ($client->patients->iterateAll() as $patient) {
    // Processes all patients across all pages
}

// Get all at once (caution: may be memory intensive)
$allPatients = $client->patients->all();

use DrChrono\Model\Patient;
use DrChrono\Model\Appointment;

// Create from array
$patient = Patient::fromArray($patientData);

echo $patient->getFullName();
echo $patient->getEmail();
echo $patient->getDateOfBirth();

// Convert to array
$data = $patient->toArray();

// Use models with resources
$appointmentData = (new Appointment())
    ->setDoctor(123)
    ->setPatient(456)
    ->setOffice(1)
    ->setDuration(30)
    ->setScheduledTime('2025-01-15T10:00:00')
    ->toArray();

$created = $client->appointments->create($appointmentData);

use DrChrono\Exception\AuthenticationException;
use DrChrono\Exception\ValidationException;
use DrChrono\Exception\RateLimitException;
use DrChrono\Exception\ApiException;

try {
    $patient = $client->patients->create($data);
} catch (ValidationException $e) {
    // Handle validation errors
    echo "Validation failed: {$e->getMessage()}\n";
    print_r($e->getValidationErrors());
} catch (RateLimitException $e) {
    // Handle rate limiting
    echo "Rate limited. Retry after: {$e->getRetryAfter()} seconds\n";
} catch (AuthenticationException $e) {
    // Handle authentication errors
    echo "Auth failed: {$e->getMessage()}\n";
} catch (ApiException $e) {
    // Handle other API errors
    echo "API error: {$e->getMessage()}\n";
    echo "Status: {$e->getStatusCode()}\n";
    print_r($e->getErrorDetails());
}

// Search patients
$results = $client->patients->search([
    'first_name' => 'John',
    'last_name' => 'Doe',
    'date_of_birth' => '1980-01-01'
]);

// Create patient
$patient = $client->patients->createPatient([
    'first_name' => 'Jane',
    'last_name' => 'Smith',
    'gender' => 'Female',
    'date_of_birth' => '1985-03-15',
    'email' => '[email protected]',
    'doctor' => 123456,
]);

// Update patient
$client->patients->updateDemographics($patient['id'], [
    'cell_phone' => '555-1234'
]);

// Get patient summary
$summary = $client->patients->getSummary($patient['id']);

// Get CCDA
$ccda = $client->patients->getCCDA($patient['id']);

// List appointments by date range
$appointments = $client->appointments->listByDateRange(
    startDate: '2025-01-01',
    endDate: '2025-01-31'
);

// List by patient
$patientAppts = $client->appointments->listByPatient($patientId);

// Create appointment
$appointment = $client->appointments->createAppointment([
    'doctor' => 123456,
    'patient' => 789012,
    'office' => 1,
    'duration' => 30,
    'scheduled_time' => '2025-01-15T10:00:00',
    'status' => 'Scheduled',
    'reason' => 'Annual checkup',
]);

// Update status
$client->appointments->setStatus($appointment['id'], 'Confirmed');

// Mark as arrived
$client->appointments->markArrived($appointment['id']);

// Mark as complete
$client->appointments->markComplete($appointment['id']);

// Cancel appointment
$client->appointments->cancel($appointment['id'], 'Patient requested cancellation');

// Create clinical note
$note = $client->clinicalNotes->createNote([
    'patient' => $patientId,
    'appointment' => $appointmentId,
    'doctor' => $doctorId,
    'chief_complaint' => 'Follow-up visit',
]);

// Update note
$client->clinicalNotes->updateNote($note['id'], [
    'assessment' => 'Patient improving',
    'plan' => 'Continue current treatment',
]);

// Lock note (finalize)
$client->clinicalNotes->lock($note['id']);

// Get note templates
$templates = $client->clinicalNotes->getTemplates();

// Upload document to patient chart
$document = $client->documents->upload(
    doctorId: 123456,
    patientId: 789012,
    filePath: '/path/to/document.pdf',
    description: 'Lab results',
    date: '2025-01-15',
    metatags: ['Lab Results', 'Bloodwork']
);

// List patient documents
$documents = $client->documents->listByPatient($patientId);

// Update metadata
$client->documents->updateMetadata($document['id'], [
    'description' => 'Updated description'
]);

// Create lab order
$order = $client->labOrders->createOrder([
    'patient' => $patientId,
    'doctor' => $doctorId,
    'order_type' => 'Lab',
]);

// List lab orders
$orders = $client->labOrders->listByPatient($patientId);

// Get order document (requisition)
$requisition = $client->labOrders->getOrderDocument($order['id']);

// Create task
$task = $client->tasks->createTask([
    'title' => 'Follow up with patient',
    'patient' => $patientId,
    'assignee' => $userId,
    'due_date' => '2025-01-20',
    'status' => 'Open',
]);

// List tasks by patient
$tasks = $client->tasks->listByPatient($patientId);

// Mark as complete
$client->tasks->markComplete($task['id']);

// Add note to task
$client->tasks->addNote($task['id'], 'Patient contacted successfully');

use DrChrono\Webhook\WebhookVerifier;

$verifier = new WebhookVerifier('your_client_secret');

// Get raw payload
$payload = file_get_contents('php://input');
$headers = getallheaders();

try {
    // Verify and parse webhook
    $event = $verifier->verifyFromRequest($payload, $headers);

    // Handle event
    if ($event->is('appointment.created')) {
        $appointmentId = $event->getAppointmentId();
        // Handle new appointment
    }

    if ($event->isPatientEvent()) {
        $patientId = $event->getPatientId();
        // Handle patient event
    }

    // Return success
    http_response_code(200);

} catch (\DrChrono\Exception\WebhookVerificationException $e) {
    http_response_code(401);
    echo "Invalid signature";
}

use DrChrono\Client\Config;
use DrChrono\DrChronoClient;

$config = new Config([
    'access_token' => 'your_token',
    'client_id' => 'your_client_id',
    'client_secret' => 'your_client_secret',
    'timeout' => 60,              // Request timeout (seconds)
    'connect_timeout' => 10,      // Connection timeout (seconds)
    'max_retries' => 3,           // Max retry attempts for rate limits
    'retry_delay' => 1000,        // Initial retry delay (milliseconds)
    'debug' => true,              // Enable debug mode
    'api_version' => 'v4',        // Specific API version
]);

$client = new DrChronoClient($config);

// Check if token is expired
if ($client->getConfig()->isTokenExpired()) {
    // Refresh token
    $tokens = $client->auth()->refreshAccessToken();

    // Update config with new token
    $client->getConfig()->setAccessToken($tokens['access_token']);
}

// Auto-refresh (recommended)
$client->auth()->ensureValidToken();
bash
composer 
bash
php artisan vendor:publish --tag=drchrono-config