nicodwik/laravel-facebook-sdk

为 Laravel 10.x 完全单元测试的 Facebook SDK v5 集成

3.3.2 2023-04-26 09:47 UTC

This package is auto-updated.

Last update: 2024-09-26 12:52:36 UTC


README

Build Status Latest Stable Version Total Downloads License

一个完全单元测试的包,用于轻松将 Facebook SDK v5 集成到 Laravel 9。

我应该使用 Laravel Socialite 吗?

Laravel 5 内置了对 Socialite 的支持,允许您使用 OAuth 2.0 提供商进行身份验证。Facebook 登录使用 OAuth 2.0,因此 Socialite 支持 Facebook 登录。

如果您只需要验证应用程序并获取用户访问令牌以获取用户的基本数据,那么 Socialite 或 The PHP League 的 Facebook OAuth Client 应该满足您的需求。

但如果您需要以下任何功能,则希望将此包与 Facebook PHP SDK 绑定:

安装

将 Laravel Facebook SDK 包添加到您的 composer.json 文件。

composer require moomak/laravel-facebook-sdk

自动发现:从版本 3.5.0 开始,Laravel Facebook SDK 支持 Laravel 5.5 及更高版本的 自动发现

服务提供者

在您的应用程序配置中,将 LaravelFacebookSdkServiceProvider 添加到提供者数组。

'providers' => [
    Moomak\LaravelFacebookSdk\LaravelFacebookSdkServiceProvider::class,
    ];

对于 Lumen,将提供者添加到您的 bootstrap/app.php 文件。

$app->register(Moomak\LaravelFacebookSdk\LaravelFacebookSdkServiceProvider::class);

外观(可选)

如果您想使用外观,请将其添加到应用程序配置中的别名数组。

'aliases' => [
    'Facebook' => Moomak\LaravelFacebookSdk\FacebookFacade::class,
    ];

但还有 更好的方法 来使用此包,即 不要使用外观

IoC 容器

IoC 容器将自动为您解决 LaravelFacebookSdk 依赖项。您可以通过多种方式从 IoC 容器中获取 LaravelFacebookSdk 实例。

// Directly from the IoC
$fb = App::make('Moomak\LaravelFacebookSdk\LaravelFacebookSdk');
// Or in PHP >= 5.5
$fb = app(Moomak\LaravelFacebookSdk\LaravelFacebookSdk::class);

// From a constructor
class FooClass {
    public function __construct(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
       // . . .
    }
}

// From a method
class BarClass {
    public function barMethod(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
       // . . .
    }
}

// Or even a closure
Route::get('/facebook/login', function(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
    // . . .
});

配置文件

注意:从版本 3.4.0 开始,只要设置了您的 必需配置值,发布配置文件是可选的。

另外注意:配置文件包含一个默认的 Graph API 版本,该版本定期提升到最新稳定版本,这可能会在您更新此包的次要或补丁版本时导致破坏性更改。建议您仍然发布配置文件,并在自己方便的时候更新 Graph API 版本,以防止破坏事物。

在Facebook中创建应用后,您需要提供应用ID和密钥。在Laravel中,您可以使用artisan命令发布配置文件。

$ php artisan vendor:publish --provider="Moomak\LaravelFacebookSdk\LaravelFacebookSdkServiceProvider" --tag="config"

配置文件在哪里? Laravel 5将配置文件发布到/config/laravel-facebook-sdk.php

在Lumen中,您需要手动将配置文件从/src/config/laravel-facebook-sdk.php复制到您基础项目目录中的配置文件夹。Lumen默认没有/config文件夹,因此如果您还没有创建,则需要创建它。

必需的配置值

您需要在配置文件中更新app_idapp_secret值,使用您的应用ID和密钥

默认情况下,配置文件将查找环境变量以获取您的应用ID和密钥。建议您使用环境变量来存储此信息,以保护您的应用密钥免受攻击者侵害。请确保更新您的/.env文件以包含您的应用ID和密钥。

