The Facebook SDK for PHP provides a native interface to the Graph API and Facebook Login

Related tags

API php-graph-sdk
Overview

Facebook SDK for PHP (v5)

Build Status Scrutinizer Code Quality Latest Stable Version

This repository contains the open source PHP SDK that allows you to access the Facebook Platform from your PHP app.

Installation

The Facebook PHP SDK can be installed with Composer. Run this command:

composer require facebook/graph-sdk

Please be aware, that there are issues when using the Facebook SDK together with Guzzle 6.x. php-graph-sdk v5.x only works with Guzzle 5.x out of the box. However, there is a workaround to make it work with Guzzle 6.x.

Upgrading to v5.x

Upgrading from v4.x? Facebook PHP SDK v5.x introduced breaking changes. Please read the upgrade guide before upgrading.

Usage

Note: This version of the Facebook SDK for PHP requires PHP 5.4 or greater.

Simple GET example of a user's profile.

require_once __DIR__ . '/vendor/autoload.php'; // change path as needed

$fb = new \Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.10',
  //'default_access_token' => '{access-token}', // optional
]);

// Use one of the helper classes to get a Facebook\Authentication\AccessToken entity.
//   $helper = $fb->getRedirectLoginHelper();
//   $helper = $fb->getJavaScriptHelper();
//   $helper = $fb->getCanvasHelper();
//   $helper = $fb->getPageTabHelper();

try {
  // Get the \Facebook\GraphNodes\GraphUser object for the current user.
  // If you provided a 'default_access_token', the '{access-token}' is optional.
  $response = $fb->get('/me', '{access-token}');
} 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;
}

$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();

Complete documentation, installation instructions, and examples are available here.

Tests

  1. Composer is a prerequisite for running the tests. Install composer globally, then run composer install to install required files.
  2. Create a test app on Facebook Developers, then create tests/FacebookTestCredentials.php from tests/FacebookTestCredentials.php.dist and edit it to add your credentials.
  3. The tests can be executed by running this command from the root directory:
$ ./vendor/bin/phpunit

By default the tests will send live HTTP requests to the Graph API. If you are without an internet connection you can skip these tests by excluding the integration group.

$ ./vendor/bin/phpunit --exclude-group integration

Contributing

For us to accept contributions you will have to first have signed the Contributor License Agreement. Please see CONTRIBUTING for details.

License

Please see the license file for more information.

Security Vulnerabilities

If you have found a security issue, please contact the maintainers directly at [email protected].

