【问题标题】:Django: Stripe & POST requestDjango:条纹和 POST 请求
【发布时间】:2018-06-29 21:44:03
【问题描述】:

我目前正在尝试在我的 Django 项目中实现 Stripe Connect。标准帐户的条带文档状态:

假设没有发生错误,最后一步是使用提供的代码 向我们的 access_token_url 端点发出 POST 请求以获取 用户的 Stripe 凭据:

curl https://connect.stripe.com/oauth/token \
   -d client_secret=sk_test_Dur3X2cOCwyjlf9Nr7OCf3qO \
   -d code="{AUTHORIZATION_CODE}" \
   -d grant_type=authorization_code

我现在想知道如何在没有表单和用户操作(单击提交按钮)的情况下使用 Django 发送 POST 请求?

【问题讨论】:

  • github.com/stripe/stripe-python看看这个插件,功能齐全,
  • 您需要从服务器向 Stripe 发出请求——这不是客户端在浏览器中发出的请求。

标签: django stripe-payments


【解决方案1】:

由于 Standard Connect 的连接流程依赖 OAuth:

https://stripe.com/docs/connect/standard-accounts#oauth-flow

所以您可以使用像 Rauth 这样的 OAuth python 库来处理流程。

另外请注意,Stripe Python 库在此处提供了 OAuth 流程的实现:

https://github.com/stripe/stripe-python/blob/a938c352c4c11c1e6fee064d5ac6e49c590d9ca4/stripe/oauth.py

您可以在此处查看其用法示例:

https://github.com/stripe/stripe-python/blob/f948b8b95b6df5b57c7444a05d6c83c8c5e6a0ac/examples/oauth.py

该示例使用 Flask 而不是 Django,但应该让您对它的使用有一个很好的了解。

关于使用现有 OAuth 实现而不是自己直接实现调用的优势:我看到的一个优势是您的代码将重用通常涵盖所有不同用例的库(例如更好的错误处理)并且是也很好测试。

【讨论】:

  • 你拯救了我的一天!我什至不知道这个例子存在,但它有助于实现它。 (见下文)非常感谢@psmvac
【解决方案2】:

感谢@psmvac,我现在可以使用 Stripe 的 oAuth 以“正确”的方式实现它。如果有人尝试相同,这里有一些参考/示例 Django 代码。显然,必须配置 urls.py。这是我的views.py:

def stripe_authorize(request):
    import stripe

    stripe.api_key = ''
    stripe.client_id = 'XYZ'

    url = stripe.OAuth.authorize_url(scope='read_only')
    return redirect(url)


def stripe_callback(request):
    import stripe
    from django.http import HttpResponse
    # import requests

    stripe.api_key = 'XYZ'
    ## import json  # ?

    code = request.GET.get('code', '')
    try:
        resp = stripe.OAuth.token(grant_type='authorization_code', code=code)
    except stripe.oauth_error.OAuthError as e:
        full_response = 'Error: ' + str(e)
        return HttpResponse(full_response)

    full_response = '''
<p>Success! Account <code>{stripe_user_id}</code> is connected.</p>
<p>Click <a href="/stripe-deauthorize?stripe_user_id={stripe_user_id}">here</a> to
disconnect the account.</p>
'''.format(stripe_user_id=resp['stripe_user_id'])
    return HttpResponse(full_response)


def stripe_deauthorize(request):
    from django.http import HttpResponse
    import stripe

    stripe_user_id = request.GET.get('stripe_user_id', '')
    try:
        stripe.OAuth.deauthorize(stripe_user_id=stripe_user_id)
    except stripe.oauth_error.OAuthError as e:
        return 'Error: ' + str(e)

    full_response = '''
<p>Success! Account <code>{stripe_user_id}</code> is disconnected.</p>
<p>Click <a href="/">here</a> to restart the OAuth flow.</p>
'''.format(stripe_user_id=stripe_user_id)
    return HttpResponse(full_response)

【讨论】:

    猜你喜欢
    • 2016-10-18
    • 2018-09-02
    • 2015-06-21
    • 2013-02-08
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    相关资源
    最近更新 更多