FACEBOOK_APP_ID=1234567890
FACEBOOK_APP_SECRET=SomeFooAppSecret

重定向示例中的用户登录

以下是一个使用重定向方法登录用户的完整示例。

此示例还演示了如何将短期访问令牌交换为长期访问令牌,如果条目不存在,则将其保存到您的users表中。

最后,它将使用Laravel内置的用户身份验证登录用户。

Lumen中的会话:“从重定向登录”功能依赖于会话来存储CSRF令牌。由于Lumen 5.2+中没有会话,您需要使用不同的方法来获取访问令牌。对于测试,您可以直接从Graph API Explorer获取访问令牌(确保从“应用程序”下拉菜单中选择您的应用)。

// Generate a login URL
Route::get('/facebook/login', function(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb)
{
    // Send an array of permissions to request
    $login_url = $fb->getLoginUrl(['email']);

    // Obviously you'd do this in blade :)
    echo '<a href="' . $login_url . '">Login with Facebook</a>';
});

// Endpoint that is redirected to after an authentication attempt
Route::get('/facebook/callback', function(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb)
{
    // Obtain an access token.
    try {
        $token = $fb->getAccessTokenFromRedirect();
    } catch (Facebook\Exceptions\FacebookSDKException $e) {
        dd($e->getMessage());
    }

    // Access token will be null if the user denied the request
    // or if someone just hit this URL outside of the OAuth flow.
    if (! $token) {
        // Get the redirect helper
        $helper = $fb->getRedirectLoginHelper();

        if (! $helper->getError()) {
            abort(403, 'Unauthorized action.');
        }

        // User denied the request
        dd(
            $helper->getError(),
            $helper->getErrorCode(),
            $helper->getErrorReason(),
            $helper->getErrorDescription()
        );
    }

    if (! $token->isLongLived()) {
        // OAuth 2.0 client handler
        $oauth_client = $fb->getOAuth2Client();

        // Extend the access token.
        try {
            $token = $oauth_client->getLongLivedAccessToken($token);
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            dd($e->getMessage());
        }
    }

    $fb->setDefaultAccessToken($token);

    // Save for later
    Session::put('fb_user_access_token', (string) $token);

    // Get basic info on the user from Facebook.
    try {
        $response = $fb->get('/me?fields=id,name,email');
    } catch (Facebook\Exceptions\FacebookSDKException $e) {
        dd($e->getMessage());
    }

    // Convert the response to a `Facebook/GraphNodes/GraphUser` collection
    $facebook_user = $response->getGraphUser();

    // Create the user if it does not exist or update the existing entry.
    // This will only work if you've added the SyncableGraphNodeTrait to your User model.
    $user = App\User::createOrUpdateGraphNode($facebook_user);

    // Log the user into Laravel
    Auth::login($user);

    return redirect('/')->with('message', 'Successfully logged in with Facebook');
});

有关用户身份验证的更多详细信息,请参阅Facebook登录

向 Facebook 发送请求

对Facebook的请求通过Graph API进行。此包是官方Facebook PHP SDK v5的Laravel包装器,因此所有官方SDK可用的方法也在此包中可用。

获取用户信息

以下代码片段将检索表示已登录用户的用户节点

try {
  $response = $fb->get('/me?fields=id,name,email', 'user-access-token');
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
  dd($e->getMessage());
}

$userNode = $response->getGraphUser();
printf('Hello, %s!', $userNode->getName());

有关更多关于get()方法的详细信息。

Facebook 登录

当我们说“使用Facebook登录”时,我们的真正意思是“通过Facebook获取用户访问令牌以代表用户调用Graph API”。这是通过OAuth 2.0通过Facebook完成的。有几种方法可以使用Facebook PHP SDK的“辅助工具”来使用Facebook登录用户。

支持的四种登录方法如下

  1. 从重定向登录(OAuth 2.0)
  2. 从JavaScript登录(使用JS SDK cookie)
  3. 从应用画布登录(使用签名请求)
  4. 从页面标签登录(使用签名请求)

从重定向登录

