'KeyError at /webhook/ 'HTTP_STRIPE_SIGNATURE'
Following is my code for webhook with a Django application
@csrf_exempt
def webhook(request):
webhook_secret = STRIPE_WEBHOOK_SECRET
payload = request.body.decode('utf-8')
signature = request.META["HTTP_STRIPE_SIGNATURE"]
try:
event = stripe.Webhook.construct_event(
payload=payload, sig_header=signature, secret=webhook_secret)
data = event['data']
except Exception as e:
return e
event_type = event['type']
data_object = data['object']
if event_type == 'invoice.paid':
webhook_object = data["object"]
stripe_customer_id = webhook_object["customer"]
stripe_sub = stripe.Subscription.retrieve(webhook_object["subscription"])
stripe_price_id = stripe_sub["plan"]["id"]
current_period_end = stripe_sub["current_period_end"]
current_period_end = datetime.datetime.fromtimestamp(current_period_end, tz=None)
pricing = Pricing.objects.get(stripe_price_id=stripe_price_id)
user = User.objects.get(stripe_customer_id=stripe_customer_id)
subscription = Subscription.objects.get(user=user)
subscription.status = stripe_sub["status"]
subscription.stripe_subscription_id = webhook_object["subscription"]
subscription.pricing = pricing
subscription.current_period_end = current_period_end
subscription.save()
if event_type == 'customer.subscription.deleted':
webhook_object = data["object"]
stripe_customer_id = webhook_object["customer"]
stripe_sub = stripe.Subscription.retrieve(webhook_object["id"])
user = User.objects.get(stripe_customer_id=stripe_customer_id)
subscription = Subscription.objects.get(user=user)
subscription.status = stripe_sub["status"]
subscription.save()
return HttpResponse()
and the url is
path('webhook/', webhook, name='webhook')
if I check the path https://example.com/webhook/, I am getting the error
Exception Type: KeyError at /webhook/
Exception Value: 'HTTP_STRIPE_SIGNATURE'
and in strpe account I am getting 500 error
Solution 1:[1]
It takes the POST request, whenever you hit the URL then it will show you this error because of the GET request.
run these commands:
$ stripe login
$ stripe listen --forward-to localhost:8000/webhook
you can follow this said by stripe itself.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
