简体   繁体   English

使用 Stripe 的 Django 中的未验证错误

[英]Not Authenticated Error in Django using Stripe

I am creating for the very first time a payment for an e-commerce website using stripe, I am following a guide and have reviewed every step carefully but always getting Not Authenticated Error and I'm unclear what is going wrong.我第一次使用条纹为电子商务网站创建付款,我遵循指南并仔细审查了每一步,但总是出现未验证错误,我不清楚出了什么问题。

I am new to Django so I'm trying to learn as much as possible from my errors.我是 Django 的新手,所以我试图从我的错误中尽可能多地学习。

Here is my views.py这是我的意见.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("/")

here is my model.py这是我的 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

and here is the forms.py这是 forms.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)

Thank you谢谢

I am following a guide and have reviewed every step carefully but always getting Not Authenticated Error and I'm unclear what is going wrong.我正在遵循指南,并仔细检查了每一步,但总是出现未验证错误,我不清楚出了什么问题。

When you see this type of error from Stripe it usually means that you haven't provided a secret key, or have provided a mal-formed string as a secret key (it should be of the form sk_test_xyz (for test mode) or sk_live_xyz (for live mode).当您从 Stripe 看到这种类型的错误时,通常意味着您没有提供密钥,或者提供了格式错误的字符串作为密钥(它应该是sk_test_xyz (用于测试模式)或sk_live_xyz (用于实时模式)。

I would double-check that you have a line where you import stripe followed by another line setting the API key as follows:我会仔细检查您是否有一行import stripe ,然后是另一行设置 API 键,如下所示:

stripe.api_key = "sk_test_xyz"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM