博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
graph api_与Facebook Graph API集成
阅读量:2515 次
发布时间:2019-05-11

本文共 12265 字,大约阅读时间需要 40 分钟。

graph api

Integrating with Facebook from PHP is easy with the help of Facebook’s PHP SDK and some HTTP libraries like Zend_Http_Client or PEAR HTTP_Request2. In this article I’ll show you how to get started using the Facebook PHP SDK. You’ll learn about the Facebook Graph API and create a Facebook application capable of updating your status message and uploading photos.

借助FacebookPHP SDK和一些HTTP库(例如Zend_Http_Client或PEAR HTTP_Request2),可以轻松地从PHP与Facebook集成。 在本文中,我将向您展示如何开始使用Facebook PHP SDK。 您将了解Facebook Graph API,并创建一个能够更新状态消息和上传照片的Facebook应用程序。

If you don’t have it already, you can clone or download the . You’ll also need a verified Facebook account.

如果还没有,可以克隆或下载 。 您还需要一个经过验证的Facebook帐户。

在Facebook上注册您的应用 (Registering your App on Facebook)

You first need to register your application on Facebook. Go to and click the Create New App button at the top of the page.

您首先需要在Facebook上注册您的应用程序。 转到 ,然后单击页面顶部的“ 创建新应用”按钮。

The dialog that opens asks you for the name and a namespace for your application. App Display Name is the name for your application that will be shown to the users. App Namespace is the namespace your application will use for Open Graph and Canvas Page.

打开的对话框将询问您应用程序的名称和名称空间。 应用程序显示名称是将显示给用户的应用程序名称。 应用程序命名空间是您的应用程序将用于“打开图形”和“画布页面”的命名空间。

alt

After you register the application, you’ll be taken to the Basic Settings screen on which you need to specify how your app will integrate with Facebook:

注册该应用程序后,将转到“基本设置”屏幕,在该屏幕上需要指定您的应用程序如何与Facebook集成:

  • Website – The website option is used for adding social functionality to your website.

    网站 –网​​站选项用于向您的网站添加社交功能。

  • App on Facebook – This Facebook app option embeds your application within a Facebook Canvas page. The code is hosted on your servers, but executes within the context of a Facebook page, similar to an IFrame.

    Facebook上的应用程序–此Facebook应用程序选项将您的应用程序嵌入Facebook Canvas页面中。 该代码托管在您的服务器上,但在Facebook页面的上下文中执行,类似于IFrame。

  • Mobile Web – The mobile web option is similar to the Website integration option, although it’s intended for mobile sites.

    移动Web –移动Web选项类似于“网站集成”选项,尽管它适用于移动网站。

  • Native iOS/Android App – The native options allow you to integrate Facebook data in your iOS and Android applications.

    本机iOS / Android应用程序 –本机选项允许您将Facebook数据集成到iOS和Android应用程序中。

  • Page Tab – The tab option exposes your application as a Facebook page tab.

    页面选项卡 –选项卡选项将您的应用程序显示为Facebook页面选项卡。

For the purposes of this article I’ll use the website integration option. My application will be a stand-alone website, and after authorization Facebook will redirect the user to a specified URL. Select the check mark next to the option and enter the URL for your application’s entry page. Then be sure to click the Save Changes button at the bottom of the page.

就本文而言,我将使用网站集成选项。 我的应用程序将是一个独立的网站,经过授权,Facebook会将用户重定向到指定的URL。 选择选项旁边的复选标记,然后输入应用程序进入页面的URL。 然后确保单击页面底部的“ 保存更改”按钮。

You should also make a note of the App ID and App Secret values at the top of the page since you will need these values to connect your application to Facebook.

您还应该在页面顶部记录“ 应用程序ID”和“ 应用程序秘密”值,因为您需要这些值才能将应用程序连接到Facebook。

alt

使用SDK (Using the SDK)

Functionality to connect and interact with Facebook is exposed through the Facebook object defined by the PHP SDK. The constructor accepts an array of parameters which contain information about your application, such as the App ID and App Secret that appear on your application’s Basic Settings page.

通过PHP SDK定义的Facebook对象公开了与Facebook连接和交互的功能。 构造函数接受一个参数数组,其中包含有关您的应用程序的信息,例如出现在应用程序的“基本设置”页面上的“ App ID”和“ App Secret ”。

FACEBOOK_APP_ID, "secret" => FACEBOOK_APP_SECRET);$fb = new Facebook($config);

授权书 (Authorization)

The getUser() method is used to retrieve the user ID of a Facebook user. The information may or may not be available, depending on whether the user is logged in or not. If the method returns 0 then you know the user has not logged in.

getUser()方法用于检索Facebook用户的用户ID。 根据用户是否登录,该信息可能可用或可能不可用。 如果该方法返回0,则说明用户尚未登录。

getUser();

The login link which serves the starting point for the OAuth authentication process with Facebook is obtained using the getLoginUrl() method. getLoginUrl() accepts an array of a parameters in which I’ve supplied redirect_uri and scope.

使用getLoginUrl()方法可获得登录链接,该链接是使用Facebook进行OAuth身份验证过程的起点。 getLoginUrl()接受一个参数数组,在其中提供了redirect_uriscope

