Download the PHP package scottybo/laravel-facebook-sdk without Composer

On this page you can find all versions of the php package scottybo/laravel-facebook-sdk. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-facebook-sdk

Laravel Facebook SDK

Build Status Latest Stable Version Total Downloads License

A fully unit-tested package for easily integrating the Facebook SDK v5 into Laravel 6.


Shouldn't I just use Laravel Socialite?

Laravel 5 comes with support for Socialite which allows you to authenticate with OAuth 2.0 providers. Facebook Login uses OAuth 2.0 and therefore Socialite supports Facebook Login.

If all you need is to authenticate an app and grab a user access token to pull basic data on a user, then Socialite or The PHP League's Facebook OAuth Client should suffice for your needs.

But if you need any of the following features, you'll want to tie in the Facebook PHP SDK with this package:

Installation

Add the Laravel Facebook SDK package to your composer.json file.

composer require scottybo/laravel-facebook-sdk

Auto-discovery: As of version 3.5.0, the Laravel Facebook SDK supports auto-discovery for Laravel 5.5 and greater.

Service Provider

In your app config, add the LaravelFacebookSdkServiceProvider to the providers array.

For Lumen, add the provider to your bootstrap/app.php file.

Facade (optional)

If you want to make use of the facade, add it to the aliases array in your app config.

But there are don't use facades.

IoC container

The IoC container will automatically resolve the LaravelFacebookSdk dependencies for you. You can grab an instance of LaravelFacebookSdk from the IoC container in a number of ways.

Configuration File

Note: As of version 3.4.0, publishing the config file is optional as long as you set your required config values.

Also note: The config file contains a default Graph API version that gets bumped up to the latest stable version periodically which might cause a breaking change when you update this package in a minor or patch version. It is recommended that you still publish the config file and update the Graph API version on your own time to prevent breaking things.

After creating an app in Facebook, you'll need to provide the app ID and secret. In Laravel you can publish the configuration file with artisan.

Where's the file? Laravel 5 will publish the config file to /config/laravel-facebook-sdk.php.

In Lumen you'll need to manually copy the config file from /src/config/laravel-facebook-sdk.php to your config folder in your base project directory. Lumen doesn't have a /config folder by default so you'll need to create it if you haven't already.

Required config values

You'll need to update the app_id and app_secret values in the config file with your app ID and secret.

By default the configuration file will look to environment variables for your app ID and secret. It is recommended that you use environment variables to store this info in order to protect your app secret from attackers. Make sure to update your /.env file with your app ID & secret.

User Login From Redirect Example

Here's a full example of how you might log a user into your app using the redirect method.

This example also demonstrates how to exchange a short-lived access token with a long-lived access token and save the user to your users table if the entry doesn't exist.

Finally it will log the user in using Laravel's built-in user authentication.

Sessions in Lumen: The "login from redirect" functionality relies on sessions to store a CSRF token. Since sessions don't exist in Lumen 5.2+, you'll need to obtain an access token using a Graph API Explorer (make sure to select your app from the "Application" drop down).

For more details on the ways to authenticate a user, see Facebook Login.

Making Requests To Facebook

Requests to Facebook are made via the Graph API. This package is a Laravel wrapper for the official Facebook PHP SDK v5 so all the methods available to the official SDK are also available in this package.

Get User Info

The following snippet will retrieve a User node representing the logged in user.

See more about the get() method.

Facebook Login

When we say "log in with Facebook", we really mean "obtain a user access token to make calls to the Graph API on behalf of the user." This is done through Facebook via OAuth 2.0. There are a number of ways to log a user in with Facebook using what the Facbeook PHP SDK calls "helpers".

The four supported login methods are:

  1. Login From Redirect (OAuth 2.0)
  2. Login From JavaScript (with JS SDK cookie)
  3. Login From App Canvas (with signed request)
  4. Login From Page Tab (with signed request)

Login From Redirect

One of the most common ways to log a user into your app is by using a redirect URL.

The idea is that you generate a unique URL that the user clicks on. Once the user clicks the link they will be redirected to Facebook asking them to grant any permissions your app is requesting. Once the user responds, Facebook will redirect the user back to a callback URL that you specify with either a successful response or an error response.

The redirect helper can be obtained using the SDK's getRedirectLoginHelper() method.

Generating a login URL

You can get a login URL just like you you do with the Facebook PHP SDK v5.

But if you set the default_redirect_uri callback URL in the config file, you can use the getLoginUrl() wrapper method which will default the callback URL (default_redirect_uri) and permission scope (default_scope) to whatever you set in the config file.

Alternatively you can pass the permissions and a custom callback URL to the wrapper to overwrite the default config.

Note: Since the list of permissions sometimes changes but the callback URL usually stays the same, the permissions array is the first argument in the getLoginUrl() wrapper method which is the reverse of the SDK's method getRedirectLoginHelper()->getLoginUrl($url, $permissions).