将用户登录到您的应用中最常见的方法之一是使用重定向URL。

想法是生成一个唯一的URL,用户点击该URL。一旦用户点击链接,他们将被重定向到Facebook,要求他们授予您的应用程序请求的任何权限。一旦用户作出回应,Facebook将用户重定向回您指定的回调URL,并带有成功响应或错误响应。

可以通过使用SDK的getRedirectLoginHelper()方法来获取重定向助手。

生成登录URL

您可以通过与Facebook PHP SDK v5相同的方式获取登录URL。

Route::get('/facebook/login', function(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
    $login_link = $fb
            ->getRedirectLoginHelper()
            ->getLoginUrl('https://exmaple.com/facebook/callback', ['email', 'user_events']);
    
    echo '<a href="' . $login_link . '">Log in with Facebook</a>';
});

但是,如果您在配置文件中设置了default_redirect_uri回调URL,则可以使用getLoginUrl()包装方法,该方法将默认回调URL(default_redirect_uri)和权限范围(default_scope)设置为配置文件中设置的值。

$login_link = $fb->getLoginUrl();

或者,您可以将权限和自定义回调URL传递给包装器以覆盖默认配置。

注意:由于权限列表有时会更改,但回调URL通常保持不变,因此权限数组是getLoginUrl()包装方法中的第一个参数,这与SDK的getRedirectLoginHelper()->getLoginUrl($url, $permissions)方法相反。

$login_link = $fb->getLoginUrl(['email', 'user_status'], 'https://exmaple.com/facebook/callback');
// Or, if you want to default to the callback URL set in the config
$login_link = $fb->getLoginUrl(['email', 'user_status']);

从回调URL获取访问令牌

用户点击上面的登录链接并确认或拒绝应用程序权限请求后,将被重定向到指定的回调URL。

在回调URL上获取访问令牌的“标准SDK”方法如下

Route::get('/facebook/callback', function(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
    try {
        $token = $fb
            ->getRedirectLoginHelper()
            ->getAccessToken();
    } catch (Facebook\Exceptions\FacebookSDKException $e) {
        // Failed to obtain access token
        dd($e->getMessage());
    }
});

LaravelFacebookSdk中有一个包装方法,用于getRedirectLoginHelper()->getAccessToken(),称为getAccessTokenFromRedirect(),它将回调URL默认为laravel-facebook-sdk.default_redirect_uri配置值。

Route::get('/facebook/callback', function(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
    try {
        $token = $fb->getAccessTokenFromRedirect();
    } catch (Facebook\Exceptions\FacebookSDKException $e) {
        // Failed to obtain access token
        dd($e->getMessage());
    }
    
    // $token will be null if the user denied the request
    if (! $token) {
        // User denied the request
    }
});

通过JavaScript进行登录

如果您使用的是JavaScript SDK,您可以从JavaScript SDK设置的cookie中获取访问令牌。

默认情况下,JavaScript SDK不会设置cookie,因此您必须在初始化SDK时明确启用它,使用cookie: true

FB.init({
  appId      : 'your-app-id',
  cookie     : true,
  version    : 'v2.10'
});

使用FB.login()通过JavaScript SDK登录用户后,您可以从存储在JavaScript SDK设置的cookie中的签名请求中获取用户访问令牌。

Route::get('/facebook/javascript', function(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
    try {
        $token = $fb->getJavaScriptHelper()->getAccessToken();
    } catch (Facebook\Exceptions\FacebookSDKException $e) {
        // Failed to obtain access token
        dd($e->getMessage());
    }

    // $token will be null if no cookie was set or no OAuth data
    // was found in the cookie's signed request data
    if (! $token) {
        // User hasn't logged in using the JS SDK yet
    }
});

从App Canvas进行登录

TokenMismatchException:默认的Laravel安装将在您尝试在Facebook中查看您的应用程序时抛出TokenMismatchException。请参阅如何修复此问题

如果您的应用程序位于Facebook应用程序画布的上下文中,您可以从第一次页面加载时发送到您的应用程序的签名请求中获取访问令牌。

