axdsan/laravel-facebook-sdk

针对 Laravel 8.x 的完全单元测试的 Facebook SDK v5 集成

5.1.1 2021-07-06 23:01 UTC

README

Build Status Latest Stable Version Total Downloads License

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

我是否应该只使用 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 axdsan/laravel-facebook-sdk

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

服务提供者

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

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

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

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

外观(可选)

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

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

但还有 更好的方法 来使用此包,那就是 不使用外观

IoC 容器

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

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

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

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

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

配置文件

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

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

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

$ php artisan vendor:publish --provider="Axdsan\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

用户登录重定向示例

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

-此示例还演示了如何使用短期访问令牌与长期访问令牌进行交换,并在用户表中不存在条目时保存用户。-

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

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

// Generate a login URL
Route::get('/facebook/login', function(Axdsan\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(Axdsan\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登录”时,我们的真正意思是“获取一个用户访问令牌以代表用户调用Graph API”。这是通过Facebook通过OAuth 2.0完成的。Facebook PHP SDK称为“helpers”的许多方法可以用来通过Facebook登录用户。

支持的四种登录方法如下

  1. 从重定向登录(OAuth 2.0)
  2. 从JavaScript登录(带有JS SDK cookie)
  3. 从App Canvas登录(带有签名请求)
  4. 从Page Tab登录(带有签名请求)

从重定向登录

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

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

可以使用SDK的getRedirectLoginHelper()方法获取重定向辅助工具。

生成登录URL

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

Route::get('/facebook/login', function(Axdsan\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(Axdsan\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(Axdsan\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,因此您必须在init() 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(Axdsan\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
    }
});

从应用画布登录

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

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

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

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

Route::match(['get', 'post'], '/facebook/canvas', function(Axdsan\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(Axdsan\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 Axdsan\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 Axdsan\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 Axdsan\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 模型中。事件节点 将返回 地点的位置字段 作为 地点节点。响应数据可能看起来像这样

{
  "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 Axdsan\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 Axdsan\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 Axdsan\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(Axdsan\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(Axdsan\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)。请参阅 许可文件 获取更多信息。