REDIRECT_URI, "scope" => "email,read_stream,publish_stream,user_photos,user_videos"); echo 'Login';

The redirect_url should be the same address you provided for Site URL when registering the application. The scope is a comma-separated list of requested permissions the application requires. Applications are allowed to access public profile information and other defaults as permitted by Facebook when the user is logged in, but if you want access to additional functionality (such as posting status messages) you must be authorized by the user to do so. The Facebook developers documentation has a . Here I’ve requested permission to to access the user’s email address, read and publishing status updates, post photos, and post videos.

redirect_url应该与您注册应用程序时为站点URL提供的地址相同。 范围是应用程序所需的请求权限的逗号分隔列表。 允许应用程序访问用户登录时的公共资料信息和Facebook允许的其他默认设置,但是如果您想访问其他功能(例如发布状态消息),则必须得到用户的授权。 Facebook开发人员文档具有的 。 在这里,我已请求访问用户的电子邮件地址,阅读和发布状态更新,发布照片以及发布视频的权限。

Regardless if the user accepts the request and logs in to Facebook, or rejects the request, he will be redirected back to the redirect_uri and several values will be available as URL parameters. A rejection will include error, error_reason, and error_description parameters:

无论用户接受请求并登录Facebook还是拒绝请求,他都会被重定向回redirect_uri,并且多个值将用作URL参数。 拒绝将包括errorerror_reasonerror_description参数:

http://example.com/facebook/myapp.php?error=access_denied&error_reason=user_denied&error_description=The+user+denied+your+request.

A successful authentication/authorization will append a code parameter, like so:

成功的身份验证/授权将附加一个code参数,如下所示:

http://example.com/facebook/myapp.php?code=TOKEN_VALUE

The code is then used to request an Access Token:

然后,该代码用于请求访问令牌:

https://graph.facebook.com/oauth/access_token?client_id=FACEBOOK_APP_ID&redirect_uri=FACEBOOK_REDIRECT_URI&client_secret=FACEBOOK_APP_SECRET&code=TOKEN_VALUE

As you’re using the SDK which handles all of this for you, I won’t go more into how OAuth works. If you’re interested in learning more read Dustin Runnell’s article and the SDK’s . (Facebook uses OAuth v2 and Dustin’s article covers v1, but it will still give you a good idea of the role requests and credentials play in the process).

当您使用可为您处理所有这些问题的SDK时,我将不进一步介绍OAuth的工作方式。 如果您想了解更多信息,请阅读Dustin Runnell的《 文和SDK的 。 (Facebook使用OAuth v2,Dustin的文章介绍了v1,但仍然可以使您很好地了解请求和凭据在此过程中的作用)。

Graph API (The Graph API)

Once the user grants permission, you can read the user’s feed of status messages with a GET request:

用户授予权限后,您就可以通过GET请求阅读用户的状态消息供稿:

https://graph.facebook.com/me/feed?access_token=ACESS_TOKEN

Alternatively, you can use the api() method which wraps a call to Facebook Graph API methods:

另外,您可以使用api()方法来包装对Facebook Graph API方法的调用:

api("/me/feed");

The api() method in this case can accept three arguments: the Graph API path for the request, the HTTP method for the request (defaults to GET), an an array of parameters specific to the Graph API method.

在这种情况下, api()方法可以接受三个参数:请求的Graph API路径,请求的HTTP方法(默认为GET ),特定于Graph API方法的参数数组。

The Graph API provides an interface to access the members and relationships in Facebook’s social graph. Each member has a unique ID and can be accessed in a REST-like manner through resources starting with “https://graph.facebook.com”. For example, sending a GET request with your browser for:

Graph API提供了一个接口来访问Facebook社交图中的成员和关系。 每个成员都有一个唯一的ID,可以通过以“ https://graph.facebook.com”开头的资源以类似REST的方式进行访问。 例如,通过浏览器发送GET请求以:

https://graph.facebook.com/harikt

will return a JSON object with basic public information about me and my profile.

将返回一个JSON对象,其中包含有关我和我的个人资料的基本公共信息。

{   "id": "596223095",   "name": "Hari Kt",   "first_name": "Hari",   "last_name": "Kt",   "link": "http://www.facebook.com/harikt",   "username": "harikt",   "gender": "male",   "locale": "en_US"}

Some requests require an Access Token. Requesting a feed of message updates is a privileged action, and so sending a GET request for:

一些请求需要访问令牌。 请求提要消息更新是一项特权操作,因此发送GET请求用于:

https://graph.facebook.com/harikt/feed

will return a JSON object populated with information about an OAuthException error.

将返回一个JSON对象,其中填充了有关OAuthException错误的信息。

{   "error": {      "message": "An access token is required to request this resource.",      "type": "OAuthException"   }}

The ID me is a convenient shorthand which refers to the current user.

ID me是一个方便的速记形式,它指向当前用户。

To add an update to the user’s feed using the api() method, you would make a POST request to /me/feed and supply a message value.

要使用api()方法向用户的供稿添加更新,您需要向/me/feed发出POST请求并提供消息值。

