Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've been unable to generate token in the stripe. Just getting Invalid parameter. Here is my views.py: class PaymentView(View): def get(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = { 'order': order, 'DISPLAY_COUPON_FORM': False, 'STRIPE_PUBLIC_KEY': settings.STRIPE_PUBLIC_KEY } return render(self.request, 'payment.html', context)

    else:
        messages.warning(self.request, "You've not added billing address.")
        return redirect('e_commerce:checkout')

def post(self, *args, **kwargs):
    order = Order.objects.get(user=self.request.user, ordered=False)
    token = self.request.POST.get('stripeToken')

    amount = int(order.get_total()*100)  # cents
    try:
        charge = stripe.Charge.create(
            amount=amount,
            currency="usd",
            source=token
        )

        # order.ordered = True
        # create the payment
        payment = Payment()
        payment.stripe_charge_id = charge['id']
        payment.user = self.request.user
        payment.amount = order.get_total()
        payment.save()

        # assign the payment to the order
        #order_items = order.items.all()
        #order_items.update(ordered=True)
        #for item in order_items:
            #item.save()
        order.ordered = True
        order.payment = payment
        # TODO assign ref code
        #order.ref_code = create_ref_code()
        order.save()
        # print("your order placed!")
        messages.success(self.request, "your order was successful.")
        return redirect("/e_commerce")



    except stripe.error.CardError as e:
        # Since it's a decline, stripe.error.CardError will be caught
        body = e.json_body
        err = body.get('error', {})
        messages.warning(self.request, f"{err.get('messages')}")
        return redirect("/e_commerce")
    except stripe.error.RateLimitError as e:
        # Too many requests made to the API too quickly
        messages.warning(self.request, "Rate limit error")
        return redirect("/e_commerce")

    except stripe.error.InvalidRequestError as e:
        # Invalid parameters were supplied to Stripe's API
        messages.warning(self.request, "Invalid parameters ,Please try again!")
        return redirect("/e_commerce")
    except stripe.error.AuthenticationError as e:
        # Authentication with Stripe's API failed
        # (maybe you changed API keys recently)
        messages.warning(self.request, "Authentication error ")
        return redirect("/e_commerce")
    except stripe.error.APIConnectionError as e:
        # Network communication with Stripe failed
        messages.warning(self.request, "Network error")
        return redirect("/e_commerce")
    except stripe.error.StripeError as e:
        # Display a very generic error to the user, and maybe send
        # yourself an email
        messages.warning(
            self.request, "Something went wrong.You were not charged.Please try again.")
        return redirect("/e_commerce")
    except Exception as e:
        # Something else happened, completely unrelated to Stripe
        messages.warning(self.request, "A serious error occured.We have been notified.")
        return redirect("/e_commerce")
        messages.warning(self.request, "Invalid data received.")
        return redirect("payment/stripe")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
529 views
Welcome To Ask or Share your Answers For Others

1 Answer

#Python Code
import stripe
data = stripe.PaymentIntent.create(
    setup_future_usage='off_session',
    amount=10000,
    currency='INR,
    payment_method_types=['card'],
)
return render(request, 'stripe-payment.html', {
    'client_secret': data.client_secret,
    'p_id': data.id,
    'stripeKey': settings.STRIPE_PUBLISHABLE_KEY,

})

##stripe-payment.html

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://js.stripe.com/v3/"></script>
    <title>Pay</title>
