How to send Stripe session checkout parameters in subscription mode

40 views Asked by At

I am quite new to stripe integration, and due to the country I am from, I cannot access the checkout session page due to account activation requirements. So, I am not able to see what all details are visible in the checkout page, and cannot debug it. (I am in test mode)

I am quite confused about how I can sent the price id of the product I select. I have created two products in my dashboard, and I am displaying then on the frontend with a pay button that calls the checkout-session endpoint.

this is my checkoutSession view

class CreateCheckoutSession(APIView):
    def post(self, request):
        if request.method == 'POST':
            

            try:

                if request.user.is_authenticated:
                    print(request.user)
                    print(request.user.id)
                    checkout_session = stripe.checkout.Session.create(
                        client_reference_id=request.user.id,
                        payment_method_types=['card'],
                        line_items=[
                            {
                                'price': "",  
                                'quantity': 1,
                            },
                        ],
                        mode='subscription',
                        success_url=os.environ['DOMAIN_URL']+'/dashboard',
                        cancel_url=os.environ['DOMAIN_URL'],
                    )
                    return Response({'sessionId': checkout_session.id})
                else:
                    return Response({'message': 'You need to register first.'}, status=403)

            except InvalidRequestError as e:
                error_message = str(e)
                return Response({'error': error_message}, status=400)

        else:
            return Response({'error': 'Method not allowed'}, status=405)

I think I should only send the price id or product id (which one am I supposed to send?) of the subscription I want to buy. I am not sure how can I do that. Could anyone please help me here? My frontend is NEXTJS and backend is django with DRF

const handleSubscription = async () => {
    try {
      const response = await AxiosInstance.post("/checkout-session", {
        
      });
      
      const sessionId = response.data.sessionId;
      const stripe = await loadStripe(
        process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
      );
      const { error } = await stripe.redirectToCheckout({
        sessionId: sessionId,
      });

      if (error) {
        console.error("Error:", error);
      }

When calling the product api, it gives me two arrays, one for each product. I need your help to understand, what are the parameters that I need to send of the product I subscribe to? and how can I sent it?

I tried implementing the stripe code implementation using stripe elements, and now switching to stripe low code, as it best suits my current use case. I cannot check if my payment is going through successfully, as I cannot make any payment from my country before account activation due to stripe policies.

1

There are 1 answers

4
Lucky2501 On

I cannot make any payment from my country before account activation due to stripe policies.

Why don't you use your test API keys? You can make test payments and Checkout sessions without an activated Stripe account.

As for the formatting of the line_items array, you have two choices:

  • Use an existing Price ID
    You've already got the code for this, just Create your Product on your Stripe account, which will have a child Price ID (it could have more than one, e.g. Product "Python course" might have a "monthly plan" Price object which bills monthly and a "annual plan" Price object).

    line_items=[
       {'price':price_id, 'quantity':1},
       {'price':price_id_2, 'quantity':2}
    ]
    

Note that with Checkout you can have one-time Prices and recurring Prices here. With mode='subscription', you will need to have at least one recurring Price naturally.

  • Build an ad-hoc Price in your Checkout Session code
    This is admittedly not as well documented, but an extremely powerful way to handle Prices without having to create them in your Stripe account (or via the API) ahead of time.

    line_items=[
       # Ad hoc recurring price
       {
          'price_data':{
                 'unit_amount':amount,
                 'currency':'usd',
                 'recurring':{'interval':'month','interval_count':1},
                 'product':prod_id
          },
          'quantity':1},
       # Ad hoc one-time price
       {
          'price_data':{
                 'unit_amount':amount,
                 'currency':'usd',
                 'product_dada':{'name':'Product name'}
          },
          'quantity':2},
    ]
    

Notice how I use product for the first Price and product_data for the second (you must use one or the other for any Price). price_data allows you to create a Product inline with the Session, the same way price_data does it for Prices.

---EDIT--- As per your comments below I don't think this answers your question, your problem is how to pass the customer selection to the backend for multiple Prices without if of case switch statements.

If I had this requirement, I'd use lookup_keys:

You could also just convert the string to the price ID on your backend via other methods such as your own dictionary, but this would be the way to do it using Stripe's infrastructure.