如何在GAE Python中使用Facebook Graph API获取用户邮箱?

6 投票
3 回答
4061 浏览
提问于 2025-04-16 05:59

我在谷歌应用引擎上使用Facebook的图形API。我能获取到用户的基本信息。但是当我尝试获取需要权限的用户信息,比如电子邮件时,结果总是显示为None(没有值)。我已经按照开发者博客上的整个教程操作过了。

这是我的代码:

class User(db.Model):
    id = db.StringProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    name = db.StringProperty(required=True)
    email = db.StringProperty(required=True)
    profile_url = db.StringProperty(required=True)
    access_token = db.StringProperty(required=True)


class BaseHandler(webapp.RequestHandler):
    """Provides access to the active Facebook user in self.current_user

    The property is lazy-loaded on first access, using the cookie saved
    by the Facebook JavaScript SDK to determine the user ID of the active
    user. See http://developers.facebook.com/docs/authentication/ for
    more information.
    """
    @property
    def current_user(self):
        if not hasattr(self, "_current_user"):
            self._current_user = None
            cookie = facebook.get_user_from_cookie(
                self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
            if cookie:
                # Store a local instance of the user data so we don't need
                # a round-trip to Facebook on every request
                user = User.get_by_key_name(cookie["uid"])
                if not user:
                    graph = facebook.GraphAPI(cookie["access_token"])
                    profile = graph.get_object("me")
                    user = User(key_name=str(profile["id"]),
                                id=str(profile["id"]),
                                name=profile["name"],
                                email=profile["email"],
                                profile_url=profile["link"],
                                access_token=cookie["access_token"])
                    user.put()
                elif user.access_token != cookie["access_token"]:
                    user.access_token = cookie["access_token"]
                    user.put()
                self._current_user = user
        return self._current_user

这是我的模板/HTML:

<fb:login-button autologoutlink="true" perms="email"></fb:login-button>

{% if current_user %}
  <p><a href="{{ current_user.profile_url }}"><img src="http://graph.facebook.com/{{ current_user.id }}/picture?type=square"/></a></p>
  <p>Hello, {{ current_user.name|escape }}</p>
  <p>email: {{ current_user.email }} </p>
{% endif %}

是不是哪里出了问题?有没有其他方法可以获取用户的电子邮件?

3 个回答

0

你的代码看起来没问题,所以我猜可能是你没有正确的扩展权限。如果你想获取电子邮件地址,就必须请求“email”这个扩展权限。你可以在这里找到扩展权限的列表。在使用图形API读取这些属性之前,你必须先请求这些权限。

1

在创建用户的时候会写入邮箱。可能你正在尝试访问那些在你没有邮箱权限时创建的用户,所以他们的邮箱就变成了None(空值)。那么,对于新创建的用户对象,这个问题也会出现吗?

1

我放弃了使用 facebook.pyfacebookoauth.py,自己用 urlfetch 做了一个 OAuth 2 客户端。你可以查看 Facebook 文档中的 '在网页应用中验证用户'

另外,我在请求 https://graph.facebook.com/oauth/authorize?https://graph.facebook.com/oauth/access_token? 时,加入了 scope='email'

撰写回答