如何从Python中的表单POST提交访问Stripe标记?

时间:2018-04-23 17:57:08

标签: python-3.x stripe-payments

我使用几乎标准的Stripe代码来获取我可以从控制台看到的令牌成功,然后我将它隐藏在输入表单字段中传递给我的Python应用程序。

我可以从表单中返回数据,但不知道如何从对象访问令牌ID和其他数据。我想访问" stripe-token-return [object Object]"

中的数据

我的Python代码是:

@app.route('/newForm', methods=['POST', 'GET'])
def newForm():
    if request.method == 'POST':
        formData = request.values
        for key, value in formData.items():
            print(key, value)
        token = request.form['stripe-token-return']
        print(token)

以下是广泛使用的Stripe代码,我可以看到在登录控制台时成功获取令牌。

<script type="text/javascript">
    // Create a Stripe client.
    var stripe = Stripe('{{ key }}');

    // Create an instance of Elements.
    var elements = stripe.elements();

    // Custom styling can be passed to options when creating an Element.
    // (Note that this demo uses a wider set of styles than the guide below.)
    var style = {
        base: {
            color: '#32325d',
            lineHeight: '18px',
            fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
            fontSmoothing: 'antialiased',
            fontSize: '16px',
            '::placeholder': {
                color: '#aab7c4'
            }
        },
        invalid: {
            color: '#fa755a',
            iconColor: '#fa755a'
        }
    };

    // Create an instance of the card Element.
    var card = elements.create('card', {
        style: style
    });

    // Add an instance of the card Element into the `card-element` <div>.
    card.mount('#card-element');

    // Handle real-time validation errors from the card Element.
    card.addEventListener('change', function(event) {
        var displayError = document.getElementById('card-errors');
        if (event.error) {
            displayError.textContent = event.error.message;
        } else {
            displayError.textContent = '';
        }
    });

    // Handle form submission.
    var form = document.getElementById('payment-form');
    form.addEventListener('submit', function(event) {
        event.preventDefault();

        stripe.createToken(card).then(function(result) {
            if (result.error) {
                // Inform the user if there was an error.
                var errorElement = document.getElementById('card-errors');
                errorElement.textContent = result.error.message;
            } else {
                // Send the token to your server.
                // form.append($('<input type="hidden" name="stripeToken">').val(result.token.id));
                console.log(result.token);
                document.getElementById('stripe-token-return').value = result.token;
                form.submit();
            }
        });
    });
</script>

1 个答案:

答案 0 :(得分:2)

您想使用:

document.getElementById('stripe-token-return').value = result.token.id;

相反;现在它发送整个对象,而不仅仅是ID。