注意:画布助手仅从Facebook接收到的签名请求数据中获取现有的访问令牌。如果访问您的应用程序的用户尚未授权您的应用程序或访问令牌已过期,则getAccessToken()方法将返回null。在这种情况下,您需要使用重定向JavaScript登录用户。

使用SDK的画布助手从签名请求数据中获取访问令牌。

Route::match(['get', 'post'], '/facebook/canvas', function(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
    try {
        $token = $fb->getCanvasHelper()->getAccessToken();
    } catch (Facebook\Exceptions\FacebookSDKException $e) {
        // Failed to obtain access token
        dd($e->getMessage());
    }

    // $token will be null if the user hasn't authenticated your app yet
    if (! $token) {
        // . . .
    }
});

从页面标签进行登录

TokenMismatchException:默认的Laravel安装将在您尝试在Facebook中查看您的页面标签时抛出TokenMismatchException。请参阅如何修复此问题

如果你的应用位于Facebook页面标签页的上下文中,这相当于应用画布,并且“从应用画布登录”方法也可以用来获取访问令牌。但是,页面标签页在签名请求中还有其他数据。

SDK提供页面标签页助手,用于在页面标签页的上下文中从签名请求数据中获取访问令牌。

Route::match(['get', 'post'], '/facebook/page-tab', function(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
    try {
        $token = $fb->getPageTabHelper()->getAccessToken();
    } catch (Facebook\Exceptions\FacebookSDKException $e) {
        // Failed to obtain access token
        dd($e->getMessage());
    }

    // $token will be null if the user hasn't authenticated your app yet
    if (! $token) {
        // . . .
    }
});

其他授权请求

Facebook支持两种其他类型的授权URL - 重新请求和重新认证。

重新请求

重新请求(或重新请求?)会再次要求用户为他们之前拒绝的权限。使用重新请求URL而不是直接通过正常登录链接重定向他们非常重要,因为

一旦有人拒绝了一个权限,登录对话框就不会再要求他们,除非你明确告诉对话框你正在重新请求一个被拒绝的权限。- Facebook 文档

您可以使用getReRequestUrl()方法生成重新请求URL。

$rerequest_link = $fb->getReRequestUrl(['email'], 'https://exmaple.com/facebook/login');
// Or, if you want to default to the callback URL set in the config
$rerequest_link = $fb->getReRequestUrl(['email']);

重新认证

重新认证通过要求用户再次输入他们的Facebook账户密码来强制他们确认他们的身份。这在在您的Web应用中更改或查看敏感数据之前添加另一个安全层非常有用。

您可以使用getReAuthenticationUrl()方法生成重新认证URL。

$re_authentication_link = $fb->getReAuthenticationUrl(['email'], 'https://exmaple.com/facebook/login');
// Or, if you want to default to the callback URL set in the config
$re_authentication_link = $fb->getReAuthenticationUrl(['email']);
// Or without permissions
$re_authentication_link = $fb->getReAuthenticationUrl();

保存访问令牌

在大多数情况下,除非你计划在用户不在浏览你的应用时(例如,例如凌晨3点的CRON作业)代表用户向Graph API发出请求,否则你不需要将访问令牌保存到数据库。

获取访问令牌后,您可以将其存储在会话中,以便用于后续请求。

Session::put('facebook_access_token', (string) $token);

然后,在调用Graph API的每个脚本中,您可以从会话中提取令牌并将其设置为默认值。

$token = Session::get('facebook_access_token');
$fb->setDefaultAccessToken($token);

在数据库中保存从Facebook获取的数据

将Graph API接收到的数据保存到数据库有时可能是一项繁琐的工作。由于Graph API以可预测的格式返回数据,因此SyncableGraphNodeTrait可以使将数据保存到数据库的过程变得容易。

任何实现SyncableGraphNodeTrait的Eloquent模型都将应用createOrUpdateGraphNode()方法。此方法确实使将直接从Facebook返回的数据创建或更新到本地数据库变得容易。

