程序matically获取Facebook Graph API的访问令牌

41 投票
8 回答
76402 浏览
提问于 2025-04-16 00:05

我正在尝试写一个bash或者python脚本,来玩一下Facebook的图形API。使用这个API看起来很简单,但我在我的bash脚本中设置curl来调用授权和访问令牌时遇到了麻烦。有没有人能提供一个有效的示例?

8 个回答

21

很简单!只需要使用 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) 
33

这就是你需要的,简单到不能再简单了。完全不需要任何第三方的开发工具包。

确保你的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']
39

更新于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

在获取令牌时的错误检查可能会更好,但你大概明白该怎么做了。

撰写回答