86423
djangoでstripeが実行されません。  
ページを開いたときに読みこずhome.htmlのボタンを押してもfetchを読み込みません。  
なぜ、プロジェクト直下のurlが読み込まれているかわかりません。  
jsのルーティングがおかしいのか見当がつかず質問させていただきました。

#### ターミナルのエラー

```

    "GET /subscription/ HTTP/1.1" 200 1496
    Not Found: /config/
    
```

Chrome拡張のNetworkを開くと以下の内容が表示されます。

```

    Page not found (404)
    Request Method: GET
    Request URL: http://127.0.0.1:8000/config/
    Using the URLconf defined in sample_app.urls, Django tried these URL patterns, in this order:
    
    admin/
    accounts/
    signup/ [name='signup']
    activate/<uidb64>/<token>/ [name='activate']
    subscription/
    The current path, config/, didn't match any of these.
    
```

プロジェクト直下のurls.pyは下記です。

#### project/urls.py

```

    from django.contrib import admin
    from django.urls import path, include
    from django.contrib.auth.decorators import login_required
    
    from django.views.generic import TemplateView
    from sample import views 
    
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('accounts/', include('django.contrib.auth.urls')),
        path('', login_required(TemplateView.as_view(template_name='registration/index.html'))),
        path("signup/", views.SignUpView.as_view(), name="signup"),
        path('activate/<uidb64>/<token>/', views.ActivateView.as_view(), name='activate'),
        path('subscription/', include('subscription.urls')),
    
```

```

    {% load static %}
    <!doctype HTML>
    <html>
        <head>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
            <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
            <script src="https://js.stripe.com/v3/"></script>  <!-- new -->
            <script src="{% static 'main.js' %}"></script> <!-- new -->
            
        </head>
        <body>
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <a class="navbar-brand" href="/">サブスク</a>
            </nav>
            <div class="container mt-4">
            {% block main %}
            <p>※{{user }}ようこそ</p>
            {% endblock %}
            
            </div>
        </body>
    </html>
    
```

#### home.html

```

    {% extends "subscription/base.html" %}
    
    {% block main %}
    <p>{{ user }}様</p>
    
    <div class="container mt-5">
        <button type="submit" class="btn btn-primary" id="submitBtn">会員</button>
        
      </div>
    {% endblock %}
    
```

#### views.py

```

    from django.shortcuts import render
    from django.views.generic import TemplateView
    
    from sample_app.settings import AUTH_USER_MODEL
    from subscription.models import Stripe_Customer
     
    User = AUTH_USER_MODEL
    
    
    from django.contrib.auth.decorators import login_required
    from django.utils.decorators import method_decorator
    
    
    from django.http.response import JsonResponse, HttpResponse  
    from django.views.decorators.csrf import csrf_exempt 
    from django.conf import settings 
    import stripe 
    
    
    @csrf_exempt
    def create_checkout_session(request):
        if request.method == 'GET':
            domain_url = 'http://localhost:8000/'
            stripe.api_key = settings.STRIPE_SECRET_KEY
            try:
                checkout_session = stripe.checkout.Session.create(
                    client_reference_id=request.user.id if request.user.is_authenticated else None,
                    success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
                    cancel_url=domain_url + 'cancel/',
                    payment_method_types=['card'],
                    mode='subscription',
                    line_items=[
                        {
                            'price': settings.STRIPE_PRICE_ID,
                            'quantity': 1,
                        }
                    ]
                )
                return JsonResponse({'sessionId': checkout_session['id']})
            except Exception as e:
                return JsonResponse({'error': str(e)})
    
    @csrf_exempt
    def stripe_config(request):
        if request.method == 'GET':
            stripe_config = {'publicKey': settings.STRIPE_PUBLISHABLE_KEY}
            return JsonResponse(stripe_config, safe=False)
    
    
    @csrf_exempt
    def stripe_webhook(request):
        stripe.api_key = settings.STRIPE_SECRET_KEY
        endpoint_secret = settings.STRIPE_ENDPOINT_SECRET
        payload = request.body
        sig_header = request.META['HTTP_STRIPE_SIGNATURE']
        event = None
    
        try:
            event = stripe.Webhook.construct_event(
                payload, sig_header, endpoint_secret
            )
        except ValueError as e:
            # Invalid payload
            return HttpResponse(status=400)
        except stripe.error.SignatureVerificationError as e:
            # Invalid signature
            return HttpResponse(status=400)
    
        # Handle the checkout.session.completed event
        if event['type'] == 'checkout.session.completed':
            session = event['data']['object']
    
            # Fetch all the required data from session
            client_reference_id = session.get('client_reference_id')
            stripe_customer_id = session.get('customer')
            stripe_subscription_id = session.get('subscription')
    
            # Get the user and create a new StripeCustomer
            user = User.objects.get(id=client_reference_id)
            Stripe_Customer.objects.create(
                user=user,
                stripeCustomerId=stripe_customer_id,
                stripeSubscriptionId=stripe_subscription_id,
            )
            print(user.username + ' just subscribed.')
    
        return HttpResponse(status=200)
    
    #--------------------------------
    
    
    
    #-------index_view-----------
    @method_decorator(login_required,name="dispatch")
    class IndexView(TemplateView):
        template_name = "subscription/home.html"
        model = Stripe_Customer
    
    
    #-------Success_view-----------
    
    class SuccessView(TemplateView):
       template_name = "subscription/success.html"
       
    #-------Cancel_view-----------
    class CancelView(TemplateView):
       template_name = "subscription/cancel.html"
    
```

#### urls.py

```

    from django.urls import path
    from . import views
    
    from django.views.generic import TemplateView
    from subscription import views 
    
    app_name ="subscription"
    
    urlpatterns = [
        path('', views.IndexView.as_view(), name='home'),
        path('config/', views.stripe_config),
        path('create-checkout-session/', views.create_checkout_session),
        path('success/', views.SuccessView.as_view(), name='success'),
        path('cancel/', views.CancelView.as_view(), name='cancel'),
    
    ]
    
```

#### static/main.js

```

    console.log("Sanity check!");
    
    // Get Stripe publishable key
    fetch("config/")
    .then((result) => { return result.json(); })
    .then((data) => {
      // Initialize Stripe.js
      const stripe = Stripe(data.publicKey);
    
      // new
      // Event handler
      let submitBtn = document.querySelector("#submitBtn");
      if (submitBtn !== null) {
        submitBtn.addEventListener("click", () => {
        // Get Checkout Session ID
        fetch("/create-checkout-session/")
          .then((result) => { return result.json(); })
          .then((data) => {
            console.log(data);
            // Redirect to Stripe Checkout
            return stripe.redirectToCheckout({sessionId: data.sessionId})
          })
          .then((res) => {
            console.log(res);
          });
        });
      }
    });
    
```

参考URL  
<https://testdriven.io/blog/django-stripe-subscriptions/>
CC BY-SA 4.0
2022-02-17T02:11:35.617
86404
2022-03-17T00:37:23.837
2022-03-17T00:37:23.837
34545
34545
question
python html django
Djangoでstripeのcheck_out_sessionが開かれない
まず、js側の`fetch`でリクエストしようとしている`"config/"`は`urls.py`に見当たりません。

`main.js`でやろうとしていることを踏まえると、リクエスト先は`/subscription/config/`が正しいように見えます。
CC BY-SA 4.0
2022-02-17T16:44:02.983
86423
2022-02-17T16:44:02.983
2784
86404
answer