use Moomak\LaravelFacebookSdk\SyncableGraphNodeTrait;

class Event extends Eloquent {
    use SyncableGraphNodeTrait;
}

例如,如果你有一个名为Event的Eloquent模型,以下是你可以如何从Graph API获取特定事件并将其作为新条目插入数据库或使用新信息更新现有条目的方法。

$response = $fb->get('/some-event-id?fields=id,name');
$eventNode = $response->getGraphEvent();

// A method called createOrUpdateGraphNode() on the `Event` eloquent model
// will create the event if it does not exist or it will update the existing
// record based on the ID from Facebook.
$event = Event::createOrUpdateGraphNode($eventNode);

createOrUpdateGraphNode()将自动将返回的字段名映射到数据库中的列名。例如,如果你的events表中的列名与事件节点的字段名不匹配,你可以映射字段

字段映射

由于你的数据库中列的名称可能不匹配Graph节点的字段名称,你可以使用$graph_node_field_aliases静态变量映射你的User模型中的字段名称。

数组的是Graph节点上字段的名称。数组的是本地数据库中列的名称。

use Moomak\LaravelFacebookSdk\SyncableGraphNodeTrait;

class User extends Eloquent implements UserInterface
{
    use SyncableGraphNodeTrait;
    
    protected static $graph_node_field_aliases = [
        'id' => 'facebook_user_id',
        'name' => 'full_name',
        'graph_node_field_name' => 'database_column_name',
    ];
}

指定“可填充”字段

默认情况下,createOrUpdateGraphNode() 方法会尝试将节点的所有字段插入到数据库中。但有时图API会返回你不经意间请求的字段,这些字段在你的数据库中不存在。在这些情况下,我们可以使用 $graph_node_fillable_fields 属性来白名单特定的字段。

use Moomak\LaravelFacebookSdk\SyncableGraphNodeTrait;

class Event extends Eloquent
{
    use SyncableGraphNodeTrait;
    
    protected static $graph_node_fillable_fields = ['id', 'name', 'start_time'];
}

使用数据库列的名称。 例如,如果你已经将数据库中的 id 字段别名为 facebook_id,你将需要在你的 $graph_node_fillable_fields 数组中指定 facebook_id

嵌套字段映射

由于图API会将请求返回的一些字段作为其他节点/对象返回,你可以使用Laravel的 array_dot() 语法 来引用这些字段。

一个例子可能是向 /me/events 端点发起请求,遍历所有事件并将它们保存到你的 Event 模型中。将返回的 事件节点 中的 地点.location 字段 作为 地点节点 返回。响应数据可能如下所示

{
  "data": [
    {
      "id": "123", 
      "name": "Foo Event", 
      "place": {
        "location": {
          "city": "Dearborn", 
          "state": "MI", 
          "country": "United States", 
          . . .
        }, 
        "id": "827346"
      }
    },
    . . .
  ]
}

假设你有一个如下的事件表

Schema::create('events', function(Blueprint $table)
{
    $table->increments('id');
    $table->bigInteger('facebook_id')->nullable()->unsigned()->index();
    $table->string('name')->nullable();
    $table->string('city')->nullable();
    $table->string('state')->nullable();
    $table->string('country')->nullable();
});

以下是你在 Event 模型中将嵌套字段映射到数据库表中的方法

use Moomak\LaravelFacebookSdk\SyncableGraphNodeTrait;

class Event extends Eloquent
{
    use SyncableGraphNodeTrait;
    
    protected static $graph_node_field_aliases = [
        'id' => 'facebook_id',
        'place.location.city' => 'city',
        'place.location.state' => 'state',
        'place.location.country' => 'country',
    ];
}

日期格式

Facebook PHP SDK会将大多数日期格式转换为 DateTime 实例。当你想要将日期/时间值插入数据库(例如,事件节点start_time 字段)时,这可能会成为问题。

默认情况下,SyncableGraphNodeTrait 会将所有 DateTime 实例转换为以下 date() 格式

