Django Stripe Integration Django.How

Author avatar wrote on 02/06/2022

1. Install

pip install stripe

2. Get Keys

1. go to https://dashboard.stripe.com/
2. developers –> “API keys”

3. Add keys to settings.py

STRIPE_PUBLISHABLE_KEY = ”
STRIPE_SECRET_KEY = ”

4. Test code

5. Pass key to view

from django.conf import settings

class HomePageView(TemplateView):    
     template_name = 'home.html'
     def get_context_data(self, **kwargs):     
          context =super().get_context_data(**kwargs)        
          context['key'] = settings.PUBLISHABLE_KEY        
          return context

 

6. Change to test code to form to act when success

7. Create template templates/payment_success.html

8. urls.py

path('charge/', views.charge, name='payment_success'), 

 

9. View
def charge(request):
    if request.method == 'POST':
        charge = stripe.Charge.create(
            amount=500,
            currency='usd',
            description='A Django charge',
            source=request.POST['stripeToken']
        )
        return render(request, 'payment_success.html')

 

Test cards

https://stripe.com/docs/testing
#cards number: 4242424242424242 cvc: any 3 digits expiry: Any future date

10. Check test logs
Checkout Docs
Subscription

https://www.ordinarycoders.com/blog/article/django-stripe-monthly-subscription