【免费下载链接】django-allauth
Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication. 🔁 Mirror of https://codeberg.org/allauth/django-allauth/
导读
本文以 django-allauth 官方文档中 Stripe provider 的配置指南为主体,结合仓库内 allauth/socialaccount/providers/stripe/ 的完整源码实现与测试用例,系统讲解如何在 Stripe 仪表盘注册 OAuth2 应用、获取 client_id 与 secret key、配置回调 URL,并在 Django 项目中完成登录接入。读完本文,你将掌握 Stripe Connect 独立账户(standalone accounts)场景下的完整 OAuth2 接入方法,并理解从授权跳转到用户资料落库的底层调用链。
一、Stripe Provider 在 django-allauth 中的定位
django-allauth 将 Stripe 作为标准的 OAuth2 第三方登录 provider 实现,源码位于 allauth/socialaccount/providers/stripe/,由四个文件组成:
provider.py:定义 provider 标识、名称、字段提取逻辑与默认权限范围;views.py:定义 OAuth2 授权、令牌换取、用户资料拉取等关键端点;urls.py:注册登录与回调两个 URL 模式;tests.py(位于 tests/apps/socialaccount/providers/stripe/tests.py):提供可复现的响应格式佐证。
该 provider 面向的是 Stripe Connect 平台模式:你的应用作为 Connect 平台,通过 OAuth2 授权让用户(商家)授权你的平台访问其 Stripe 账户信息。这与普通的"用第三方账号登录"略有区别——登录后 django-allauth 拿到的账号数据来自 Stripe 的 Account API。
二、在 Stripe 仪表盘注册 OAuth2 应用
1. 进入 Connect 应用设置页
原文档明确指出,注册 OAuth2 应用的位置是 Stripe 仪表盘的 Connect → Settings 页面(Account applications settings):
https://dashboard.stripe.com/account/applications/settings
这是 Stripe Connect 平台模式下的应用注册入口,与普通 API key 管理页面相互独立。
2. 获取 Development 与 Production 两套 client_id
该页面会同时提供两套 client_id:
- Development
client_id:用于本地开发与测试环境,对应测试模式的密钥体系; - Production
client_id:用于线上环境,对应真实密钥体系。
在 django-allauth 的 admin 后台(SocialApp)中注册应用时,需要根据当前部署环境选择对应的 client_id 填写。从源码看,client_id 会被 OAuth2 客户端直接拼入授权请求,见 allauth/socialaccount/providers/oauth2/provider.py 中的 redirect() 方法——它通过 oauth2_adapter.get_client(request, app) 构造客户端,app.client_id 即来自你在 admin 中填写的值。
3. 在 "Website URL" 中注册回调地址
OAuth2 应用的回调(callback)地址需要在 Settings 页面的 "Website URL" 输入框中注册。原文档给出的示例为:
http://example.com/accounts/stripe/login/callback/
这里有几个要点:
-
路径必须与 django-allauth 实际暴露的回调端点一致。从 allauth/socialaccount/providers/oauth2/urls.py 可以看到,
default_urlpatterns(StripeProvider)会生成两个 URL:{provider_slug}/login/ → 名为 {provider_id}_login 的登录视图 {provider_slug}/login/callback/ → 名为 {provider_id}_callback 的回调视图由于 provider id 为
stripe,且 socialaccount 的 URL 默认挂载在accounts/前缀下,最终得到的就是/accounts/stripe/login/与/accounts/stripe/login/callback/,与原文档示例路径完全吻合。 -
回调地址必须对外可访问:Stripe 在授权完成后会 302 跳转到该地址并携带授权码
code,因此该地址不能是内网地址。
三、获取 OAuth2 secret key
原文档特别强调了一个容易踩坑的细节:Stripe 的 OAuth2 secret key 并不在 Connect 应用设置页面,而是与你平时调用 Stripe API 所用的 secret key 完全相同,需要在仪表盘的 API keys 页面获取:
https://dashboard.stripe.com/account/apikeys
因此 django-allauth admin 后台 SocialApp 中的 Secret key 字段应填写:
- 开发环境 →
sk_test_...开头的测试密钥; - 生产环境 →
sk_live_...开头的正式密钥。
这一设计从源码中也能得到印证:在 allauth/socialaccount/providers/stripe/views.py 中,access_token_url 指向 https://connect.stripe.com/oauth/token,而换取令牌时使用的正是 app.secret(见 allauth/socialaccount/providers/oauth2/views.py 的 get_client() 方法),Stripe 端即用它来校验平台身份。
四、在 Django 项目中完成配置
1. 注册 provider 应用
在 settings.py 的 INSTALLED_APPS 中加入:
INSTALLED_APPS = [
# ... 其他应用
"allauth",
"allauth.account",
"allauth.socialaccount",
"allauth.socialaccount.providers.stripe",
]
该注册方式与仓库内置测试项目的配置一致,参见 tests/projects/common/settings.py。
2. 在 admin 后台创建 SocialApp
进入 Django admin,在 Social applications 中添加一条记录:
| 字段 | 填写值 |
|---|---|
| Provider | Stripe |
| Name | 自定义名称(如 "Stripe Connect") |
| Client id | 上一步获取的 Development / Production client_id |
| Secret key | 从 API keys 页面获取的 sk_test_... / sk_live_... 密钥 |
| Sites | 选择当前站点(必须绑定,否则运行时无法解析到该应用) |
3.(可选)自定义权限范围
从 allauth/socialaccount/providers/stripe/provider.py 可知,Stripe provider 的默认授权范围是:
def get_default_scope(self):
return ["read_only"]
即默认以只读权限访问用户的 Stripe 账户。如需调整,可通过 SOCIALACCOUNT_PROVIDERS 配置覆盖(该机制由 allauth/socialaccount/providers/oauth2/provider.py 的 get_scope() 实现,SCOPE 设置优先于默认值):
SOCIALACCOUNT_PROVIDERS = {
"stripe": {
"SCOPE": ["read_write"],
}
}
注意:read_write 会申请对商家 Stripe 账户的读写权限,涉及资金敏感操作,生产环境请按最小权限原则选择。
五、源码级解析:Stripe Provider 的实现细节
1. Provider 类与字段提取
allauth/socialaccount/providers/stripe/provider.py 中定义了三个核心成员:
class StripeAccount(ProviderAccount):
def to_str(self):
default = super().to_str()
email = self.account.extra_data.get("email")
business = self.account.extra_data.get("business_name")
if business:
return f"{email or default} ({business})"
else:
return email or default
class StripeProvider(OAuth2Provider):
id = "stripe"
name = "Stripe"
account_class = StripeAccount
oauth2_adapter_class = StripeOAuth2Adapter
def extract_uid(self, data):
return data["id"]
def extract_common_fields(self, data):
return dict(name=data.get("display_name"), email=data.get("email"))
extract_uid以 Stripe 账户对象中的id(形如acct_xxx)作为本地唯一标识;extract_common_fields将display_name与email映射为 django-allauth 的通用用户字段;StripeAccount.to_str在存在business_name时展示为email (business_name)格式,便于后台区分商家账号。
2. OAuth2 适配器与三个关键端点
allauth/socialaccount/providers/stripe/views.py 定义了 StripeOAuth2Adapter:
class StripeOAuth2Adapter(OAuth2Adapter):
provider_id = "stripe"
access_token_url = "https://connect.stripe.com/oauth/token"
authorize_url = "https://connect.stripe.com/oauth/authorize"
profile_url = "https://api.stripe.com/v1/accounts/%s"
def complete_login(self, request, app, token, **kwargs):
response = kwargs["response"]
headers = {"Authorization": f"Bearer {token.token}"}
with get_adapter().get_requests_session() as sess:
url = self.profile_url % response.get("stripe_user_id")
resp = sess.get(url, headers=headers)
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request, extra_data)
三个端点各自承担的角色:
| 端点 | 作用 |
|---|---|
authorize_url | 将用户引导至 Stripe Connect 授权页,携带 client_id、redirect_uri、scope 等参数 |
access_token_url | 用授权码 code 换取 access_token(Stripe 返回的令牌数据中还包含 stripe_user_id) |
profile_url | 通过 Bearer {access_token} 调用 Stripe Account API,拉取账户详情作为 extra_data |
complete_login 是 OAuth2 回调的收尾环节:它从令牌响应中取出 stripe_user_id(形如 acct_xxx),拼入 profile_url 后携带 Bearer 令牌发起请求,将返回的账户 JSON 交给 sociallogin_from_response 完成用户创建/登录流程。
3. 测试用例对响应格式的佐证
测试文件 给出了两组可复现的响应样本,有助于理解数据流:
令牌交换响应(get_login_response_json)关键字段:
{
"access_token": "testac",
"livemode": false,
"token_type": "bearer",
"stripe_publishable_key": "pk_test_someteskey",
"stripe_user_id": "acct_sometestid",
"scope": "read_write",
"refresh_token": "testrf"
}
账户资料响应(get_mocked_response)关键字段:
{
"id": "acct_sometestid",
"object": "account",
"business_name": null,
"country": "SE",
"default_currency": "eur",
"display_name": "Test",
"email": "test@example.com",
"charges_enabled": true,
"transfers_enabled": true
}
测试还验证了 StripeAccount.to_str 在无 business_name 时返回邮箱 test@example.com 的展示逻辑,与第一节中的源码实现互相印证。
六、完整登录流程全景
结合 allauth/socialaccount/providers/oauth2/views.py 中的基类实现,Stripe 登录的完整链路如下:
- 发起登录:用户访问
/accounts/stripe/login/,OAuth2LoginView通过StripeOAuth2Adapter.get_client()构造 OAuth2 客户端,由OAuth2Provider.redirect()生成指向authorize_url的 302 跳转,同时将登录意图(process、next 等)存入会话状态(state),见 oauth2/provider.py; - 用户授权:用户在 Stripe Connect 页面完成授权后,Stripe 重定向回
/accounts/stripe/login/callback/?code=...&state=...; - 校验与换令牌:
OAuth2CallbackView.dispatch()先校验state与错误参数,再调用get_access_token_data()向access_token_url换令牌,parse_token()解析出SocialToken(含expires_in过期时间),见 oauth2/views.py; - 拉取账户:
StripeOAuth2Adapter.complete_login()用令牌调用 Account API 得到extra_data; - 完成登录:
complete_social_login()依据extract_uid查找或创建SocialAccount,触发社交登录信号,最终完成用户会话建立。
值得留意的是,回调视图对用户取消授权(error=access_denied)与未知错误做了区分处理,分别映射为 AuthError.CANCELLED 与 AuthError.UNKNOWN,并渲染认证错误页,保证异常路径可控。
七、注意事项与排错提示
- 环境与密钥匹配:Development
client_id必须配合sk_test_...密钥,Productionclient_id必须配合sk_live_...密钥,混用会导致令牌换取失败; - 回调地址一致性:Stripe 后台 "Website URL" 中填写的地址必须与
/accounts/stripe/login/callback/完全一致(含域名与协议),否则 Stripe 会拒绝回调; - 站点绑定:忘记在 admin 中为
SocialApp绑定当前Site是常见的运行时报错来源(DoesNotExist/ 应用解析失败); - 权限最小化:默认
read_only范围已能满足大多数"读取账户信息"场景;仅在确实需要代商家操作时才考虑提升为read_write; - Stripe Connect 模式:该 provider 面向 Connect 平台模式,更多关于独立账户(standalone accounts)的业务背景可参考原文档末尾指向的 Stripe Connect 官方说明。
结语
本文从 docs/socialaccount/providers/stripe.rst 的官方配置指南出发,完整覆盖了 Stripe 仪表盘应用注册、client_id 与 secret key 获取、回调 URL 配置三个实操环节,并通过 provider.py、views.py、urls.py 与 测试用例 的源码级剖析,还原了从授权跳转到用户资料落库的完整链路。按本文步骤配置后,你的 Django 应用即可通过 Stripe Connect OAuth2 安全地接入商家账户授权流程。
【免费下载链接】django-allauth
Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication. 🔁 Mirror of https://codeberg.org/allauth/django-allauth/
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



