I am trying to use GET method on 127.0.0.1:8000/buy/1/ from 127.0.0.1:8000/item/1/, to get this result, just like if i simply go to "buy" page. But the button doesnt work for some reason. But you can see /buy/1/ on a button in F12. Why? Much thanks in advance.
Views
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
})
URLS
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>
CodePudding user response:
I see a few errors in the frontend code:
Stripe
is not defined. Make sure you include it as explained heredocument.getElementById(buy-button')
should bedocument.getElementById('buy-button')
(a'
is missing).then(response => return response.json())
should be.then(response => response.json())
(noreturn
keyword)
If that still doesn't fix the issue, please add some logs to your code and make sure to include the exact error messages you see.
CodePudding user response:
There is a typo error in your variable declaration
var buyButton = document.getElementById(buy-button');
It's meant to be:
var buyButton = document.getElementById('.buy-button');