Django Stripe CheckoutSession страница GET

Я пытаюсь использовать метод GET на 127.0.0.1:8000/buy/1/ с 127.0.0.1:8000/item/1/, чтобы получить этот результат, так же как если бы я просто перешел на страницу "купить". Но кнопка почему-то не работает. Но вы можете увидеть /buy/1/ на кнопке в F12. Почему? Большое спасибо заранее.

Виды

class ProductLandingPageView(DetailView):
    model = Item
    template_name = 'items/items.html'
    context_object_name = 'item'


class CreateCheckoutSessionView(View): 
    
    def get(self, request, pk):
        item_id = self.kwargs["pk"]
        item = Item.objects.get(id=item_id)

        checkout_session = stripe.checkout.Session.create(
            success_url="https://morungexpress.com/uploads/2022/01/36931750_1642339369_cc2dfdf7494bfa9436aac0d4a882a653.jpg",
            cancel_url="https://englishlib.org/dictionary/img/wlibrary/c/5ffdb27d24e086.50388072.jpg",
            mode="payment",
            line_items=[
                {
                    'price_data': {
                        'currency': 'usd',
                        'unit_amount': item.price,
                        'product_data': {
                            'name': item.name
                        },
                    },
                    "quantity": 1,
                }
            ]
            )
        return JsonResponse({
            'id': checkout_session.id
        })

УРЛЫ

from django.urls import path
from .views import *

urlpatterns = [
    path('item/<int:pk>/', ProductLandingPageView.as_view(), name='item'),
    path('buy/<int:pk>/', CreateCheckoutSessionView.as_view(), name='buy')
]

HTML

<html>
  <head>
    <title>Buy {{ item.name }}</title>
  </head>
  <body>
        <h1>{{ item.name }}</h1>
        <p>{{ item.description }}</p>
        <p>{{ item.price }}</p>
    <button id="buy-button">Buy</button>
    <script type="text/javascript">
      var stripe = Stripe('pk_test_a9nwZVa5O7b0xz3lxl318KSU00x1L9ZWsF');
      var buyButton = document.getElementById(buy-button');
      buyButton.addEventListener('click', function() {
        fetch("{% url 'buy' item.id %}", {
          method: 'GET'})
        .then(response => return response.json())
        .then(session => stripe.redirectToCheckout({ sessionId: session.id }))
      });
    </script>

  </body>
  
</html>

В объявлении переменной допущена опечатка

var buyButton = document.getElementById(buy-button');

Это должно быть:

var buyButton = document.getElementById('.buy-button');

Я вижу несколько ошибок в коде фронтенда:

  • Stripe не определен. Обязательно включите его как объяснено здесь
  • .
  • document.getElementById(buy-button') должно быть document.getElementById('buy-button') (отсутствует ')
  • .then(response => return response.json()) должно быть .then(response => response.json()) (отсутствует ключевое слово return)

Если это все еще не устраняет проблему, пожалуйста, добавьте журналы к вашему коду и обязательно укажите точные сообщения об ошибках, которые вы видите.

Вернуться на верх