Comments
  • Facebook SDK returned an error: Cross-site request forgery validation failed. Required param

    Facebook SDK returned an error: Cross-site request forgery validation failed. Required param "state" missing.

    Hi, I've moved to the latest version of the SDK and tried the simple login example for starters and it was working fine a few days ago. However I now get the following error:

    Facebook SDK returned an error: Cross-site request forgery validation failed. Required param "state" missing.

    I can't figure out the problem, I've had a look at the following section of the Helper.

     /**
     * Validate the request against a cross-site request forgery.
     *
     * @throws FacebookSDKException
     */
    protected function validateCsrf()
    {
        $state = $this->getState();
        $savedState = $this->persistentDataHandler->get('state');
    
       if (!$state || !$savedState) {
            throw new FacebookSDKException('Cross-site request forgery validation failed. Required param "state" missing.');
        }
    
        $savedLen = strlen($savedState);
        $givenLen = strlen($state);
    
        if ($savedLen !== $givenLen) {
            throw new FacebookSDKException('Cross-site request forgery validation failed. The "state" param from the URL and session do not match.');
        }
    
        $result = 0;
        for ($i = 0; $i < $savedLen; $i++) {
            $result |= ord($state[$i]) ^ ord($savedState[$i]);
        }
    
        if ($result !== 0) {
            throw new FacebookSDKException('Cross-site request forgery validation failed. The "state" param from the URL and session do not match.');
        }
    }
    
    opened by LeagueRivals 53
  • Removed the HTTP layer and started to use HTTPlug

    Removed the HTTP layer and started to use HTTPlug

    This will fix #605, it is also related to #586.

    This is a PR in order to better support PSR7 in this library by using HTTPlug abstraction. By using HTTPlug a lot of code can be removed and the maintenance will be more focus on the graph API and not the HTTP transport layer (as you can see the diff, a lot of code is no longer necessary).

    Advantages

    • End user choice: The end user will have the choice of the http client implementation, which will be, for a majority of user, the guzzle6 library. However some others librairies can be chosen, like Zend/Http or CakePHP one which are already available in their respective framework.

      By not couple us to Guzzle6 we allow people to use this SDK with Guzzle5 (or any other adapter).

    • Less maintenance on this library: HTTPlug offer a large feature set (with the usage of the client-common package) which does not need to be rewrite in this library: Retry failed requests, Load Balancing (Client Pool), Failure detection, logging, caching etc ...

    • Better integration with frameworks (Symfony ATM, Laravel in progress): HTTPlug offer an integration to existing frameworks for library using this layer. In example, for Symfony all requests will be logged and traced when in dev mode (time, memory, diff at each modification, etc ....).

    • Shared work: Many libraries already implement HTTPlug or are on the way, this mean, we can better profit for feature offered / wanted by other libraries.

    Future work

    One could go further with PSR-7. I've chosen to stop here for this PR. But possible future work could be:

    • Removing the FacebookResponse and FacebookRequest
    • Remove RequestBodyMultipart and replace it with MultipartStreamBuilder
    • Remove RequestBodyUrlEncoded and RequestBodyInterface
    • Remove FacebookClient::getHttpClient
    CLA Signed 
    opened by Nyholm 46
  • GraphObject sub-classes development

    GraphObject sub-classes development

    The official docs demonstrate some sub-classes like GraphUser, and the code have another unmentioned classes like GraphAlbum, and many other types still haven't classes at all.

    I just want to ask about your plan to offer a complete set of GraphObject sub-classes? and if you have any plan to support Edges in addition to the Fields?

    I'm really interested to contribute in these points, but I need to hear from you before I add any pull requests?

    enhancement 
    opened by devmsh 34
  • Error : Can't Load URL: The domain of this URL isn't included in the app

    Error : Can't Load URL: The domain of this URL isn't included in the app

    When i am trying to login with facebook on my site, after facebook login it throwing

    Graph returned an error : Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

    It was working fine two days ago. Today one of my user told me regarding this and when i checked it is throwing error after facebook login.

    What is the problem & how do I fix it? I've searched, and found many similar posts, but none of them have a solution that I can figure out how to apply.

    Thanx for help in advance

    opened by gurjanjua 33
  • Need to support video upload in php sdk

    Need to support video upload in php sdk

    Hi Guys,

    Facebook shipped a Resumable video upload api(https://developers.facebook.com/docs/graph-api/video-uploads) on F8, which will helps video publisher to achieve a more reliable uploading experience. In order to simplify the developer work, we want to add a helper class in php sdk, which will receive the single video file, cut it into small chunks and feed facebook chunked uploading api.

    We already add this functionality into Facebook python sdk(https://github.com/facebook/facebook-python-ads-sdk/blob/master/facebookads/video_uploader.py). And currently want to have the same thing in php sdk with our July release.

    @YuanhuiChen is working on this new sdk api right now. https://github.com/facebook/facebook-php-sdk-v4/pull/452

    @SammyK just kindly noticed me that we didn't kick any discussion for this sdk api interface yet. I'm sorry. It is our mistake. But would like to start the discussion now and keep everyone in the same page.

    Could you guys take a look at this diff and give us your insight feedbacks?

    Thanks a lot, Lei

    opened by codingtmd 32
  • [4.1] Simple request response refactor

    [4.1] Simple request response refactor

    Phew! OK, let's see everyone can agree on this setup. :) This isn't 100% 4.1 feature packed but we can use it as a good starting point if everything is OK.

    Setup

    To make a request to Graph, you need to instantiate a new FacebookApp to hold your app config. You'll also need a FacebookClient to send request entities to Graph.

    use Facebook\Entities\FacebookApp;
    use Facebook\FacebookClient;
    
    $facebookApp = new FacebookApp('{app-id}', '{app-secret}');
    $facebookClient = new FacebookClient(/* $httpClientHandler, $enableBeta */);
    

    Simple GET Request

    use Facebook\Entities\FacebookRequest;
    
    $request = new FacebookRequest($facebookApp, '{access-token}', 'GET', '/me'/*, $params, $eTag, $graphVersion */);
    $facebookResponse = $facebookClient->sendRequest($request);
    
    $userProfile = $facebookResponse->getGraphObject();
    

    Simple POST Request

    use Facebook\Entities\FacebookRequest;
    
    $request = new FacebookRequest($facebookApp, '{access-token}', 'POST', '/me/feed', ['message'=>'Foo message!']/*, $eTag, $graphVersion */);
    $facebookResponse = $facebookClient->sendRequest($request);
    
    $data = $facebookResponse->getDecodedBody();
    
    $id = $data['id'];
    

    Simple DELETE Request

    use Facebook\Entities\FacebookRequest;
    
    $request = new FacebookRequest($facebookApp, '{access-token}', 'DELETE', '/{some-id}'/*, $params, $eTag, $graphVersion */);
    $facebookResponse = $facebookClient->sendRequest($request);
    
    $data = $facebookResponse->getDecodedBody();
    
    $wasSuccessful = $data['was_successful'];
    

    Batch Request Setup

    use Facebook\Entities\FacebookBatchRequest;
    
    $batchRequest = new FacebookBatchRequest(/* $facebookApp, '{access-token}', [$requests], $graphVersion */);
    

    Three ways to add requests to batch request

    Via constructor

    use Facebook\Entities\FacebookBatchRequest;
    use Facebook\Entities\FacebookRequest;
    
    // If $facebookApp and $accessToken on a `FacebookRequest` are null, it will fallback to the parent `FacebookBatchRequest` app & token.
    $requests = [
      new FacebookRequest(null, null, 'GET', '/me'),
      new FacebookRequest($facebookApp, '{access-token}', 'POST', '/me/feed', ['foo'=>'bar']),
      ];
    $batchRequest = new FacebookBatchRequest($facebookApp, '{access-token}', $requests);
    

    Via add() as an array

    use Facebook\Entities\FacebookRequest;
    
    // Numeric array:
    $requests = [
      new FacebookRequest(null, null, 'GET', '/me'),
      new FacebookRequest($facebookApp, '{access-token}', 'POST', '/me/feed', ['foo'=>'bar']),
      ];
    $batchRequest->add($requests);
    
    // ... OR ...
    
    // Associative array:
    // The key of the array will be used to assign a name to the request.
    $requests = [
      'named-request-one' => new FacebookRequest(null, null, 'GET', '/me'),
      'named-request-two' => new FacebookRequest($facebookApp, '{access-token}', 'POST', '/me/feed', ['foo'=>'bar']),
      ];
    $batchRequest->add($requests);
    

    Via add() as a FacebookRequest

    $batchRequest->add(new FacebookRequest(null, null, 'GET', '/me'));
    $batchRequest->add(new FacebookRequest($facebookApp, {access-token}, 'GET', '/me'), 'my-reqest-name');
    

    Getting a response from batch request

    $facebookBatchResponse = $facebookClient->sendBatchRequest($batchRequest);
    
    foreach ($facebookBatchResponse as $response) {
      if (!$response->isError()) {
        // $response is a `FacebookResponse` entity
      } else {
        $e = $response->getThrownException();
        echo $e->getMessage();
      }
    }
    

    Helpers

    You also pass along the FacebookApp and FacebookClient into the helpers like so:

    $app = new FacebookApp('123', 'foo_app_secret');
    $helper = new FacebookRedirectLoginHelper($app);
    

    AccessToken

    The AccessToken entity requires FacebookApp and FacebookClient for requests that call Graph. For example:

    $accessTokenFromCode = AccessToken::getAccessTokenFromCode('foo_code', $app, $client);
    

    I think this could be done better for the future. I'd like to simplify the AccessToken entity to only hold data about the access token. And any calls to graph could be done with a FacebookAccessTokenHelper. What do you guys think?

    Simplified FacebookHttpClientInterface

    I also simplified the FacebookHttpClientInterface so that the request headers could be sent as an argument in the send() method.

    Integration Tests Labled

    The tests that actually touch Graph are labeled "integration". So you can run the test suite with:

    $ phpunit --exclude-group integration
    

    And it won't touch the live version of Graph. So now we can incorporate Travis CI without any issues! :)

    TODO

    For the next few PR's:

    • Factories to make FacebookRequest's and FacebookBatchRequest's
    • Collections on GrahObject
    • Adding GraphList with pagination
    opened by SammyK 32
  • Getting different values for $_SESSION[

    Getting different values for $_SESSION["FBRLH_state"] and $_GET['state'] on fb callback

    Hey Guys,

    I'm developing my website ---- and I'm having an issue with my Facebook callback page. I'm getting this error: Facebook SDK returned an error: Cross-site request forgery validation failed. The "state" param from the URL and session do not match..

    I was reading Facebook PHP SDK and I found that when you call $fb->getRedirectLoginHelper() a new value for $_SESSION["FBRLH_state"] will be assigned so when I call it again on my callback (because I need to get the accessToken) , a error will happen because ($_SESSION["FBRLH_state"] != $_GET['state']);

    https://github.com/facebook/facebook-php-sdk-v4/blob/master/src/Facebook/Helpers/FacebookRedirectLoginHelper.php

    public function __construct(OAuth2Client $oAuth2Client, PersistentDataInterface $persistentDataHandler = null, UrlDetectionInterface $urlHandler = null, PseudoRandomStringGeneratorInterface $prsg = null)
        {
            $this->oAuth2Client = $oAuth2Client;
            $this->persistentDataHandler = $persistentDataHandler ?: new FacebookSessionPersistentDataHandler();
            $this->urlDetectionHandler = $urlHandler ?: new FacebookUrlDetectionHandler();
            $this->pseudoRandomStringGenerator = PseudoRandomStringGeneratorFactory::createPseudoRandomStringGenerator($prsg);
        }
    

    Index page:

    $fb = $this->facebook;
    $helper = $fb->getRedirectLoginHelper();
    $permissions = ['email','public_profile','user_friends'];
    $loginUrl = $helper->getLoginUrl('https://fleacollege.com/login/facebook', $permissions);
    
    //passing url from controller to view :
    $this->view->facebookURL = $loginUrl;
    

    Callback page:

    $fb = $this->facebook;
    $helper = $fb->getRedirectLoginHelper();
    
    try {
    $accessToken = $helper->getAccessToken();
    } 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() . "</br>";
    exit;
    }
    
    $accessToken = $helper->getAccessToken();
    echo $_SESSION["FBRLH_state"] . "</br>";
    echo $_GET['state'];
    

    return from echo:

    e7fca1bfcb37fe3262468c068b72a3de
    e0eec1b15428c9429846d2b41753473f
    

    Anyone know why this is happening? I just followed https://developers.facebook.com/docs/php/howto/example_facebook_login/5.0.0

    opened by marcelopiomsf 29
  • Bug when using a valid access token by invalid appsecret_proof that is disabled

    Bug when using a valid access token by invalid appsecret_proof that is disabled

    Hi, I'm using the latest version of the sdk (5.5.0) I've unset the appsecret_proof in the app advanced config, but when I use a valid access token got directly from the api tools. But I get all the time the next error:

    Invalid appsecret_proof provided in the API argument

    This is a code issue, due I'm using the main README.md code that should works but don't. Please, check it and fix it this, so we can not use que facebook until now.

    opened by mvcmaker 28
  • Batch upload multiple photos to album

    Batch upload multiple photos to album

    I am trying to use the batch upload to work with photos but I am getting an error.

    For some reason it uploads the first photo but the other photos throw an error.

    Is there a quick guide to get this to work?

    opened by tosh001 25
  • email return null for public email

    email return null for public email

    it returns email only for sdk registered user and return null for all users even if i login using email. $response = $fb->get('/me?fields=id,name,first_name,last_name,email,gender,education,birthday,location,picture,link', $accessToken);

    but it returns null except my registered account.

    opened by gaurvivek 24
  • The ultimate SemVer discussion: how?

    The ultimate SemVer discussion: how?

    You heard it on PHP Roundtable first ladies and gentlemen! Straight from the horse's mouth, @gfosco is open to supporting SemVer! Yay! :D

    But! The question is: how?

    The current repo is prefixed with -v4. I know we can rename, but GitHub doesn't support 301 redirects which can be problematic for all the links pointing to this repo. But once it's renamed, it should be pretty trivial (I think) to point packagist to the new repo & people can still use composer like they've always done.

    Anyone ever done this before & have advice on how we can rename the repo without too much disruption? :) cc @yguedidi @mtdowling

    Yay for 5.0! :D

    opened by SammyK 24
  • PHP 8.1: Serializable interface is deprecated

    PHP 8.1: Serializable interface is deprecated

    Error in PHP 8.1 Facebook\FacebookApp implements the Serializable interface, which is deprecated. Implement __serialize() and __unserialize() instead (or in addition, if support for old PHP versions is necessary)

    opened by stanislav-janu 0
  • getLogoutUrl broken again?

    getLogoutUrl broken again?

    Hi All.

    I'm calling $helper->getLogoutUrl($access_token, $redirectUrl); and it doesn't log me out of facebook. I know it's a valid token and the redirect actually works, but my user stays logged-in to facebook no matter what.

    Is there something specific beyond the redirect that I need to do? I need to log my user out of facebook so that they can switch to a different facebook user before using my application. I do not use facebook to authenticate in my app.

    TIA

    opened by dwhalenenr 0
  • Issues when running on live app

    Issues when running on live app

    I have an app that's pulling business page data (star reviews) working on a testing app, but as soon as I switch to a live app it no longer works.

    Can someone confirm this is working.

    opened by wes-kay 0
  • Support Gaming Graph Domain

    Support Gaming Graph Domain

    If APP client use the SDK of Gaming Graph Domain, APP server have to request the URL of Gaming Graph Domain, or add 'GG|' in front APP_ID at Facebook\FacebookApp@getAccessToken. This PR privode a simple way to toggle to use Gaming Graph URL. Reference Gaming Graph Domain (graph.fb.gg)

    CLA Signed 
    opened by KiddoLin 0
  • What is the alternative permeation for manage_pages and publishh_pages since they are  deprecated

    What is the alternative permeation for manage_pages and publishh_pages since they are deprecated

    Dear all. I want to post a video on my Facebook page with the name of the page. What is the correct permeation that I need to have on my app?

    Reagrads

    opened by beshoo 1
Owner
Meta Archive
These projects have been archived and are generally unsupported, but are still available to view and use
Meta Archive
a tool to get Facebook data, and some Facebook bots, and extra tools found on Facebook Toolkit ++.

FACEBOOK TOOLKIT a tool to get Facebook data, and some Facebook bots, and extra tools found on Facebook Toolkit ++. Graph API Facebook. Made with ❤️ b

Wahyu Arif Purnomo 569 Dec 27, 2022
Facebook SDK for PHP (v6) - allows you to access the Facebook Platform from your PHP app

Facebook SDK for PHP (v6) This repository contains the open source PHP SDK that allows you to access the Facebook Platform from your PHP app. Installa

null 0 Aug 10, 2022
SDK of the LINE Login API for PHP

LINE Login for PHP SDK of the LINE Login API for PHP Documentation See the official API documentation for more information. Installation Use the packa

null 4 Sep 15, 2022
An SDK built to facilitate application development for Facebook Ads API.

Facebook Business SDK for PHP Introduction The Facebook Business SDK is a one-stop shop to help our partners better serve their businesses. Partners a

Meta 719 Dec 28, 2022
Zoho CRM API SDK is a wrapper to Zoho CRM APIs. By using this sdk, user can build the application with ease

Archival Notice: This SDK is archived. You can continue to use it, but no new features or support requests will be accepted. For the new version, refe

null 81 Nov 4, 2022
The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructure and leverage the power of 1Password Secrets Automation

1Password Connect PHP SDK The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructu

Michelangelo van Dam 12 Dec 26, 2022
Fully unit tested Facebook SDK v5 integration for Laravel & Lumen

Laravel Facebook SDK A fully unit-tested package for easily integrating the Facebook SDK v5 into Laravel and Lumen 5.0, 5.1, 5.2, & 5.3. This is packa

Sammy Kaye Powers 697 Nov 6, 2022
Shopware PHP SDK is a simple SDK implementation of Shopware 6 APIs

Shopware PHP SDK is a simple SDK implementation of Shopware 6 APIs. It helps to access the API in an object-oriented way.

Thuong Le 77 Dec 19, 2022
Symfony bundle integrating server-sent native notifications

Symfony UX Notify Symfony UX Notify is a Symfony bundle integrating server-sent native notifications in Symfony applications using Mercure. It is part

Symfony 6 Dec 15, 2022
Esse SDK em PHP foi desenvolvido no intuito de tornar mais prático a integração com nossa API.

Sobre Beedoo SDK Acessar documentação completa da Beedoo API. A API é organizada seguindo a arquitetura REST, boas práticas, convenções e padrões como

Beedoo Edtech 5 Dec 2, 2021
A PHP SDK for accessing the OpenAI GPT-3 API

OpenAI GPT-3 Api Client in PHP Installation You can install the package via composer: composer require orhanerday/open-ai Usage use Orhanerday\OpenAi\

Orhan erday 462 Jan 2, 2023
PHP SDK for the Sellix Developers API (developers.sellix.io)

PHP SDK for the Sellix Developers API (developers.sellix.io). Quickly get started and create products, payments and more using PHP.

Sellix 7 Nov 23, 2022
Mark Sign - Gateway API PHP SDK

Mark Sign - Gateway API PHP SDK

Mark Sign 3 Feb 22, 2022
Light PHP SDK to interact with the Doma(in)Validity API.

Doma(in)Validity PHP SDK. Light PHP SDK to interact with the Doma(in)Validity API. Usage <?php require_once 'vendor/autoload.php'; use Domainvalidit

Doma(In)Validity 2 May 3, 2022
A PHP SDK for the ScreenshotOne.com API to take screenshots of any URL

phpsdk An official Screenshot API client for PHP. It takes minutes to start taking screenshots. Just sign up to get access and secret keys, import the

ScreenshotOne.com 4 Jun 14, 2022
BT Open API SDK in PHP

Mosel, a sdk package for BT open APIs This package is still under construction (july 13th 2022). Open Api are described in the Bouygues Telecom Develo

BboxLab 0 Jul 7, 2022
This API provides functionality for creating and maintaining users to control a simple To-Do-List application. The following shows the API structure for users and tasks resources.

PHP API TO-DO-LIST v.2.0 This API aims to present a brief to consume a API resources, mainly for students in the early years of Computer Science cours

Edson M. de Souza 6 Oct 13, 2022
ExchangeRatesAPI - Currency Exchange Rates API SDK

ExchangeRatesAPI - Currency Exchange Rates API SDK This is an unofficial wrapper for the awesome, free ExchangeRatesAPI, which provides exchange rate

Ben Major 33 Jun 28, 2022
The NKN open API is a blockchain-to-database parser with an easy to use interface written in PHP

The NKN open API is a blockchain-to-database parser with an easy to use interface written in PHP. We're using Laravel as our framework to provide a clean and maintainable code.

Rule110 - The NKN open source community 7 Jun 26, 2022