PHP code example of grim-reapper / msgraph-php

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

    

grim-reapper / msgraph-php example snippets


use GrimReapper\MsGraph\Authentication\AuthConfig;
use GrimReapper\MsGraph\Core\GraphClient;

$config = new AuthConfig([
    'clientId' => 'your-client-id',
    'clientSecret' => 'your-client-secret',
    'tenantId' => 'your-tenant-id',
    'redirectUri' => 'https://yourapp.com/callback'
]);

$graphClient = new GraphClient($config);

use GrimReapper\MsGraph\Services\OneDriveService;

$oneDrive = new OneDriveService($graphClient);

// List files
$files = $oneDrive->listFiles('/');

// Upload a file
$oneDrive->uploadFile('/path/to/local/file.pdf', 'Documents/file.pdf');

// Download a file
$content = $oneDrive->downloadFile('/Documents/file.pdf');

use GrimReapper\MsGraph\Services\DocumentService;

$documentService = new DocumentService($graphClient);

// Convert DOCX to PDF
$convertedContent = $documentService->convertDocument(
    '/Documents/document.docx',
    'pdf'
);

use GrimReapper\MsGraph\Services\MailService;

$mailService = new MailService($graphClient);

// Send email
$mailService->sendEmail([
    'to' => '[email protected]',
    'subject' => 'Test Email',
    'body' => 'This is a test email from Microsoft Graph PHP'
]);

// Read emails
$messages = $mailService->getMessages();

$config = new AuthConfig([
    'clientId' => 'your-client-id',
    'clientSecret' => 'your-client-secret',
    'tenantId' => 'your-tenant-id',
    'redirectUri' => 'https://yourapp.com/callback',
    'scopes' => ['https://graph.microsoft.com/.default'],
    'cache' => new FileCache(), // Optional: Custom cache implementation
    'logger' => new Logger(), // Optional: Custom logger
]);

// Custom HTTP client
$httpClient = new GuzzleHttp\Client([
    'timeout' => 30,
    'headers' => ['User-Agent' => 'MyApp/1.0']
]);

$graphClient = new GraphClient($config, $httpClient);

use GrimReapper\MsGraph\Exceptions\GraphException;
use GrimReapper\MsGraph\Exceptions\AuthenticationException;

try {
    $files = $oneDrive->listFiles('/');
} catch (AuthenticationException $e) {
    // Handle authentication errors
    echo "Authentication failed: " . $e->getMessage();
} catch (GraphException $e) {
    // Handle API errors
    echo "Graph API error: " . $e->getMessage();
} catch (Exception $e) {
    // Handle other errors
    echo "General error: " . $e->getMessage();
}
bash
composer