I'm trying to configure Django Stripe Subscriptions for WebApp.
I want to let Subscribed users cancel the subscription themselves.
The code below is to delete user's information from StripeAPI and Django StripeCustomer model.
Here is view.py
import stripe
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http.response import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import get_user_model
from subscriptions.models import StripeCustomer
@login_required
@csrf_exempt
def cancel_subscription(request):
if request.user.is_authenticated:
endpoint_secret = settings.STRIPE_ENDPOINT_SECRET
payload = request.body
event = None
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
session = event['data']['object']
stripe_customer = StripeCustomer.objects.get(user=request.user)
stripe.api_key = settings.STRIPE_SECRET_KEY
sub_id = stripe.Subscription.retrieve(stripe_customer.stripeSubscriptionId)
client_reference_id = session.get('client_reference_id')
user = get_user_model().objects.get(id=client_reference_id)
try:
#delete from stripeapi
stripe.Subscription.delete(sub_id)
#delete from StripeCustomer model
StripeCustomer.objects.delete(
user=user,
stripeCustomerId=stripe_customer_id,
stripeSubscriptionId=stripe_subscription_id,
)
print(user.username + ' unsubscribed.')
except Exception as e:
import traceback
traceback.print_exc()
return JsonResponse({'error': (e.args[0])}, status =403)
return render(request, 'home.html')
When I excecute the code error occuerd at
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
The error message is below
Exception Type: keyError
Exception Value: 'HTTP_STRIPE_SIGNATURE'
I don't understand why the error occurs at request.META['HTTP_STRIPE_SIGNATURE'],because other part of this view can execute this code.
I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you
I think you're mixing up a webhook handler and a regular POST request route as part of your application here. You either need one or the other, and I suspect you don't need the webhook stuff at all given what you're trying to to.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.