Stripe InvalidRequestError at /subscription/ Request req_F6PVTyTtfDXnIf: You passed an empty string for 'line_items[0][price]'. We assume empty values

I am trying to set a subscription service on my website using Django.

models.py

from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now

class Subscription(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    customer_id= models.CharField(max_length=255)
    subscription_id = models.CharField(max_length=225, unique=True)
    product_name = models.CharField(max_length=255)
    price = models.IntegerField()
    interval = models.CharField(max_length=50, default="month")
    start_date = models.DateTimeField(null=True, blank=True)
    end_date = models.DateTimeField(null=True, blank=True)
    canceled_at = models.DateTimeField(null=True, blank=True)

    @property
    def is_active(self):
        if self.end_date:
            if now() < self.enddate:
                return True
            else:
                return False
            
        else:
            return True
        
    @property
    def tier(self):
        tier_mapping = {
            'Basic Membership': 1,
            'Premium Membership':2,
            'Pro Membership':3,
        }
        tier = tier_mapping.get(self.product_name, None)
        return tier

    def __str__(self):
        return f"{self.user.username} - {self.product_name} Active: {self.is_active}"

views.py

from django.shortcuts import render, redirect, reverse

import stripe
from django.conf import settings
stripe.api_key = settings.STRIPE_SECRET_KEY

def subscription_view(request):
    subscription = {
        'Basic Membership' :'price_1RNgLNIoFyCdZSrgu83irObA',
        'premium' :'price_1RNgLvIoFyCdZSrg9j87OiP7',
        'pro' :'price_1RNgMUIoFyCdZSrgEIxgO9HP',
       
    }

    if request.method == 'POST':
        if not request.user.is_authenticated:
            return redirect(f"{reverse('account_login')}?next={request.get_full_path()}")
        
        price_id = request.POST.get('price_id')

        checkout_session = stripe.checkout.Session.create(
            
            line_items=[
                {
                    
                    'price':price_id,
                    'quantity':1,
                },
            ],
            payment_method_types=['card'],
            mode='subscription',
            success_url = request.build_absolute_uri(reverse("create_subscription")) + f'?session_id={{CHECKOUT_SESSION_ID}}',
            cancel_url=request.build_absolute_uri(f'{reverse("subscription")}'),
            customer_email=request.user.email,
            metadata={
                'user_id': request.user.id,
            }
            
        )
        return redirect(checkout_session.url, code=303)

    return render(request, 'a_subscription/subscription.html', {'subscription' : subscription})

def create_subscription(request):
   
    #create subscription object in database

    return redirect('my_sub')

def my_sub_view(request):
    return render(request, 'a_subscription/my-sub.html')

Error message:

InvalidRequestError at /subscription/ Request req_F6PVTyTtfDXnIf: You passed an empty string for 'line_items[0][price]'. We assume empty values are an attempt to unset a parameter; however 'line_items[0][price]' cannot be unset. You should remove 'line_items[0][price]' from your request or supply a non-empty value.

I had it working just before this & this suddenly started happening once I tried to incorporate create_subscription in views.

Any help would be much appreciated!

The error message is pretty helpful in this case (which is not always the case with API error messages!). It tells you that you are passing an empty string for the price_id variable when you attempt to create your checkout session.

Since this value is coming from the request arg in your subscription_view() function, you will need to investigate why you are not getting a valid price_id. It might make sense to provide a False default value and a check for it.

I have highlighted the line from your views.py file below where I think you should investigate further:

def subscription_view(request):
    subscription = {
        'Basic Membership' :'price_1RNgLNIoFyCdZSrgu83irObA',
        'premium' :'price_1RNgLvIoFyCdZSrg9j87OiP7',
        'pro' :'price_1RNgMUIoFyCdZSrgEIxgO9HP',
       
    }

    if request.method == 'POST':
        if not request.user.is_authenticated:
            return redirect(f"{reverse('account_login')}?next={request.get_full_path()}")
        
        price_id = request.POST.get('price_id')  # <- Why is this empty?
        
        # Check if you have a valid price_id before you run this next command
        checkout_session = stripe.checkout.Session.create(
            line_items=[
                {
                    
                    'price':price_id,
                    'quantity':1,
                },
            ],
            ...
        )

Once you can identify why your POST request does not have the expected price ID, you will hopefully know what you need to do to pass it back to your server code.

I figured it out! simple error on my behalf, I changed basic to Basic Membership on Stripe and views.py but not in my html file! Thank you so much!!!

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