Y-m-d H:i:s

这应该是大多数情况下大多数关系型数据库的正确格式。但这个格式缺少时区,这可能会对你的应用程序很重要。此外,如果你以不同的格式存储日期/时间值,你将需要自定义将 DateTime 实例转换为的格式。为此,只需在你的模型中添加一个 $graph_node_date_time_to_string_format 属性并将其设置为任何 有效的日期格式

use Moomak\LaravelFacebookSdk\SyncableGraphNodeTrait;

class Event extends Eloquent
{
    use SyncableGraphNodeTrait;
    
    protected static $graph_node_date_time_to_string_format = 'c'; # ISO 8601 date
}

将用户登录到 Laravel

Laravel Facebook SDK使您可以使用Laravel内置的认证驱动程序轻松登录用户。

更新用户表

为了使Facebook认证与Laravel内置的认证一起工作,您需要将Facebook用户的ID存储在您的用户表中。

自然地,您将需要为用户想要保留的每一项信息创建一个列。

如果您需要在用户不浏览您的应用时代表用户发起请求(例如,凌晨3点的cron作业),则可以存储访问令牌在数据库中。但通常您不需要将访问令牌存储在数据库中。

您需要生成一个迁移来修改您的 users 表并添加任何新列。

注意: 请确保将 <name-of-users-table> 替换为您的用户表的名称。

$ php artisan make:migration add_facebook_columns_to_users_table --table="<name-of-users-table>"

现在更新迁移文件以包括您想要在用户上保存的新字段。至少您需要保存Facebook用户ID。

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddFacebookColumnsToUsersTable extends Migration
{
    public function up()
    {
        Schema::table('users', function(Blueprint $table)
        {
            // If the primary id in your you user table is different than the Facebook id
            // Make sure it's an unsigned() bigInteger()
            $table->bigInteger('facebook_user_id')->unsigned()->index();
            // Normally you won't need to store the access token in the database
            $table->string('access_token')->nullable();
        });
    }

    public function down()
    {
        Schema::table('users', function(Blueprint $table)
        {
            $table->dropColumn(
                'facebook_user_id',
                'access_token'
            );
        });
    }
}

别忘了运行迁移。

$ php artisan migrate

如果您计划使用Facebook用户ID作为主键,请确保您有一个名为 id 的列,该列是无符号的大整数并已索引。如果您在数据库中的不同字段中存储Facebook ID,请确保该字段存在,并确保您在模型中将其映射到您自定义的ID名称。

如果您正在使用Eloquent ORM并将访问令牌存储在数据库中,请确保在您的User模型中隐藏access_token字段,以防止可能的暴露。

别忘了将SyncableGraphNodeTrait添加到您的用户模型中,以便您可以将模型与Graph API返回的数据同步。

# User.php
use Moomak\LaravelFacebookSdk\SyncableGraphNodeTrait;

class User extends Eloquent implements UserInterface {
    use SyncableGraphNodeTrait;

    protected $hidden = ['access_token'];
}

在Laravel中登录用户

用户使用Facebook登录并从Graph API获取用户ID后,您可以通过将登录用户的User模型传递给Auth::login()方法来在Laravel中登录用户。

class FacebookController {
    public function getUserInfo(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
       try {
           $response = $fb->get('/me?fields=id,name,email');
       } catch (Facebook\Exceptions\FacebookSDKException $e) {
           dd($e->getMessage());
       }
       
       // Convert the response to a `Facebook/GraphNodes/GraphUser` collection
       $facebook_user = $response->getGraphUser();
       
       // Create the user if it does not exist or update the existing entry.
       // This will only work if you've added the SyncableGraphNodeTrait to your User model.
       $user = App\User::createOrUpdateGraphNode($facebook_user);
       
       // Log the user into Laravel
       Auth::login($user);
    }
}

处理多个应用

如果您想在同一脚本中使用多个Facebook应用或想在运行时调整设置,您可以创建一个新的LaravelFacebookSdk实例,并使用自定义设置。

Route::get('/example', function(Moomak\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
    // All the possible configuration options are available here
    $fb2 = $fb->newInstance([
      'app_id' => env('FACEBOOK_APP_ID2'),
      'app_secret' => env('FACEBOOK_APP_SECRET2'),
      'default_graph_version' => 'v2.10',
      // . . .
    ]);
});

错误处理

Facebook PHP SDK会抛出Facebook\Exceptions\FacebookSDKException异常。每当Graph返回错误响应时,SDK将抛出一个继承自Facebook\Exceptions\FacebookSDKExceptionFacebook\Exceptions\FacebookResponseException。如果抛出了Facebook\Exceptions\FacebookResponseException,您可以从getPrevious()方法中获取与错误相关的特定异常。

try {
    // Stuffs here
} catch (Facebook\Exceptions\FacebookResponseException $e) {
    $graphError = $e->getPrevious();
    echo 'Graph API Error: ' . $e->getMessage();
    echo ', Graph error code: ' . $graphError->getCode();
    exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo 'SDK Error: ' . $e->getMessage();
    exit;
}

LaravelFacebookSdk不会抛出任何自定义异常。

故障排除

在画布应用中遇到TokenMismatchException

如果您的应用是在应用画布或页面标签的上下文中提供的,那么当您尝试在Facebook上查看应用时,可能会看到一个TokenMismatchException错误。这是因为Facebook会通过发送带有signed_request参数的POST请求来渲染您的应用,而Laravel 5启用了针对每个非读取请求的CSRF保护,因此会触发错误。

尽管可以完全禁用此功能,但并不推荐这样做,因为CSRF保护是您网站上重要的安全功能之一,并且默认情况下应在每个路由上启用。

在Laravel 5.1 & 5.2中禁用CSRF

将异常添加到您的画布端点,并在您的app\Http\Middleware\VerifyCsrfToken.php文件中的$except数组中。

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'facebook/canvas',
        'facebook/page-tab',
        // ... insert all your canvas endpoints here
    ];
}

在Laravel 5.0中禁用CSRF

在Laravel 5.0中,禁用CSRF验证要复杂一些,但有一篇文章解释了如何在Laravel 5.0中禁用特定路由的CSRF保护

在您的app\Http\Middleware\VerifyCsrfToken.php文件中,添加一个excludedRoutes()方法。然后创建一个包含您画布应用或页面标签端点的路由数组。完整的文件如下所示

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Illuminate\Session\TokenMismatchException;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     *
     * @throws TokenMismatchException
     */
    public function handle($request, Closure $next)
    {
        if ($this->isReading($request) || $this->excludedRoutes($request) || $this->tokensMatch($request)) {
            return $this->addCookieToResponse($request, $next($request));
        }

        throw new TokenMismatchException;
    }

    /**
     * Ignore CSRF on these routes.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    private function excludedRoutes($request)
    {
        $routes = [
          'my-app/canvas',
          'my-app/page-tab',
          // ... insert all your canvas endpoints here
        ];

        foreach($routes as $route){
            if ($request->is($route)) {
                return true;
            }
        }

        return false;
    }
}

在保存用户时遇到QueryException

如果您正在使用MySQL,那么当您使用createOrUpdateGraphNode()将用户保存到数据库时,可能会遇到一个QueryException

QueryException in Connection.php line 754:
SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value

这是因为默认情况下启用了严格模式,这会将sql_mode设置为包括STRICT_TRANS_TABLES。由于我们不需要为通过Facebook登录的用户设置密码,因此此字段将是空的。解决此错误的一个方法是,在您的config/database.php文件中将MySQL驱动的strict设置为false

测试

测试是用phpunit编写的。您可以从项目目录的根目录运行以下命令来运行测试。

$ ./vendor/bin/phpunit

贡献

有关详细信息,请参阅CONTRIBUTING

致谢

此包由Scott Bowler维护。请参阅贡献者列表

许可证

MIT许可(MIT)。有关更多信息,请参阅许可文件