I want to give access to certain pages on the website only to registered users who have paid a membership fee through Stripe. I already have view that creates the User and decorators in front of the restricted views.
How can the Member be created and the Stripe ids added to his profile only after Stripe has successfully accepted the payment and redirected him to the 'success' page?
Views.py:
# views.py
@unauthenticated_user
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
email = form.cleaned_data.get('email')
group = Group.objects.get(name='Member')
user.groups.add(group)
Member.objects.create(user=user, name=username, first_name=first_name, last_name=last_name, email=email)
messages.success(request, 'Account was created for ' + username)
return redirect('login_page')
content = {'form':form }
return render(request,'spacs_money_app/register.html', content)
#views.py
@csrf_exempt
def create_checkout_session(request):
if request.method == 'GET':
domain_url = 'http://localhost:8000/'
stripe.api_key = settings.STRIPE_TEST_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_MONTHLY_PRICE_ID,
'quantity': 1,
}
]
)
return JsonResponse({'sessionId': checkout_session['id']})
except Exception as e:
return JsonResponse({'error': str(e)})
Models.py:
# models.py
class Member(models.Model):
user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
stripe_id = models.CharField(max_length=200, null=True)
first_name = models.CharField(max_length=200, null=True)
last_name = models.CharField(max_length=200, null=True)
email = models.EmailField()
profile_pic = models.ImageField(default="blank-profile-picture-973460_640.png", null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)