如何使用Python获取Facebook OAuth令牌?

0 投票
1 回答
533 浏览
提问于 2025-04-18 14:35

我想从Facebook获取访问令牌。我正在使用facepy这个库。下面是我写的一些代码片段。

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'face',
    'facepy',
)

 FACEBOOK_APPLICATION_INITIAL_PERMISSIONS = ['publish_actions', 'publish_stream', 'manage_pages']

这是我的urls.py文件

urlpatterns = patterns('',
    url(r'^$', 'face.views.authorize_application', name='authorize_application'),
    url(r'^rag_the_app/$', 'face.views.get_token', name='get_token'),
    url(r'^oauth/access_token/$', 'face.views.manage_pages', name='manage_pages'),
    )

这是我的views.py文件

import urllib
from facepy import GraphAPI
from facepy.utils import get_extended_access_token


def authorize_application(request):

    query = {
        'client_id': FACEBOOK_APPLICATION_ID,
        'redirect_uri': 'http://%s:8000/%s' % (FACEBOOK_APPLICATION_DOMAIN, FACEBOOK_APPLICATION_NAMESPACE),
        'scope': FACEBOOK_APPLICATION_INITIAL_PERMISSIONS

    }
    return render(
        request = request,
        template_name = 'authorization.html',
        dictionary = {
            'url': 'https://www.facebook.com/dialog/oauth?%s' % urllib.urlencode(query)
        },
        status = 401
    )



def get_token(request):

    code = request.GET.get('code', '')

    query = {
        'client_id': FACEBOOK_APPLICATION_ID,
        'redirect_uri': 'http://%s:8000/%s' % (FACEBOOK_APPLICATION_DOMAIN, FACEBOOK_APPLICATION_NAMESPACE),
        'client_secret': FACEBOOK_APPLICATION_SECRET_KEY,
        'code': code
        }

    return render(
        request = request,
        template_name = 'authorization.html',
        dictionary = {
            'url': 'https://graph.facebook.com/oauth/access_token?%s' % urllib.urlencode(query)
            }, 
        )
    request.session['access_token'] = response['access_token']


def manage_pages(request):

    oauth_access_token = get_extended_access_token(access_token, FACEBOOK_APPLICATION_ID, FACEBOOK_APPLICATION_SECRET_KEY)
    graph = GrahAPI(oauth_access_token)
    page_id = '263880043816054'
    og_path = "%d/feed" %page_id
    graph.post( path = og_path, message = "hello page" )

Facebook应用的基本设置

canvas url: http://localhost:8000 
secure canvas url: https://localhost:8000
app_domain: localhost:8000

Facebook应用的高级设置

有效的OAuth重定向URI

http://localhost:8000/oauth/access_token/

当我运行我的服务器时,它出现了一个错误

Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.

我该如何获取访问令牌?我哪里做错了?

1 个回答

0

你需要把你的开发服务器暴露到互联网,让Facebook能够找到你,以便进行回调。你不能使用本地地址localhost。

以下所有内容:

  • 画布网址
  • 安全画布网址
  • 有效的OAuth重定向网址

...都应该是你的服务器的域名或网址,能够被互联网访问到。

撰写回答