"Hello World!");$status = $fb->api("/me/feed", "POST", $data);

To upload a new photo you would make a POST request to /me/photos (or ALBUM_ID/photos to upload to a specific album) and supply an array with name and image arguments.

要上传新照片,您需要对/me/photos (或ALBUM_ID/photos进行POST请求,以上ALBUM_ID/photos特定相册中,并提供一个包含名称图像参数的数组。

setFileUploadSupport(true); $data = array( "name" => "a vacation photo", "image" => "@/home/hari/vacation/img42.jpg");$status = $fb->api("/me/photos", "POST", $data);

The SDK uses PHP’s cURL extension to post data, and calling setFileUploadSupport() with true will provide the data values to CURLOPT_POSTFIELDS as an array which in turn causes cURL to encode the data as “multipart/form-data”. Also cURL-related is the use of @ before the full path of the image to be posted. See the description for CURLOPT_POSTFIELDS in PHP’s for more information.

SDK使用PHP的cURL扩展名来发布数据,并调用true setFileUploadSupport()将数据值作为数组提供给CURLOPT_POSTFIELDS ,这反过来会使cURL将数据编码为“多部分/表单数据”。 与cURL相关的还有在要发布的图像的完整路径之前使用@ 。 有关更多信息,请参见PHP的对CURLOPT_POSTFIELDS的描述。

To learn more about Facebook’s Graph API I recommend you to read the and experiment with the which is quite a handy utility.

要了解有关Facebook的Graph API的更多信息,建议您阅读并尝试使用 ,它是一个非常实用的实用程序。

您的首次申请 (Your First Application)

Let’s bring together everything you’ve learned now and write a very basic example of a Facebook application. It will prompt the user to log in and authorize the application, and then enable him to update his status message and upload a photo.

让我们将您现在学到的所有内容汇总在一起,并编写一个非常基本的Facebook应用程序示例。 它将提示用户登录并授权应用程序,然后使他能够更新其状态消息并上传照片。

FACEBOOK_APP_ID, "secret" => FACEBOOK_APP_SECRET);$fb = new Facebook($config);$user = $fb->getUser();?> Hello Facebook
"read_stream,publish_stream,user_photos", "redirect_uri" => REDIRECT_URI); echo 'Login'; }else { ?>
" method="post" enctype="multipart/form-data">
$_POST["message"], "image" => "@" . realpath($_FILES["image"]["tmp_name"])); $fb->setFileUploadSupport(true); $status = $fb->api("/me/photos", "POST", $data); } } else { // update status message $data = array("message" => $_POST["message"]); $status = $fb->api("/me/feed", "POST", $data); } } if (isset($status)) { echo "
" . print_r($status, true) . "
"; } }?>

The code presents a link to log in or out as appropriate depending on the return value of getUser(). Then, a simple HTML form is displayed which permits the user to enter a status message and possibly an image file. When the user submits the form, the code verifies the uploaded image if one is provided and posts it to Facebook, or performs just a status message update.

该代码根据getUser()的返回值提供了一个用于登录或注销的链接。 然后,显示一个简单HTML表单,该表单允许用户输入状态消息以及可能的图像文件。 当用户提交表单时,代码将验证上载的图像(如果提供了该图像)并将其发布到Facebook,或者仅执行状态消息更新。

摘要 (Summary)

The code here is for demonstration purposes, and I’ve omitted a lot of filtering and security-related checks you’d want to perform when writing a real-world application. It does however highlight the main points presented in this article. The Facebook PHP SDK makes integrating with Facebook easy. It abstracts working with OAuth authentication and the Facebook Graph API.

此处的代码仅用于演示目的,而我省略了编写真实应用程序时要执行的许多筛选和与安全性相关的检查。 但是,它确实突出了本文介绍的要点。 Facebook PHP SDK使与Facebook的集成变得容易。 它抽象了使用OAuth身份验证和Facebook Graph API的工作。

Image via /

图片 /

翻译自:

graph api

转载地址:http://qqrgb.baihongyu.com/

你可能感兴趣的文章
新浪微博辅助工具说明一
查看>>
(Easy) N-th Tribonacci Number LeetCode
查看>>
萤火虫小巷1
查看>>
鼠标移上图标字体,让其旋转
查看>>
SD卡bus speed-Default speed/Default high speed/UHS-1/UHS-2/UHS-3
查看>>
Ajax实战
查看>>
C++抽象类实践
查看>>
android SDK SDK Manager.exe 无法打开,一闪而过最终解决办法
查看>>
uWSGI、uwsgi、WSGI、之间的关系,为什么要用nginx加uWSGI部署。
查看>>
前端技术博客网站收藏
查看>>
洛谷 P1443 马的遍历题解
查看>>
super关键字
查看>>
Echart--百度地图(散点图)
查看>>
好用的python库(转)
查看>>
Java集合遍历时删除
查看>>
「BZOJ2153」设计铁路 - 斜率DP
查看>>
(动态规划、递归) leetcode 87. Scramble String
查看>>
[补档]暑假集训D8总结
查看>>
Linux如何查看JDK的安装路径
查看>>
git命令-切换分支
查看>>