以编程方式获取使用Facebook Graph API的访问令牌

jus*_*nhj 39 python bash facebook

我试图将一个bash或python脚本放在一起玩facebook图形API.使用API​​看起来很简单,但我在bash脚本中设置curl时遇到问题,无法调用authorize和access_token.有没有人有一个有效的例子?

mar*_*ead 37

更新2018-08-23

由于这仍然得到一些观点和赞成,我只想提一下,到目前为止似乎存在一个维护的第三方SDK:https://github.com/mobolic/facebook-sdk


迟到总比没有好,也许其他寻找它的人会找到它.我在MacBook上使用Python 2.6.

这需要你拥有

您可以在Facebook开发人员文档中阅读有关身份验证的内容.有关详细信息,请参阅https://developers.facebook.com/docs/authentication/.

这篇博客文章也可能对此有所帮助:http://blog.theunical.com/facebook-integration/5-steps-to-publish-on-a-facebook-wall-using-php/

开始:

#!/usr/bin/python
# coding: utf-8

import facebook
import urllib
import urlparse
import subprocess
import warnings

# Hide deprecation warnings. The facebook module isn't that up-to-date (facebook.GraphAPIError).
warnings.filterwarnings('ignore', category=DeprecationWarning)


# Parameters of your app and the id of the profile you want to mess with.
FACEBOOK_APP_ID     = 'XXXXXXXXXXXXXXX'
FACEBOOK_APP_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
FACEBOOK_PROFILE_ID = 'XXXXXX'


# Trying to get an access token. Very awkward.
oauth_args = dict(client_id     = FACEBOOK_APP_ID,
                  client_secret = FACEBOOK_APP_SECRET,
                  grant_type    = 'client_credentials')
oauth_curl_cmd = ['curl',
                  'https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(oauth_args)]
oauth_response = subprocess.Popen(oauth_curl_cmd,
                                  stdout = subprocess.PIPE,
                                  stderr = subprocess.PIPE).communicate()[0]

try:
    oauth_access_token = urlparse.parse_qs(str(oauth_response))['access_token'][0]
except KeyError:
    print('Unable to grab an access token!')
    exit()

facebook_graph = facebook.GraphAPI(oauth_access_token)


# Try to post something on the wall.
try:
    fb_response = facebook_graph.put_wall_post('Hello from Python', \
                                               profile_id = FACEBOOK_PROFILE_ID)
    print fb_response
except facebook.GraphAPIError as e:
    print 'Something went wrong:', e.type, e.message
Run Code Online (Sandbox Code Playgroud)

获取令牌时检查错误可能会更好,但您可以了解要执行的操作.

  • 通过这个例子,它很可能这个SDK几乎没用 - 我建议使用"请求"Python库来代替http通信:https://pypi.python.org/pypi/requests (6认同)
  • 官方一个!你可以从GitHub获得它:https://github.com/facebook/python-sdk我更新了答案以包含链接. (2认同)
  • 谢谢,但"不推荐使用此SDK". (2认同)

Waq*_*qas 29

在这里,尽可能简单.不需要任何第三方SDK等

确保安装了Python'requests'模块

import requests

def get_fb_token(app_id, app_secret):
    url = 'https://graph.facebook.com/oauth/access_token'       
    payload = {
        'grant_type': 'client_credentials',
        'client_id': app_id,
        'client_secret': app_secret
    }
    response = requests.post(url, params=payload)
    return response.json()['access_token']
Run Code Online (Sandbox Code Playgroud)

  • 在编写时,此端点返回JSON,因此将`result = file.text.split("=")[1]`更改为`result = file.json()['access_token']` (2认同)

s29*_*s29 18

简单!只需使用facebook-sdk.

import facebook

app_id = 'YOUR_APP_ID'
app_secret = 'YOUR_APP_SECRET'

graph = facebook.GraphAPI()

# exactly what you're after ;-)
access_token = graph.get_app_access_token(app_id, app_secret) 
Run Code Online (Sandbox Code Playgroud)


Ian*_*ens 9

您首先需要设置一个应用程序.然后,以下将根据您的应用程序ID和密码吐出访问令牌:

> curl -F type=client_cred -F client_id=[...] -F client_secret=[...] https://graph.facebook.com/oauth/access_token
Run Code Online (Sandbox Code Playgroud)


daa*_*aku 6

由于Web浏览器需要涉及实际授权,因此没有"独立脚本"可以完成所有操作.如果你只是在玩API,或者正在编写一个自己自动化的脚本,并希望access_token自己不会过期,你可以在这里找到一个:http://fbrell.com/auth/offline-access-代币


小智 6

有一种方法可以做到这一点,我发现它,但这是很多工作,需要你100%欺骗浏览器(你可能会违反他们的服务条款)

对不起,我不能提供所有的细节,但它的要点:

  1. 假设您有一个Facebook帐户的用户名/密码,请转到oauth/authenticate ...页面的curl.提取"Set-Cookie"标题中返回的所有Cookie,然后按照任何"Location"标题(沿途编译Cookie).
  2. 抓取登录表单,保留所有字段,并提交它(设置引用和内容类型标题,并插入您的电子邮件/通行证)相同的cookie集合(1)要求
  3. 与(2)相同,但现在您需要POST提交(2)提交后获得的批准表单,将REferer标题设置为获取表单的thr URL.
  4. 按照重定向,直到它将您发送回您的网站,并从该网址获取"代码"参数
  5. 在oauth端点交换access_token的代码

主要的问题是cookie管理和重定向.基本上,你必须100%模仿浏览器.我认为这是hackery,但有一种方法,它真的很难!