InvalidRequestError:此客户没有附加的付款来源

时间:2018-02-18 06:10:54

标签: django stripe-payments

我一直在关注Stripe的快速入门指南。

https://stripe.com/docs/quickstart

https://stripe.com/docs/subscriptions/quickstart

这就是我的表格:

<form id="register-form" method="post">
    {% csrf_token %}
    {% for field in registration_form %}
        <p>{{ field }}</p>
        {% if field.errors %}
            <p class="text-danger">{{ field.errors.as_text|cut:"* "|escape }}</p>
        {% endif %} 
    {% endfor %}
    {% if registration_form.non_field_errors %}
        <p class="text-danger">{{ registration_form.non_field_errors.as_text|cut:"* "|escape }}</p>
    {% endif %}
    <div id="stripe-wrapper">
        <p id="card-element"></p>
    </div>                  
    <p id="card-errors" role="alert"></p>
    <button id="register-btn" class="btn btn-primary" type="submit">Register</button>

    <script type="text/javascript">
        var displayError=   document.getElementById('card-errors');
        var stripe=         Stripe("pk_test_BjhejGz5DZNcSHUVaqoipMtF");
        var elements=       stripe.elements();

        var style=      {
            base: {
                fontSize: "1.1875rem",
                fontSmoothing: "always",
                fontWeight: "600"
            }
        };

        var card=   elements.create("card",{style:style});
        card.mount("#card-element");
        card.addEventListener('change', function(event) {

            if (event.error) {
                displayError.textContent = event.error.message;
            } else {
                displayError.textContent = '';
            }
        });

        var formID= "register-form";
        var form=   document.getElementById(formID);
        form.addEventListener("submit",function(event){
            event.preventDefault();

            stripe.createToken(card).then(function(result){
                if(result.error) {
                    displayError.textContent=   result.error.message;
                } else {
                    stripeTokenHandler(result.token, formID);
                }                               
            })
        });
        // tut https://stripe.com/docs/stripe-js/elements/quickstart#create-form
        function stripeTokenHandler(token, formID) {
            // Insert the token ID into the form so it gets submitted to the server
            var form = document.getElementById(formID);
            var hiddenInput = document.createElement('input');
            hiddenInput.setAttribute('type', 'hidden');
            hiddenInput.setAttribute('name', 'stripeToken');
            hiddenInput.setAttribute('value', token.id);
            form.appendChild(hiddenInput);
            // Submit the form
            form.submit();
        }
    </script>
</form>

然后我的views.py有了这个:

if registration_form.is_valid():
    stripe.api_key= "sk_test_8rdFokhVsbsJJysHeKgyrMTc"
    stripeCustomer= stripe.Customer.create(
        email=request.POST["username"],
    )
    subscription=   stripe.Subscription.create(
        customer=stripeCustomer["id"],
        items=[{"plan":"plan_CLFfBrRAKl7TRt"}],
    )

这给了我一个错误:

Internal Server Error: /login-register/
Traceback (most recent call last):
  File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/mezzanine/pages/middleware.py", line 98, in process_view
    return view_func(request, *view_args, **view_kwargs)
  File "/home/myUserName/myDjangoProjectWithStripe/product_blog/theme/views.py", line 154, in login_register
    items=[{"plan":"plan_CLFfBrRAKl7TRt"}],
  File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/stripe/api_resources/subscription.py", line 33, in create
    return super(Subscription, cls).create(**params)
  File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/stripe/api_resources/abstract/createable_api_resource.py", line 17, in create
    response, api_key = requestor.request('post', url, params, headers)
  File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/stripe/api_requestor.py", line 153, in request
    resp = self.interpret_response(rbody, rcode, rheaders)
  File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/stripe/api_requestor.py", line 365, in interpret_response
    self.handle_error_response(rbody, rcode, resp.data, rheaders)
  File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/stripe/api_requestor.py", line 178, in handle_error_response
    raise err
InvalidRequestError: Request req_o39ceLlhtpJmmr: This customer has no attached payment source

如何将付款来源附加到客户?由于我正在测试,我使用测试信用卡,其编号为4242 4242 4242 4242

2 个答案:

答案 0 :(得分:2)

错误意味着它所说的,客户没有附加的付款方式/来源。您正在为您的html表单添加stripeToken,但是您没有在服务器端执行任何操作。您需要将令牌添加到您的客户(在创建客户时将source设置为令牌),然后您将能够向客户收费,创建订阅等。

答案 1 :(得分:0)

您需要在注册时添加付款表单, 假设您有/ payment-form路由,请在views.py中添加以下内容:

from yourapp import settings

def payment_form(request):
    context = { "stripe_key": settings.STRIPE_PUBLIC_KEY }
    return render(request, "yourtemplate.html", context)

在模板中,复制并粘贴条纹文档的结帐部分下的表单。

<form action="/checkout" method="POST">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="stripe_key" # Make sure to wrap the variable name with double {}
    data-amount="2000"
    data-name="Your APp"
    data-description="Your Product"
    data-image="Link to your logo"
    data-currency="usd">
</script>
</form>

请注意,我们将条带public_key传递给data-key属性,默认情况下,它将使用您的实际公钥填充,但我发现更好地使用该变量。

我们还将表单的action属性设置为/ checkout,我们将在下一步中创建它。此路线将处理结账逻辑。

实际发生的是:当用户提交表单(即:付款)时,他们的银行帐户信息将被发送到条带进行处理。如果接受付款,则stripe将向表单的action属性中指定的端点发出POST请求。我们的想法是捕获该令牌并使用它来为用户的卡充电。