Я пытаюсь зарядить пользователя с помощью полосы в Django. Проблема, с которой я сталкиваюсь, заключается в том, что, когда я печатаю свое значение stripeToken, в командной строке оно печатает «None». Вот почему я получаю «Ошибка неверных параметров». Я прокомментировал все ошибки, просто чтобы увидеть реальную ошибку, и это было:
InvalidRequestError at /payment/stripe/ Request req_5yo1v0CwbYGjTV: Must provide source or customer.
Почему мое значение stripeToken прибывает None? Может ли кто-нибудь помочь мне в решении этой проблемы? Заранее спасибо.
My Views.py:
class PaymentView(View):
def get(self, *args, **kwargs):
the_id = self.request.session['cart_id']
cart = Cart.objects.get(id=the_id)
order = Order.objects.get(cart=cart)
token = self.request.POST.get('stripeToken')
print(cart)
print(order)
print(token)
return render(self.request, "orders/payment.html")
def post(self, *args, **kwargs):
the_id = self.request.session['cart_id']
cart = Cart.objects.get(id=the_id)
order = Order.objects.get(cart=cart)
amount = int(order.final_total * 100) # to convert it into cents
token = self.request.POST.get('stripeToken')
try:
# user_stripe = self.request.user.userstripe.stripe_id
# customer = stripe.Customer.retrieve(user_stripe)
charge = stripe.Charge.create(
amount= amount,
currency="usd",
# card= card,
# customer = customer,
source = token,
description = "Charge for %s" %(self.request.user.username)
)
# card = customer.cards.create(card=token)
payment = Payment()
payment.stripe_charge_id = charge['id']
payment.user = self.request.user
payment.amount = int(order.final_total())
payment.save()
order.payment = payment
order.save()
messages.success(self.request, "Your order was successful")
return redirect("/")
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.error(self.request, f"{err.get('message')}")
except stripe.error.RateLimitError as e:
# Too many requests made to the API too quickly
messages.error(self.request, "Rate Limit Error")
return redirect("/")
except stripe.error.InvalidRequestError as e:
# Invalid parameters were supplied to Stripe's API
messages.warning(self.request, "Invalid Parameters")
return redirect(".")
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("/")
except stripe.error.APIConnectionError as e:
# Network communication with Stripe failed
messages.warning(self.request, "API Connection Error")
return redirect("/")
except stripe.error.StripeError as e:
# Display a very generic error to the user, and maybe send
# yourself an email
messages.error(self.request, "Something went wrong. You were not charged. Please try again.")
return redirect("/")
except Exception as e:
# Something else happened, completely unrelated to Stripe
messages.error(self.request, "A serious error occured. We have been notified.")
return redirect("/")
context = {"cart": cart, 'order': order}
template = "orders/payment.html"
return render(self.request, template, context)
Мой платеж. html:
{% block content %}
<div class="current-card-form">
<form action="." method="post" class="stripe-form">
{% csrf_token %}
<input type="hidden" name="use_default" value="true">
<div class="stripe-form-row">
<button id="stripeBtn">Submit Payment</button>
</div>
<div id="card-errors" role="alert"></div>
</form>
</div>
<script nonce=""> // Create a Stripe client.
var stripe = Stripe('');
// Create an instance of Elements.
var elements = stripe.elements();
// 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('stripe-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.
stripeTokenHandler(result.token);
}
});
});
// Submit the form with the token ID.
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('stripe-form');
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>
{% endblock %}