Can't access OneDrive via API (Laravel)

Alessio Vietri 6 Reputation points
2021-02-09T06:59:09.377+00:00

I'm trying to connect to my OneDrive and upload/download files to/from it, but I always get "User's mysite not found" exception and I don't know why. I'm not using frontend login. This is my code:

    $tenantId = '-----';
    $clientId = '-----';
    $clientSecret = '-----';
    $guzzle = new \GuzzleHttp\Client();
    $url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
    $token = json_decode($guzzle->post($url, [
        'form_params' => [
            'client_id' => $clientId,
            'client_secret' => $clientSecret,
            'resource' => 'https://graph.microsoft.com/',
            'grant_type' => 'client_credentials',
        ],
    ])->getBody()->getContents());
    $accessToken = $token->access_token;
    $graph = new \Microsoft\Graph\Graph();
    $graph->setBaseUrl("https://graph.microsoft.com/")
        ->setApiVersion("v1.0")
        ->setAccessToken($accessToken);
    try {
        $userId = '-----';
        $user = $graph->createRequest("GET", "/users/".$userId."/drive/root")
                    ->execute();
        $graph->createRequest("PUT",  "/users/".$userId."/drive/root/children/robots.txt/content")
            ->upload('../public/robots.txt');
        dd('OK');
    }
    catch (\Exception $e) {
        dd($e);
    }

Any suggestion? Thanks in advance!

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,248 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.