What are the best practices for handling OAuth authentication in PHP when using external APIs like Facebook?

When handling OAuth authentication in PHP for external APIs like Facebook, it is important to securely store and manage access tokens, handle token expiration and renewal, and implement proper error handling for authentication failures. One common practice is to use a library like GuzzleHTTP to make HTTP requests to the API endpoints and manage the authentication flow.

// Example code snippet using GuzzleHTTP for OAuth authentication with Facebook API

use GuzzleHttp\Client;

$client = new Client();

// Make a request to Facebook API to get access token
$response = $client->post('https://graph.facebook.com/v12.0/oauth/access_token', [
    'form_params' => [
        'client_id' => 'YOUR_APP_ID',
        'client_secret' => 'YOUR_APP_SECRET',
        'redirect_uri' => 'YOUR_REDIRECT_URI',
        'code' => 'AUTHORIZATION_CODE'
    ]
]);

$data = json_decode($response->getBody(), true);

$accessToken = $data['access_token'];

// Use the access token to make authenticated requests to Facebook API
$response = $client->get('https://graph.facebook.com/v12.0/me', [
    'query' => [
        'access_token' => $accessToken
    ]
]);

$userData = json_decode($response->getBody(), true);

// Handle the response data as needed