def stripe_webhook(request): """Handle webhooks from stripe""" if request.method != "POST": return HttpResponseNotAllowed(["POST"]) payload = request.body sig_header = request.META.get("HTTP_STRIPE_SIGNATURE") try: if settings.STRIPE_WEBHOOK_SECRET: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET) else: event = json.loads(request.body) event_id = event["id"] event_type = event["type"] if event_type.startswith(("charge", "invoice")): event_object_id = event["data"]["object"].get("id", "") else: event_object_id = "" except (TypeError, ValueError, SyntaxError) as exception: logging.error("Stripe Webhook: Error parsing JSON: %s", exception, exc_info=sys.exc_info()) return HttpResponseBadRequest() except KeyError as exception: logging.error( "Stripe Webhook: Unexpected structure: %s in %s", exception, event, exc_info=sys.exc_info(), ) return HttpResponseBadRequest() except stripe.error.SignatureVerificationError as exception: logging.error( "Stripe Webhook: Signature Verification Error: %s", sig_header, exc_info=sys.exc_info(), ) return HttpResponseBadRequest() # If we've made it this far, then the webhook message was successfully sent! # Now it's up to us to act on it. success_msg = ("Received Stripe webhook\n" "\tfrom:\t%(address)s\n" "\tid:\t%(id)s\n" "\ttype:\t%(type)s\n" "\tdata:\t%(data)s\n") % { "address": request.META["REMOTE_ADDR"], "id": event_id, "type": event_type, "data": event, } logger.info(success_msg) if event_type == "charge.succeeded": send_charge_receipt.delay(event_object_id) elif event_type == "invoice.payment_succeeded": send_invoice_receipt.delay(event_object_id) elif event_type == "invoice.payment_failed": failed_payment.delay(event_object_id) return HttpResponse()
def form_valid(self, form): """If the form is valid, charge the token provided by the form, then send a receipt.""" token = form.cleaned_data['stripe_token'] email = form.cleaned_data['stripe_email'] amount = form.cleaned_data['stripe_amount'] charge = self.make_charge(token, amount, email) if charge is None: return self.form_invalid(form) # Send the receipt send_charge_receipt.delay(charge.id) return super(DonationFormView, self).form_valid(form)
def stripe_webhook(request): """Handle webhooks from stripe""" if request.method != "POST": return HttpResponseNotAllowed(['POST']) try: event_json = json.loads(request.body) event_id = event_json['id'] event_type = event_json['type'] if event_type.startswith(('charge', 'invoice')): event_object_id = event_json['data']['object']['id'] else: event_object_id = '' except (TypeError, ValueError, SyntaxError) as exception: logging.error('Error parsing JSON: %s', exception) return HttpResponseBadRequest() except KeyError as exception: logging.error('Unexpected dictionary structure: %s in %s', exception, event_json) return HttpResponseBadRequest() # If we've made it this far, then the webhook message was successfully sent! # Now it's up to us to act on it. success_msg = ( 'Received Stripe webhook\n' '\tfrom:\t%(address)s\n' '\tid:\t%(id)s\n' '\ttype:\t%(type)s\n' '\tdata:\t%(data)s\n' ) % { 'address': request.META['REMOTE_ADDR'], 'id': event_id, 'type': event_type, 'data': event_json } logger.info(success_msg) if event_type == 'charge.succeeded': send_charge_receipt.delay(event_object_id) elif event_type == 'invoice.payment_succeeded': send_invoice_receipt.delay(event_object_id) elif event_type == 'invoice.payment_failed': failed_payment.delay(event_object_id) return HttpResponse()
def stripe_webhook(request): """Handle webhooks from stripe""" if request.method != "POST": return HttpResponseNotAllowed(['POST']) payload = request.body sig_header = request.META.get('HTTP_STRIPE_SIGNATURE') try: if settings.STRIPE_WEBHOOK_SECRET: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET, ) else: event = json.loads(request.body) event_id = event['id'] event_type = event['type'] if event_type.startswith(('charge', 'invoice')): event_object_id = event['data']['object'].get('id', '') else: event_object_id = '' except (TypeError, ValueError, SyntaxError) as exception: logging.error( 'Stripe Webhook: Error parsing JSON: %s', exception, exc_info=sys.exc_info(), ) return HttpResponseBadRequest() except KeyError as exception: logging.error( 'Stripe Webhook: Unexpected structure: %s in %s', exception, event, exc_info=sys.exc_info(), ) return HttpResponseBadRequest() except stripe.error.SignatureVerificationError as exception: logging.error( 'Stripe Webhook: Signature Verification Error: %s', sig_header, exc_info=sys.exc_info(), ) return HttpResponseBadRequest() # If we've made it this far, then the webhook message was successfully sent! # Now it's up to us to act on it. success_msg = ( 'Received Stripe webhook\n' '\tfrom:\t%(address)s\n' '\tid:\t%(id)s\n' '\ttype:\t%(type)s\n' '\tdata:\t%(data)s\n' ) % { 'address': request.META['REMOTE_ADDR'], 'id': event_id, 'type': event_type, 'data': event } logger.info(success_msg) if event_type == 'charge.succeeded': send_charge_receipt.delay(event_object_id) elif event_type == 'invoice.payment_succeeded': send_invoice_receipt.delay(event_object_id) elif event_type == 'invoice.payment_failed': failed_payment.delay(event_object_id) return HttpResponse()