Facebook PHP SDK (v5)

repository·5.x·Indexed 25 days ago

https://github.com/facebookarchive/php-graph-sdk

An open-source library for PHP applications to interact with the Facebook Platform and Graph API. It enables developers to integrate Facebook login, make Graph API requests, upload photos and videos, and send batch requests. Requires PHP 5.4 or greater and is compatible with Guzzle 5.x.

Tokens
36K
Snippets
89
Records
171
Agent score
81%

What's inside facebookarchive-php-graph-sdk

  1. Obtain an access token from an App Canvas context

    5.x

    If a user has already authenticated your app within the Canvas context, you can attempt to retrieve an access token using getAccessToken().

    Note: The method returns null if the signed request does not contain OAuth 2.0 data required to obtain a token. You should handle both Facebook\Exceptions\FacebookResponseException (for Graph API errors) and Facebook\Exceptions\FacebookSDKException (for validation or local issues).

    $fb = new Facebook\Facebook([/* */]);
    $canvasHelper = $fb->getCanvasHelper();
    
    try {
      $accessToken = $canvasHelper->getAccessToken();
    } catch(Facebook\Exceptions\FacebookResponseException $e) {
      // When Graph returns an error
      echo 'Graph returned an error: ' . $e->getMessage();
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
      // When validation fails or other local issues
      echo 'Facebook SDK returned an error: ' . $e->getMessage();
    }
    
    if (isset($accessToken)) {
      // Logged in.
    }
  2. Upload a video using a single request (Graph versions < v2.3)

    5.x

    For older versions of the Graph API, videos must be uploaded in a single request. To do this, include a FacebookVideo entity in the 'source' key of your data array when calling the post() method on the /me/videos endpoint.

    // Upload a video for a user
    $data = [
      'title' => 'My awesome video',
      'description' => 'More info about my awesome video.',
      'source' => $fb->videoToUpload('/path/to/video.mp4'),
    ];
    
    try {
      $response = $fb->post('/me/videos', $data);
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
      echo 'Error: ' . $e->getMessage();
      exit;
    }
    
    $graphNode = $response->getGraphNode();
    
    echo 'Video ID: ' . $graphNode['id'];
  3. Obtain an access token using FacebookPageTabHelper

    5.x

    If a user has already authenticated your app, you can use getAccessToken() to retrieve their access token. This method may throw Facebook\Exceptions\FacebookResponseException if the Graph API returns an error, or Facebook\Exceptions\FacebookSDKException if validation fails or other local issues occur.

    $fb = new Facebook\Facebook([/* config */]);
    $pageHelper = $fb->getPageTabHelper();
    
    try {
      $accessToken = $pageHelper->getAccessToken();
    } catch(Facebook\Exceptions\FacebookResponseException $e) {
      // When Graph returns an error
      echo 'Graph returned an error: ' . $e->getMessage();
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
      // When validation fails or other local issues
      echo 'Facebook SDK returned an error: ' . $e->getMessage();
    }
    
    if (isset($accessToken)) {
      // Logged in.
    }
  4. Use FacebookPageTabHelper to handle page tabs

    5.x

    Use Facebook\Helpers\FacebookPageTabHelper to obtain an access token or a signed request when your application is running within the context of a Facebook page tab. This helper provides methods to extract page-specific data from the signed request payload.

    $fb = new Facebook\Facebook([/* config */]);
    $pageHelper = $fb->getPageTabHelper();
    $signedRequest = $pageHelper->getSignedRequest();
    
    if ($signedRequest) {
      $payload = $signedRequest->getPayload();
      var_dump($payload);
    }
  5. Inject a custom PseudoRandomStringGenerator into FacebookRedirectLoginHelper

    5.x

    If you are using Facebook\Helpers\FacebookRedirectLoginHelper directly, you can inject your custom generator via its constructor.

    use Facebook\Helpers\FacebookRedirectLoginHelper;
    
    $myPseudoRandomStringGenerator = new MyCustomPseudoRandomStringGenerator();
    $helper = new FacebookRedirectLoginHelper($fbApp, null, null, $myPseudoRandomStringGenerator);
  6. Handle App Canvas signed requests with FacebookCanvasHelper

    5.x

    When your app is loaded via Facebook Canvas, Facebook sends a POST request containing a signed request. Use Facebook\Helpers\FacebookCanvasHelper to validate and decrypt this request.

    To access the decrypted payload, call getSignedRequest() and then getPayload() on the returned Facebook\SignedRequest instance.

    $fb = new Facebook\Facebook([/* */]);
    $canvasHelper = $fb->getCanvasHelper();
    $signedRequest = $canvasHelper->getSignedRequest();
    
    if ($signedRequest) {
      $payload = $signedRequest->getPayload();
      var_dump($payload);
    }
  7. Install the Facebook PHP SDK via Composer

    5.x

    Install the Facebook PHP SDK using Composer by running the following command.

    Compatibility Note:

    • This SDK requires PHP 5.4 or greater.
    • Version 5.x works with Guzzle 5.x out of the box.
    • If you are using Guzzle 6.x, you will need to implement a workaround to inject your own HTTP client.
    composer require facebook/graph-sdk
  8. Upload a video using chunked uploading (Graph v2.3+)

    5.x

    For Graph API versions 2.3 and higher, you can use chunked (resumable) uploads. Use the uploadVideo() method on the Facebook\Facebook instance. This method handles the complexity of uploading the file in chunks automatically.

    Parameters for uploadVideo():

    • node: The Graph node to which the video is being uploaded (e.g., 'me').
    • path: The path to the video file.
    • fields: An array of metadata (e.g., 'title', 'description').
    • access_token: The user access token.
    // Upload a video for a user (chunked)
    $data = [
      'title' => 'My awesome video',
      'description' => 'More info about my awesome video.',
    ];
    
    try {
      $response = $fb->uploadVideo('me', '/path/to/video.mp4', $data, '{user-access-token}');
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
      echo 'Error: ' . $e->getMessage();
      exit;
    }
    
    echo 'Video ID: ' . $response['video_id'];
  9. Force response body in batch requests

    5.x

    By default, the Graph API omits the response body for requests that are referenced via JSONPath or depends_on. To force the server to return the response body for these requests, use $fb->newBatchRequest() and add requests with the omit_response_on_success option set to false.

    <?php
    $batch = $fb->newBatchRequest();
    
    // Set 'omit_response_on_success' to false to force the server to return the response
    $batch->add($requestUserEvents, [
        "name" => "user-events",
        "omit_response_on_success" => false
    ]);
    
    $responses = $fb->getClient()->sendBatchRequest($batch);
  10. Make requests to the Graph API

    5.x

    To interact with the Graph API, use an instance of Facebook\Facebook. You should set a default access token using setDefaultAccessToken('{access-token}') to avoid passing it manually to every request.

    Use the get() method to perform a GET request to a specific endpoint. The get() method returns a Facebook\FacebookResponse object.

    To handle errors, catch Facebook\Exceptions\FacebookResponseException for errors returned by the Graph API itself, and Facebook\Exceptions\FacebookSDKException for local validation failures or SDK-specific issues.

    $fb = new Facebook\Facebook([/* . . . */]);
    
    // Sets the default fallback access token so we don't have to pass it to each request
    $fb->setDefaultAccessToken('{access-token}');
    
    try {
      $response = $fb->get('/me');
      $userNode = $response->getGraphUser();
    } catch(Facebook\Exceptions\FacebookResponseException $e) {
      // When Graph returns an error
      echo 'Graph returned an error: ' . $e->getMessage();
      exit;
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
      // When validation fails or other local issues
      echo 'Facebook SDK returned an error: ' . $e->getMessage();
      exit;
    }
    
    echo 'Logged in as ' . $userNode->getName();