Я впервые создаю платеж для веб-сайта электронной коммерции с использованием нашивки, я следую руководству и тщательно проанализировал каждый шаг, но всегда получаю сообщение об ошибке неаутентифицированного, и мне неясно, что происходит неправильно.
Я новичок в Django, поэтому я стараюсь как можно больше учиться на своих ошибках.
Вот мои views.py
class PaymentView(View):
def get(self, *args, **kwargs):
# order
order = Order.objects.get(user=self.request.user, ordered=False)
context = {
'order': order
}
return render(self.request, "payment.html", context)
# `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create-token
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)
try:
charge = stripe.Charge.create(
amount=amount, # cents
currency="usd",
source=token,
)
# create 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.ordered = True
order.payment = payment
order.save()
messages.success(self.request, "Your Order was Successful ! ")
return redirect("/")
except stripe.error.CardError as e:
body = e.json_body
err = body.get('error', {})
messages.error(self.request, f"{err.get('message')}")
# Since it's a decline, stripe.error.CardError will be caught
return redirect("/")
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.error(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.error(self.request, "Not Authenticated")
return redirect("/")
except stripe.error.APIConnectionError as e:
# Network communication with Stripe failed
messages.error(self.request, "Network 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
# send an email to ourselves
messages.error(
self.request, "A serious Error Occured. We have been notified.")
return redirect("/")
здесь мой model.py
class Payment(models.Model):
stripe_charge_id = models.CharField(max_length=50)
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL, blank=True, null=True)
amount = models.FloatField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
и вот форма.py
class CheckoutForm(forms.Form):
street_address = forms.CharField(widget=forms.TextInput(attrs={
'placeholder': '1234 Main St',
'class': 'form-control'
}))
apartment_address = forms.CharField(required=False, widget=forms.TextInput(attrs={
'placeholder': 'Apartment or suite',
'class': 'form-control'
}))
province = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control'
}))
country = CountryField(blank_label='(select country)').formfield(
widget=CountrySelectWidget(attrs={
'class': 'custom-select d-block w-100'
}))
postal_code = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control'
}))
same_shipping_address = forms.BooleanField(required=False)
save_info = forms.BooleanField(required=False)
payment_option = forms.ChoiceField(
widget=forms.RadioSelect, choices=PAYMENT_CHOICES)
Спасибо