Page not found (404) Error in Django when creating a checkout session with Stripe

Question:

I am working on my first Stripe integration project to Django and I have landed into a problem that I have not managed to figure out a solution. I am trying to create a session whereby users can be redirected to the page where they can make a payment.
Here is my views.py:

class ProductLandingPageView(TemplateView):
    template_name = "landing.html"

    def get_context_data(self, **kwargs):
        product = Product.objects.get(name="Test Product")
        context = super(ProductLandingPageView, self).get_context_data(**kwargs)
        context.update({
            "product": product,
            "STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLISHABLE_KEY
        })
        return context

class CreateCheckoutSessionView(View):
    def post(self, request, *args, **kwargs):
        product_id = self.kwargs["pk"]
        product = Product.objects.get(id=product_id)
        YOUR_DOMAIN = "http://127.0.0.1:8000"
        checkout_session = stripe.checkout.Session.create(
            line_items=[
                {
                    # Provide the exact Price ID (for example, pr_1234) of the product you want to sell
                    'price': '{{product.price}}',
                    'quantity': 1,
                },
            ],
            metadata={
                "product_id": product.id
            },
            mode='payment',
            success_url=YOUR_DOMAIN + '/success/',
            cancel_url=YOUR_DOMAIN + '/cancel/',
        )
        return redirect(checkout_session.url, code=303)

Here is my urls.py;

urlpatterns = [
    path('', ProductLandingPageView.as_view(), name='landing'),
    path('success/', SuccessView.as_view(), name='success'),
    path('cancel/', CancelView.as_view(), name='cancel'),
    path('create-checkout-session/<pk>', CreateCheckoutSessionView.as_view(), name='create-checkout-session'),
]

Also here is the templatate where the checkout button is located:

<body>
    <section>
      <div class="product">
        <!-- <img src="https://i.imgur.com/EHyR2nP.png" alt="The cover of Stubborn Attachments" /> -->
        <div class="description">
          <h3>{{product.name}}</h3>
          <h5>${{product.price}}</h5>
        </div>
      </div>
      <form action="/create-checkout-session" method="POST">
        <button type="submit" id="checkout-button">Checkout</button>
      </form>
    </section>
    {% csrf_token %}
  </body>
   <script type="text/javascript">
        const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        // Create an instance of the Stripe object with your publishable API key
        var stripe = Stripe("{{ STRIPE_PUBLISHABLE_KEY }}");
        var checkoutButton = document.getElementById("checkout-button");
    checkoutButton.addEventListener("click", function () {
        fetch("{% url 'create-checkout-session' pk=product.id %}", {
        method: "POST",
        headers: {
            'X-CSRFToken': csrftoken
        }
      })
        .then(function (response) {
          return response.json();
        })
        .then(function (session) {
          return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function (result) {
         
          if (result.error) {
            alert(result.error.message);
          }
        })
        .catch(function (error) {
          console.error("Error:", error);
        });
    });
    </script>

</html>

Attached is the screenshot of the error in the browser Screenshot of error

Any help will be highly appreciated.

Asked By: KipronoKirui

||

Answers:

Your urls.py await you to provide pk as URL parameter, on picture you are not providing anything. So urls.py never finds the right route.

And please urls.py:

urlpatterns = [
    ...
    path('create-checkout-session/<int:pk>', CreateCheckoutSessionView.as_view(), name='create-checkout-session'),
]

views.py

class CreateCheckoutSessionView(View):
    def post(self, request, *args, **kwargs):
        product_id = self.kwargs["pk"]
        try:
            product = Product.objects.get(id=product_id)
        
            YOUR_DOMAIN = "http://127.0.0.1:8000"
            checkout_session = stripe.checkout.Session.create(
                line_items=[
                {
                    # Provide the exact Price ID (for example, 
                    # pr_1234) of the product you want to sell
                    'price': product.price,
                    'quantity': 1,
                    },
                ],
                metadata={
                    "product_id": product.id
                },
                mode='payment',
                success_url=YOUR_DOMAIN + '/success/',
                cancel_url=YOUR_DOMAIN + '/cancel/',
            )
            return redirect(checkout_session.url, code=303)
        except Product.DoesNotExist:
            return render(request, tmpl, {'error': 'product does not exist'})

template html:

{% if error %}
    {{ error }}
{% endif %}
Answered By: Danijel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.