linkthrow / lumen-facebook-sdk
完全单元测试的 Lumen Facebook SDK
Requires
- php: >=5.5.0
- facebook/php-sdk-v4: ~5.0
- illuminate/auth: ~5.1
- illuminate/config: ~5.1
- illuminate/database: ~5.1
- illuminate/routing: ~5.1
- illuminate/session: ~5.1
- illuminate/support: ~5.1
- irazasyed/larasupport: ~1.0
Requires (Dev)
- mockery/mockery: ~0.9
- phpunit/phpunit: ~4.0
- squizlabs/php_codesniffer: ~2.0
README
一个完全单元测试的包,用于轻松地将 Facebook SDK v5 集成到 Lumen 中。
安装
将 Lumen Facebook SDK 包添加到您的 composer.json 文件中。
{
"require": {
"linkthrow/lumen-facebook-sdk": "~4.0"
}
}
服务提供者
在您的 bootstrap/app.php 中,添加支持提供者和 LumenFacebookSdkServiceProvider
$app->register(Irazasyed\Larasupport\Providers\ArtisanServiceProvider::class);
$app->register(LinkThrow\LumenFacebookSdk\LumenFacebookSdkServiceProvider::class);
门面(可选)
如果您想使用门面,请在 bootstrap/app.php 中的别名数组中添加它
首先通过以下方式启用别名:
$app->withFacades();
然后添加:
class_alias(LinkThrow\LumenFacebookSdk\FacebookFacade::class, 'Facebook');
IoC 容器
IoC 容器将自动为您解析 LumenFacebookSdk 依赖。您可以通过多种方式从 IoC 容器中获取 LumenFacebookSdk 实例。
// Directly from App::make(); $fb = App::make('LinkThrow\LumenFacebookSdk\LumenFacebookSdk'); //In order to do this you must first register the App provider, add the following to bootstrap/app.php $app->register(App\Providers\AppServiceProvider::class); class_alias(Illuminate\Support\Facades\App::class, 'App'); // From a constructor class FooClass { public function __construct(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $fb) { // . . . } } // From a method class BarClass { public function barMethod(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $fb) { // . . . } } // Or even a closure Route::get('/facebook/login', function(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $fb) { // . . . });
配置文件
在 Facebook 中创建应用后,您需要提供应用 ID 和密钥。首先发布配置文件。
$ php artisan vendor:publish --provider="LinkThrow\LumenFacebookSdk\LumenFacebookSdkServiceProvider" --tag="config"
文件在哪里?使用我们安装的 Larasupport 包,Lumen 将配置文件发布到
config/lumen-facebook-sdk.php。
必需的配置值
您需要在配置文件中更新 app_id 和 app_secret 值,使用 您的应用 ID 和密钥。
默认情况下,配置文件将查找环境变量以获取您的应用 ID 和密钥。建议您使用环境变量来存储此信息,以保护您的应用密钥免受攻击者侵害。请确保更新您的 /.env 文件,包括您的应用 ID & 密钥。
FACEBOOK_APP_ID=1234567890
FACEBOOK_APP_SECRET=SomeFooAppSecret
同步 Graph 节点与 Laravel 模型
如果您在用户的表中有一个 facebook_user_id 列,您可以将 SyncableGraphNodeTrait 添加到您的 User 模型中,以便从 Graph API 自动同步用户节点与您的模型。
class User extends Eloquent implements UserInterface { use LinkThrow\LumenFacebookSdk\SyncableGraphNodeTrait; protected static $graph_node_field_aliases = [ 'id' => 'facebook_user_id', ]; }
有关从 Facebook 保存数据到数据库的更多信息。
重定向示例中的用户登录
以下是使用重定向方法登录用户到您的应用的完整示例。
此示例还演示了如何将短期访问令牌与长期访问令牌交换,并在条目不存在的情况下将用户保存到您的 users 表中。
最后,它将使用 Laravel 内置的用户身份验证登录用户。
// Generate a login URL Route::get('/facebook/login', function(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $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(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $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登录”时,实际上是指“代表用户获取用于调用Graph API的用户访问令牌”。这是通过Facebook通过OAuth 2.0来完成的。使用Facebook PHP SDK中称为“helpers”的方式,有多种方法可以使用Facebook登录用户。
支持的四种登录方法包括
- 通过重定向登录(OAuth 2.0)
- 通过JavaScript登录(带有JS SDK cookie)
- 通过App Canvas登录(带有签名请求)
- 通过页面标签登录(带有签名请求)
通过重定向登录
将用户登录到您的应用的一种最常见方式是使用重定向URL。
其基本思想是生成一个用户点击的唯一URL。一旦用户点击链接,他们将被重定向到Facebook,并要求授予您的应用请求的任何权限。一旦用户做出响应,Facebook将用户重定向回您指定的回调URL,无论是成功响应还是错误响应。
可以通过SDK的getRedirectLoginHelper()方法获取重定向助手。
生成登录URL
您可以获取一个登录URL,就像您使用Facebook PHP SDK v5一样。
Route::get('/facebook/login', function(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $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(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $fb) { try { $token = $fb ->getRedirectLoginHelper() ->getAccessToken(); } catch (Facebook\Exceptions\FacebookSDKException $e) { // Failed to obtain access token dd($e->getMessage()); } });
LumenFacebookSdk中有一个用于getRedirectLoginHelper()->getAccessToken()的包装方法,名为getAccessTokenFromRedirect(),它将回调URL默认为laravel-facebook-sdk.default_redirect_uri配置值。
Route::get('/facebook/callback', function(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $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.5' });
使用FB.login()登录通过JavaScript SDK登录用户后,您可以从存储在JavaScript SDK设置的cookie中的签名请求中获取用户访问令牌。
Route::get('/facebook/javascript', function(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $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:默认情况下,当您尝试在Facebook中查看canvas应用时,它将抛出
TokenMismatchException。请参阅如何修复此问题。
如果您的应用位于Facebook应用canvas的上下文中,您可以从第一次页面加载时通过POST发送到您的应用的签名请求中获取访问令牌。
注意:画布助手仅从Facebook接收的已签名请求数据中获取现有的访问令牌。如果访问您应用的用户尚未授权您的应用或其访问令牌已过期,则
getAccessToken()方法将返回null。在这种情况下,您需要使用重定向或JavaScript让用户登录。
使用SDK的画布助手从已签名请求数据中获取访问令牌。
Route::get('/facebook/canvas', function(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $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:默认情况下,当您在Facebook中尝试查看页面标签时,它将抛出
TokenMismatchException。请查看如何修复此问题。
如果您的应用位于Facebook页面标签的上下文中,即与应用画布相同,则“从应用画布登录”方法也可以用来获取访问令牌。但页面标签在已签名的请求数据中还有其他数据。
SDK提供了一个页面标签助手,用于在页面标签的上下文中从已签名请求数据中获取访问令牌。
Route::get('/facebook/page-tab', function(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $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 LinkThrow\LumenFacebookSdk\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 表中的列名与 Event 节点的字段名不匹配,您可以 映射字段。
字段映射
由于您数据库中列的名称可能不匹配图节点字段的名称,您可以使用 $graph_node_field_aliases 静态变量在 User 模型中映射字段名称。
数组的 keys 是图节点上字段的名称。数组的 values 是本地数据库中列的名称。
use LinkThrow\LumenFacebookSdk\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 LinkThrow\LumenFacebookSdk\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 模型。将返回的 Event 节点,该节点将 place.location 字段 返回为 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 LinkThrow\LumenFacebookSdk\SyncableGraphNodeTrait; class Event extends Eloquent { use SyncableGraphNodeTrait; protected static $facebook_field_aliases = [ 'id' => 'facebook_id', 'place.location.city' => 'city', 'place.location.state' => 'state', 'place.location.country' => 'country', ]; }
日期格式
Facebook PHP SDK 将将大多数日期格式转换为 DateTime 实例。当您想将日期/时间值插入到数据库中(例如,Event 节点 的 start_time 字段)时,这可能会出现问题。
默认情况下,SyncableGraphNodeTrait 将所有 DateTime 实例转换为以下 date() 格式
Y-m-d H:i:s
这应该是大多数情况下大多数关系数据库的正确格式。但是,此格式缺少时区,这对于您的应用程序可能很重要。此外,如果您以不同的格式存储日期/时间值,则希望自定义将 DateTime 实例转换为的格式。为此,只需将 $graph_node_date_time_to_string_format 属性添加到您的模型中并将其设置为任何 有效的日期格式。
use LinkThrow\LumenFacebookSdk\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 LinkThrow\LumenFacebookSdk\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(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $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应用程序或想在运行时调整设置,您可以创建一个新的 LumenFacebookSdk 实例并使用自定义设置。
Route::get('/example', function(LinkThrow\LumenFacebookSdk\LumenFacebookSdk $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.5', // . . . ]); });
错误处理
Facebook PHP SDK抛出 Facebook\Exceptions\FacebookSDKException 异常。每当Graph API返回错误响应时,SDK将抛出扩展自 Facebook\Exceptions\FacebookSDKException 的 Facebook\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; }
LumenFacebookSdk不抛出任何自定义异常。
使用画布应用获取TokenMismatchException
如果您的应用程序在应用程序画布或页面标签的上下文中提供服务,当您尝试在Facebook上查看应用程序时,您可能会看到 TokenMismatchException 错误。这是因为Facebook将通过发送包含 signed_request 参数的POST请求来渲染您的应用程序,而Laravel 5对每个非读取请求都启用了CSRF保护,从而触发了错误。
虽然可以完全禁用此功能,但这绝对不推荐,因为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 = [ 'my-app/canvas', 'my-app/page-tab', // ... insert all your canvas endpoints here ]; }
测试
测试是用 phpunit 编写的。您可以从项目目录的根目录运行以下命令来运行测试。
$ ./vendor/bin/phpunit
贡献
有关详细信息,请参阅 CONTRIBUTING。
致谢
此软件包由 Sammy Kaye Powers 维护。请参阅贡献者完整列表。
许可证
此软件包受MIT许可(MIT)保护。有关更多信息,请参阅 许可文件。