Obtaining an access token from a callback URL

After the user has clicked on the login link from above and confirmed or denied the app permission requests, they will be redirected to the specified callback URL.

The standard "SDK" way to obtain an access token on the callback URL is as follows:

There is a wrapper method for getRedirectLoginHelper()->getAccessToken() in LaravelFacebookSdk called getAccessTokenFromRedirect() that defaults the callback URL to the laravel-facebook-sdk.default_redirect_uri config value.

Login From JavaScript

If you're using the JavaScript SDK, you can obtain an access token from the cookie set by the JavaScript SDK.

By default the JavaScript SDK will not set a cookie, so you have to explicitly enable it with cookie: true when you init() the SDK.

After you have logged a user in with the JavaScript SDK using FB.login(), you can obtain a user access token from the signed request that is stored in the cookie that was set by the JavaScript SDK.

Login From App Canvas

TokenMismatchException: Default Laravel installations will throw a TokenMismatchException when you try to view your app in Facebook. See how to fix this issue.

If your app lives within the context of a Facebook app canvas, you can obtain an access token from the signed request that is POST'ed to your app on the first page load.

Note: The canvas helper only obtains an existing access token from the signed request data received from Facebook. If the user visiting your app has not authorized your app yet or their access token has expired, the getAccessToken() method will return null. In that case you'll need to log the user in with either JavaScript.

Use the SDK's canvas helper to obtain the access token from the signed request data.

Login From Page Tab

TokenMismatchException: Default Laravel installations will throw a TokenMismatchException when you try to view your page tab in Facebook. See how to fix this issue.

If your app lives within the context of a Facebook Page tab, that is the same as an app canvas and the "Login From App Canvas" method will also work to obtain an access token. But a Page tab also has additional data in the signed request.

The SDK provides a Page tab helper to obtain an access token from the signed request data within the context of a Page tab.

Other authorization requests

Facebook supports two other types of authorization URL's - rerequests and re-authentications.

Rerequests

Rerequests (or re-requests?) ask the user again for permissions they have previously declined. It's important to use a rerequest URL for this instead of just redirecting them with the normal log in link because:

Once someone has declined a permission, the Login Dialog will not re-ask them for it unless you explicitly tell the dialog you're re-asking for a declined permission. - Facebook Documentation

You can generate a rerequest URL using the getReRequestUrl() method.

Re-authentications

Re-authentications force a user to confirm their identity by asking them to enter their Facebook account password again. This is useful for adding another layer of security before changing or view sensitive data on your web app.

You can generate a re-authentication URL using the getReAuthenticationUrl() method.

Saving the Access Token

In most cases you won't need to save the access token to a database unless you plan on making requests to the Graph API on behalf of the user when they are not browsing your app (like a 3AM CRON job for example).

After you obtain an access token, you can store it in a session to be used for subsequent requests.

Then in each script that makes calls to the Graph API you can pull the token out of the session and set it as the default.

Saving data from Facebook in the database

Saving data received from the Graph API to a database can sometimes be a tedious endeavor. Since the Graph API returns data in a predictable format, the SyncableGraphNodeTrait can make saving the data to a database a painless process.

Any Eloquent model that implements the SyncableGraphNodeTrait will have the createOrUpdateGraphNode() method applied to it. This method really makes it easy to take data that was returned directly from Facebook and create or update it in the local database.

For example if you have an Eloquent model named Event, here's how you might grab a specific event from the Graph API and insert it into the database as a new entry or update an existing entry with the new info.

The createOrUpdateGraphNode() will automatically map the returned field names to the column names in your database. If, for example, your column names on the events table don't match the field names for an Event node, you can map the fields.

Field Mapping

Since the names of the columns in your database might not match the names of the fields of the Graph nodes, you can map the field names in your User model using the $graph_node_field_aliases static variable.

The keys of the array are the names of the fields on the Graph node. The values of the array are the names of the columns in the local database.

Specifying "fillable" fields

By default the createOrUpdateGraphNode() method will try to insert all the fields of a node into the database. But sometimes the Graph API will return fields that you didn't specifically ask for and don't exist in your database. In those cases we can white list specific fields with the $graph_node_fillable_fields property.

Use the name of the database column. For example, if you've aliased the id field to the facebook_id column in your databse, you'll want to specify facebook_id in your $graph_node_fillable_fields array.

Nested field mapping

Since the Graph API will return some of the fields from a request as other nodes/objects, you can reference the fields on those using Laravel's array_dot() notation.

An example might be making a request to the /me/events endpoint and looping through all the events and saving them to your Event model. The Event node will return the place.location fields as Location nodes. The response data might look like this:

Let's assume you have an event table like this:

Here's how you would map the nested fields to your database table in your Event model:

Date formats

The Facebook PHP SDK will convert most date formats into instances of DateTime. This can be problematic when you want to insert a date/time value into the database (e.g. the start_time field of an Event node).

By default the SyncableGraphNodeTrait will convert all DateTime instances to the following date() format:

Y-m-d H:i:s

That should the proper format for most cases on most relational databases. But this format is missing the timezone which might be important to your application. Furthermore if you're storing the date/time values in a different format, you'll want to customize the format that DateTime instances get converted to. To do this just add a $graph_node_date_time_to_string_format property to your model and set it to any valid date format.

Logging The User Into Laravel

The Laravel Facebook SDK makes it easy to log a user in with Laravel's built-in authentication driver.

Updating The Users Table

In order to get Facebook authentication working with Laravel's built-in authentication, you'll need to store the Facebook user's ID in your user's table.

Naturally you'll need to create a column for every other piece of information you want to keep about the user.

You can store the access token in the database if you need to make requests on behalf of the user when they are not browsing your app (like a 3AM cron job). But in general you won't need to store the access token in the database.

You'll need to generate a migration to modify your users table and add any new columns.

Note: Make sure to change <name-of-users-table> to the name of your user table.

Now update the migration file to include the new fields you want to save on the user. At minimum you'll need to save the Facebook user ID.

Don't forget to run the migration.

If you plan on using the Facebook user ID as the primary key, make sure you have a column called id that is an unsigned big integer and indexed. If you are storing the Facebook ID in a different field, make sure that field exists in the database and make sure to map to it in your model to your custom id name.

If you're using the Eloquent ORM and storing the access token in the database, make sure to hide the access_token field from possible exposure in your User model.

Don't forget to add the SyncableGraphNodeTrait to your user model so you can sync your model with data returned from the Graph API.

Logging the user into Laravel

After the user has logged in with Facebook and you've obtained the user ID from the Graph API, you can log the user into Laravel by passing the logged in user's User model to the Auth::login() method.

Working With Multiple Apps

If you have multiple Facebook apps that you'd like to use in the same script or you want to tweak the settings during runtime, you can create a new instance of LaravelFacebookSdk with the custom settings.

Error Handling

The Facebook PHP SDK throws Facebook\Exceptions\FacebookSDKException exceptions. Whenever there is an error response from Graph, the SDK will throw a Facebook\Exceptions\FacebookResponseException which extends from Facebook\Exceptions\FacebookSDKException. If a Facebook\Exceptions\FacebookResponseException is thrown you can grab a specific exception related to the error from the getPrevious() method.

The LaravelFacebookSdk does not throw any custom exceptions.

Troubleshooting

Getting a TokenMismatchException with canvas apps

If your app is being served from within the context of an app canvas or Page tab, you'll likely see a TokenMismatchException error when you try to view the app on Facebook. This is because Facebook will render your app by sending a POST request to it with a signed_request param and since Laravel 5 has CSRF protection that is enabled for every non-read request, the error is triggered.

Although it's possible to disable this feature completely, it's certainly not recommended as CSRF protection is an important security feature to have on your site and it should be enabled on every route by default.

Disable CSRF on endpoints in Laravel 5.1 & 5.2

Add an exception to your canvas endpoint to the $except array in your app\Http\Middleware\VerifyCsrfToken.php file.

Disable CSRF on endpoints in Laravel 5.0

In Laravel 5.0 it was a bit trickier to disable CSRF verification but there is an article that explains how to disable CSRF protection for specific routes in Laravel 5.0.

In your app\Http\Middleware\VerifyCsrfToken.php file, add an excludedRoutes() method. Then create an array of routes that are endpoints to you canvas app or page tab. The complete file looks like this:

Getting a QueryException when saving a User

If you're using MySQL, you might get a QueryException when saving a user to the database with createOrUpdateGraphNode().

This is because by default, strict mode is enabled which sets sql_mode to include STRICT_TRANS_TABLES. Since we don't need a password for users logging in with Facebook, this field will be empty. A workaround to this error is to set strict to false for the MySQL diver in your config/database.php file.

Testing

The tests are written with phpunit. You can run the tests from the root of the project directory with the following command.

Contributing

Please see CONTRIBUTING for details.

Credits

This package is maintained by Scott Bowler. See a full list of contributors.

License

The MIT License (MIT). Please see License File for more information.


All versions of laravel-facebook-sdk with dependencies

PHP Build Version
Package Version
Requires php Version >=7.3
illuminate/auth Version ~7
illuminate/config Version ~7
illuminate/database Version ~7
illuminate/routing Version ~7
illuminate/session Version ~7
illuminate/support Version ~7
scottybo/facebook-graph-sdk Version ^5.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package scottybo/laravel-facebook-sdk contains the following files

Loading the files please wait ....