Stripe payment Integration in Django
February 4, 2025 No Comments

Introduction

This documentation provides a comprehensive guide for implementing Stripe subscription-based payments in a Django application, with an important emphasis on building everything with the help of AI and providing detailed prompts. Whether you’re building a SaaS platform, membership site, or any subscription-based service, this integration will enable you to:

  • Process recurring payments securely
  • Manage customer subscriptions
  • Handle payment lifecycle events
  • Track subscription status
  • Automate billing processes

What You'll Need

Cursor AI installed (download it from https://cursor.sh/

  • Linux or Mac
    • The downloaded file should be with the extension AppImage you need to give execution permission to this file to run
				
					chmod +x ./cursor-0.40.4-build-2409052yfcjagw2-x86_64.AppImage
				
			
    • Now execute this file by:
				
					./cursor-0.40.4-build-2409052yfcjagw2-x86_64.AppImage
				
			

This execution opens the cursor editor.

  • Python installed on your computer (download it from https://www.python.org/)
  • Understanding the Stripe API and Payment Method.

How to Use Cursor AI

Throughout this guide, we’ll be using Cursor AI to help us write code and understand concepts. Here’s how to use it:

1. Open your project in Cursor.

2. When you need help, press Ctrl+K (Cmd+K on Mac) to open the AI prompt.

3. Type your question or request, then press Enter.

4. Cursor AI will provide a response. You can then choose to insert the suggested code or ask for more information.

Using the Chat Interface

To start a chat with Cursor AI:

1. Click on the chat icon in the left sidebar or press Ctrl+Shift+L (Cmd+Shift+L on Mac).

2. Type your question or request in the chat box.

3. You can have a back-and-forth conversation with the AI, asking follow-up questions or requesting clarifications.

Tagging Files

To reference specific files in your chat:

1. In your question, use the @ symbol followed by the filename.

2. For example: “Can you explain the models in @blog/models.py?”

Note: Cursor may take time or require a little more effort to understand the context and may not give exactly the results we expected in one go.

Task Context

After countless experiments, we finally learned how to effectively provide task context to cursors.

1. Now, let’s explain the context to Cursor more efficiently by just tagging all the files that might be affected in the process, or let Cursor explore the whole codebase—something we don’t recommend.

2. Now, let’s explain the context of the task we want to perform. If you have any documentation related to the task, then provide it and let the Cursor explore the code and help create the task plan.

Example: As you now understand the context of the code, we are trying to implement Stripe payment with subscription functionality. Here are some documents that might help you get more context on the task. 

@https://docs.stripe.com/api/subscriptions/create 

@https://docs.stripe.com/metadata/use-cases 

Can you please explore this and give me a plan that we can implement? That would be nice.

Note: Cursor may take time or require a little more effort to understand the context and may not give exactly the results we expected in one go.

Stripe Webhook integration

Now that we are integrating the Stripe payment subscription, we will require the webhook secret, client_secret, API key, product_id, and price_id. All of these can be obtained from the Stripe dashboard.

Let’s ask the cursor if he can help us with integration. We’ll design this prompt so the cursor can get some hints and a general idea of the task for more efficient results.

Prompt:
				
					We are integrating Stripe for a subscription-based service. Please provide guidance on obtaining and managing the following critical Stripe configuration details:

1. Webhook Secret
2. Client Secret
3. API Key
4. Product ID
5. Price ID

Could you walk me through:
- Where exactly to find these in the Stripe Dashboard
- Any specific steps or sections I need to navigate
- Any best practices for securely managing these credentials
- Potential pitfalls to avoid during the integration process

				
			
Output:

There is so much that the cursor returns for guidance, but these are the few main highlights that are most useful.

Implement stripe subscription

Now that the cursor understands our task and has all the necessary context and values required, let’s implement the subscription. 

I have created two products on Stripe: one is a Gold Plan and the other is a Silver Plan. Both are subscription-based products. It’s very straightforward – on the left menu, you’ll find the option to create the product: Stripe Dashboard > Left Side Menu > Product Catalog > Create Product

Now that we have all the necessary required things we can start the actual webhook integration.

Prompt
				
					Now that we have all the necessary requirements, we can start the actual webhook integration. We need to add the webhook to the Stripe dashboard to complete the process. Let's start from there.
				
			
Output

Stipe UI Integration

Note: Building the UI may take longer than we expect. If you have any UI layouts to provide, this may help, but it does require more effort than the backend. You may not get the desired result in one go.

As you can see, Stripe has updated the code that can handle Stripe events and provided the webhook that we need to add to the Stripe dashboard. Once we add this to the dashboard, we will need to work on the UI to implement the Stripe payment button.

Prompt
				
					Now that we have updated the codebase for Stripe integration, we have to add the payment button as well. You can explore the file 'processing_payment_request.html' and add the payment method there.
				
			
Output

If everything goes smoothly, then after clicking on the pay button, you will be redirected to the payment page. If not, try to search through the documentation and provide related resources like this blog with your prompt. This will help the cursor to understand better: https://learndjango.com/tutorials/django-stripe-tutorial

Price_id and Product_id Integration and Payment Session Creation.

Now that we have integrated the button and UI page, we should start working on the backend for price integration. Now then we have to add a make section where we should enter price_id and product_id.

Prompt
				
					Hey, I want to add a Stripe payment system here, and for that, we need the price_id and product_id. If you could provide an option to add those as well, that would be great.

				
			
Output

Here, it updates the codebase and also provides other important notes that might help us improve our system. If you would like to implement any of the suggestions, simply copy and paste that line. No additional changes are needed. 

After you provide any suggestion as input, Cursor works accordingly and provides results as shown below.

As you can see, the cursor updates the admin file and the model file to store the product_id and price_id.

This is not our first time trying to add the product_id and price_id; it took us multiple tries to accomplish this. If you encounter any error, simply copy it and provide it to the Cursor along with an explanation of what you were doing and how this error might have been triggered. If the error persists, search for it and provide reference documentation to the Cursor.

Note: Ask the cursor to explore the codebase after each task to keep the codebase context fresh. 

Now that we have added the price_id and product_id, we should record the payment status and other payment-related details for later use. First, let’s ask Cursor if he has already added all of this or not.

Prompt
				
					Can you please explore the codebase and check if we are storing the transaction data in the database? If we are not storing it, then we should implement storage for all transaction data.
				
			

According to our prompt cursor check of the code that stores the transaction details, we found that there is no code for storing the transaction data. After I ran the code, I received a few errors, and I provided the feedback to cursor like this:

Prompt
				
					I received this error. Could you check it and identify any other potential errors? The error was related to 'conversation_credit': ``` 
 Decimal('3000.00'), 'daily_credit_limit': Decimal('500.00'), 'openai_models': <QuerySet [<IncludedModelsInProducts: Silver Plan - gpt-4o-mini>]>, 'disabled': False}]
[06/Nov/2024 12:25:02] "GET /user/profile/generation/?payment_success=true HTTP/1.1" 200 34006
Creating checkout session for a product: Gold Plan (UUID: b6739083-85a6-4b97-8181-3048d1e20092)
Stripe session creation error: Request req_0OeHQwpi4d3rnH: Received unknown parameter: product_data[description]
Bad Request: /payments/create-checkout-session/
[06/Nov/2024 12:25:05] "POST /payments/create-checkout-session/ HTTP/1.1" 400 96
```

				
			

According to this prompt, Cursor should try to identify other potential errors and resolve them as well.  

We have completed most of the tasks so far. Now we need to create the payment sessions. Regarding the create session code, the cursor might already be implemented. We should check with him first and then ask them to create one if needed.

Prompt
				
					Can you please check if we have created the payment session code or not? If not, could you help me with that?
				
			

Testing

Now that we have created all the required components, it’s time to test them. You can ask, “How should we test all these things?”

key.py is the file where I store all the keys and secrets.

Prompt
				
					It seems we have implemented everything. Now, we should test all of this. Could you help me figure out how to do that? Also, please explore the key.py file for more information.
				
			

We should follow these steps to complete the testing. If anything goes wrong, have Cursor directly copy the error, as we did before. Then, explain the scenario and let Cursor figure out what is going wrong.

If everything goes smoothly then we should get the success message and success event on stripe dashboard.

Conclusion

We have successfully demonstrated how to implement Stripe subscription integration in a Django application using Cursor AI as our development assistant.

A key takeaway from this process is that while Cursor AI significantly accelerates development, success depends on providing clear context, proper documentation, and iterative refinement of prompts. When errors occur, sharing specific error messages and context with Cursor AI leads to more effective problem-solving.

Write a comment

Your email address will not be published. Required fields are marked *