</head>
<style>
    .pay-div {
        padding: 25px;
        background: linear-gradient(to right, #8c73cb 0%, #0c8dbc 100%);
        width: 100%;
        max-width: 600px;
        margin: 0 auto;
        border-radius: 20px;
    }

    .pay-box {
        width: 100%;
        height: auto;
        min-height: calc(100vh - 10px);
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .pay {
        display: flex;
        justify-content: space-between;
        color: #fff;
        align-items: flex-start;
    }

    .form-group label {
        color: #ffffffba;
        font-size: 18px;
    }

    .form-group input {
        height: 50px;
    }

    input.form-control.amount-input {
        background-color: transparent;
    }

    input.form-control.amount-input::placeholder {
        color: #fff;
    }

    span#basic-addon2 {
        background-color: #0d4665;
        color: #fff;
    }

    label.form-check-label a {
        color: #123e61;
        padding: 10px;
    }

    label.form-check-label {
        color: #fff;
        font-size: 18px;
    }

    button.btn.btn-continue {
        width: 120px;
        height: 45px;
        background-color: #0d4665;
        color: #c1daec;
        font-size: 20px;
    }

    .pay2 h1 {
        text-transform: uppercase;
    }


    /* Hide HTML5 Up and Down arrows. */
    input[type="number"]::-webkit-outer-spin-button,
    input[type="number"]::-webkit-inner-spin-button {
        -webkit-appearance: none;
        margin: 0;
    }

    input[type="number"] {
        -moz-appearance: textfield;
    }

    .StripeElement {
        box-sizing: border-box;
        height: 40px;
        padding: 10px 12px;
        border: 1px solid transparent;
        border-radius: 4px;
        background-color: white;
        box-shadow: 0 1px 3px 0 #e6ebf1;
        -webkit-transition: box-shadow 150ms ease;
        transition: box-shadow 150ms ease;
    }

    .StripeElement--focus {
        box-shadow: 0 1px 3px 0 #cfd7df;
    }

    .StripeElement--invalid {
        border-color: #fa755a;
    }

    .StripeElement--webkit-autofill {
        background-color: #fefde5 !important;
    }
</style>
<script>
    '{% if user_id == None %}'
    alert('Please pass user id')
    '{% endif %}'
</script>

<body>
    <div class="container">
        <div class="pay-box">
            <div class="pay-div">
                <div class="row mt-3">
                    <div class="col-md-5">
                        <div class="form-group">
                            <label>Amount to transfar</label>
                            <div class="input-group mb-3">
                                <input type="number" class="form-control amount-input" required id="amount"
                                    value="100" placeholder="10.00" name="amount" >
                                <div class="input-group-append">
                                    <span class="input-group-text" id="basic-addon2"
                                        style="text-transform: uppercase;">INR</span>
                                </div>
                                <div id='div_amount'></div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-7">
                        <div class="form-group">
                            <label>Card Holder Name</label>
                            <input type="text" class="form-control" name="name" value="" id="card-holder-name"
                                required placeholder="Mr X">
                            <div id="div_name"></div>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="form-group">
                            <label for="card-element">
                                Credit or debit card
                            </label>
                            <div id="card-element">
                            </div>
                            <div id="card-errors" style="color: red;" role="alert">
                            </div>
                        </div>
                    </div>
                    <div id="error" style="color: red;"></div>
                    <div class="col-md-12 text-center mt-5">
                        <button id="card-button" data-secret="{{client_secret}}" class="btn btn-continue">Pay
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>
    <script type="text/javascript">
        var stripe = Stripe('{{stripeKey}}');
        var elements = stripe.elements();
        var cardElements = elements.create('card');
        cardElements.mount('#card-element');
        var cardButton = document.getElementById('card-button')
        var cardHolderName = document.getElementById('card-holder-name')
        var clientsecret = cardButton.dataset.secret
        $("#card-button").prop('disabled', false);
        cardButton.addEventListener('click', function (ev) {
            stripe.handleCardPayment(
                clientsecret, cardElements, {
                payment_method_data: {
                    billing_details: {
                        name: cardHolderName.value,
                    }
                }
            }
            ).then(function (result) {
                console.log(result.error.message)
                $('#error').html(result.error.message)
                if (result.error) {
                    jQuery.ajax(
                        {
                            type: "GET",
                            url: "/failed-transaction",
                            data: {
                                p_id: '{{p_id}}',
                                user_id: '1234'
                            },
                            success: function (data) {
                                console.log('')
                            }, error: function (jqXHR, textStatus, errorThrown) {
                                console.log('error')
                            }

                        })
                } else {
                    console.log("success")
                }
            })
        })

    </script>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...