6

我正在使用 django-allauth 对用户进行身份验证(使用Patreon 的 API v1),它使用以下信息将 json 添加到数据库中。如果用户的承诺与特定层级匹配(或高于一个层级),我想在网站上显示额外的内容。

{
  "attributes": {
    "about": null,
    "can_see_nsfw": true,
    "created": "2019-05-20T20:29:02.000+00:00",
    "default_country_code": null,
    "discord_id": null,
    "email": "admin@email.com",
    "facebook": null,
    "facebook_id": null,
    "first_name": "Adm",
    "full_name": "Adm Nsm",
    "gender": 0,
    "has_password": true,
    "image_url": "https://c8.patreon.com/2/200/21383296",
    "is_deleted": false,
    "is_email_verified": false,
    "is_nuked": false,
    "is_suspended": false,
    "last_name": "Nsm",
    "social_connections": {
      "deviantart": null,
      "discord": null,
      "facebook": null,
      "instagram": null,
      "reddit": null,
      "spotify": null,
      "twitch": null,
      "twitter": null,
      "youtube": null
    },
    "thumb_url": "https://c8.patreon.com/2/200/21383296",
    "twitch": null,
    "twitter": null,
    "url": "https://www.patreon.com/user?u=21383296",
    "vanity": null,
    "youtube": null
  },
  "id": "21383296",
  "relationships": {
    "pledges": {
      "data": [
        {
          "id": "24461189",
          "type": "pledge"
        }
      ]
    }
  },
  "type": "user"
}

起初,我认为relationships.pledges.data.id 将具有当前层的ID,并且我设法为特定用户添加了一个额外的内容块,但显然这只是一厢情愿;在使用第二个帐户进行测试后,我认为是承诺级别的 ID 似乎每次都不同。我想我可能需要从Patreon 的 API请求更多信息,但不确定如何取回我需要的东西。

编辑:

据我所知,我需要从/api/oauth2/v2/members/{id}请求current_entitled_tiers

问题是所需的 ID 与用户登录后获得的 ID 不同。所以我首先需要使用已生成的 oauth 访问令牌和 GET /api/oauth2/v2/identity作为长 ID 号.

我当前的问题是,当我尝试从 /api/oauth2/v2/identity 获取 ID 时,我收到 401 错误代码:

<Response [401]>
{'errors': [{'code': 1, 'code_name': 'Unauthorized', 'detail': "The server could not verify that you are authorized to access the URL requested.  You either supplied the wrong credentia
ls (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.", 'id': 'b298d8b1-73db-46ab-b3f4-545e6f934599', 'status': '401', 'title': 'Unauthori
zed'}]}

我要发送的是:

headers = {"authorization": "Bearer " + str(access_token)}  # User's Access Token
req = requests.get("https://patreon.com/api/oauth2/v2/identity?include=memberships", headers=headers)

如果我通过/api/oauth2/v2/campaigns/{campaign_id}/members获得正确的 ID,我可以从/api/oauth2/v2/members/{id}请求并获得我需要的东西,但中间步骤使用当前登录用户以获取他们的 ID 使我无法理解。

谢谢你。

4

2 回答 2

4

我设法通过直接更改 django-allauth 来获得承诺。由于它使用 API v1,您需要更改范围才能从 API v2 端点获取信息。为此,我必须从 allauth 修改 patreon 提供程序和视图。

这只是我在 python 中的第二个项目,所以请原谅可能混乱或不理想的代码:

提供者.py

    # Change
    def get_default_scope(self):
        return ['pledges-to-me', 'users', 'my-campaign']

    # to
    def get_default_scope(self):
        return ['identity', 'identity[email]', 'campaigns', 'campaigns.members']

视图.py

"""
Views for PatreonProvider
https://www.patreon.com/platform/documentation/oauth
"""

import requests

from allauth.socialaccount.providers.oauth2.views import (
    OAuth2Adapter,
    OAuth2CallbackView,
    OAuth2LoginView,
)

from .provider import PatreonProvider


class PatreonOAuth2Adapter(OAuth2Adapter):
    provider_id = PatreonProvider.id
    access_token_url = 'https://www.patreon.com/api/oauth2/token'
    authorize_url = 'https://www.patreon.com/oauth2/authorize'
    profile_url = 'https://www.patreon.com/api/oauth2/v2/identity?include=memberships&fields[user]=email,first_name,full_name,image_url,last_name,social_connections,thumb_url,url,vanity'


    def complete_login(self, request, app, token, **kwargs):
        resp = requests.get(self.profile_url,
                            headers={'Authorization': 'Bearer ' + token.token})
        extra_data = resp.json().get('data')

        try:
            member_id = extra_data['relationships']['memberships']['data'][0]['id']
            member_url = f'https://www.patreon.com/api/oauth2/v2/members/{member_id}?include=currently_entitled_tiers&fields%5Btier%5D=title'
            resp_member = requests.get(member_url,
                                headers={'Authorization': 'Bearer ' + token.token})
            pledge_title = resp_member.json()['included'][0]['attributes']['title']
            extra_data["pledge_level"] = pledge_title

        except (KeyError, IndexError):
            extra_data["pledge_level"] = None
            pass


        return self.get_provider().sociallogin_from_response(request,
                                                             extra_data)


oauth2_login = OAuth2LoginView.adapter_view(PatreonOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(PatreonOAuth2Adapter)

有了它,您可以从 API v2 端点请求(仍在使用 APIv1 客户端,尚未测试它是否可以与 API v2 客户端一起使用),它会将质押标题添加到社交帐户的 extra_data 字段中。

于 2019-05-23T21:24:11.827 回答
2

我已经使用 Nick S 的部分答案更新了 django-allauth,以启用 Patreon API v2(从 django-allauth 0.40.0 开始)。

要使用 API v2,您现在只需在 settings.py 中更改 SOCIALACCOUNT_PROVIDERS 的 patreon 条目:

settings.py(添加到最后)

SOCIALACCOUNT_PROVIDERS = {
    'patreon': {
        'VERSION': 'v2',
    }
}

默认情况下,这也会将质押层添加到每个用户的社交帐户,并将其存储在extra_data['pledge_level'].

于 2019-06-28T03:48:32.697 回答