Почему тестирование Stripe CLI не работает с dj-stripe?
Я пытаюсь проверить, что URL работают для DJ Stripe с помощью Stripe CLI. Первоначально я собирался реализовать представление самостоятельно, но потом решил использовать DJ Stripe. В моем первоначальном представлении CLI работает, просто прослушивая мой URL и запуская stripe trigger checkout.session.completed
:
✗ stripe listen --forward-to localhost:80/webhook/subscriptions
/
⡿ Checking for new versions... A newer version of the Stripe CLI is available, please update to: v1.7.4
⢿ Getting ready... > Ready! Your webhook signing secret is whsec_flxws0UD9fzx16CMB5krTZdzy5LI63SE (^C to quit)
2021-10-11 14:29:56 --> payment_intent.created [evt_3JjUC8KxszORsacj0V7a7Kll]
2021-10-11 14:29:56 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_3JjUC8KxszORsacj0V7a7Kll]
2021-10-11 14:29:59 --> customer.created [evt_1JjUCBKxszORsacjAxsANDCu]
2021-10-11 14:29:59 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_1JjUCBKxszORsacjAxsANDCu]
2021-10-11 14:29:59 --> payment_intent.succeeded [evt_3JjUC8KxszORsacj0ZPYDcwj]
2021-10-11 14:29:59 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_3JjUC8KxszORsacj0ZPYDcwj]
2021-10-11 14:29:59 --> charge.succeeded [evt_3JjUC8KxszORsacj001d3jMs]
2021-10-11 14:30:00 --> checkout.session.completed [evt_1JjUCBKxszORsacjedLR1580]
2021-10-11 14:30:00 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_3JjUC8KxszORsacj001d3jMs]
2021-10-11 14:30:00 <-- [200] POST http://localhost:80/webhook/subscriptions/ [evt_1JjUCBKxszORsacjedLR1580]
Мой рабочий код, не относящийся к j-stripe, выглядит следующим образом:
@csrf_exempt
def stripe_subscription_webhook_received(request):
stripe.api_key = cmu.get_stripe_api_key()
webhook_secret = request.headers['STRIPE_SIGNATURE']
payload = json.loads(request.body)
try:
event = stripe.Event.construct_from(payload, stripe.api_key)
except ValueError as e:
return HttpResponse(status=400)
if event.type == 'checkout.session.completed':
payment_intent = event.data.object
print(payment_intent)
elif event.type == 'invoice.paid':
# bunch of events...
# ...
else:
print(f"Unhandled Stripe event type: {event.type}")
cmu.email_self_about_stripe_webhook(event)
return HttpResponse(status=200)
Однако, при попытке использовать URL DJ Stripe я получаю 400 ошибок:
✗ stripe listen --forward-to localhost:80/stripe/my_product_webhook/
⡿ Checking for new versions... A newer version of the Stripe CLI is available, please update to: v1.7.4
⣻ Getting ready... > Ready! Your webhook signing secret is whsec_flxws0UD9fzx16CMB5krTZdzy5LI63SE (^C to quit)
2021-10-11 14:37:16 --> payment_intent.created [evt_3JjUJDKxszORsacj1newBYzm]
2021-10-11 14:37:16 <-- [400] POST http://localhost:80/stripe/my_product_webhook/ [evt_3JjUJDKxszORsacj1newBYzm]
2021-10-11 14:37:21 --> customer.created [evt_1JjUJIKxszORsacjp6CsOLt1]
2021-10-11 14:37:21 <-- [400] POST http://localhost:80/stripe/my_product_webhook/ [evt_1JjUJIKxszORsacjp6CsOLt1]
2021-10-11 14:37:21 --> payment_intent.succeeded [evt_3JjUJDKxszORsacj1swQx4Mu]
2021-10-11 14:37:21 --> charge.succeeded [evt_3JjUJDKxszORsacj13CHPHjY]
2021-10-11 14:37:21 <-- [400] POST http://localhost:80/stripe/my_product_webhook/ [evt_3JjUJDKxszORsacj1swQx4Mu]
2021-10-11 14:37:21 <-- [400] POST http://localhost:80/stripe/my_product_webhook/ [evt_3JjUJDKxszORsacj13CHPHjY]
2021-10-11 14:37:21 --> checkout.session.completed [evt_1JjUJJKxszORsacjrFkPSeX2]
2021-10-11 14:37:21 <-- [400] POST http://localhost:80/stripe/my_product_webhook/ [evt_1JjUJJKxszORsacjrFkPSeX2]
Глядя на исходный код dj-stripe views.py, кажется, что это может быть сделано специально, чтобы возвращать 400 ошибок, учитывая return HttpResponseBadRequest()
.
@method_decorator(csrf_exempt, name="dispatch")
class ProcessWebhookView(View):
"""
A Stripe Webhook handler view.
This will create a WebhookEventTrigger instance, verify it,
then attempt to process it.
If the webhook cannot be verified, returns HTTP 400.
If an exception happens during processing, returns HTTP 500.
"""
def post(self, request):
if "HTTP_STRIPE_SIGNATURE" not in request.META:
# Do not even attempt to process/store the event if there is
# no signature in the headers so we avoid overfilling the db.
return HttpResponseBadRequest()
trigger = WebhookEventTrigger.from_request(request)
if trigger.is_test_event:
# Since we don't do signature verification, we have to skip trigger.valid
return HttpResponse("Test webhook successfully received!")
if not trigger.valid:
# Webhook Event did not validate, return 400
return HttpResponseBadRequest()
return HttpResponse(str(trigger.id))
Моя цель - перейти от собственной реализации webhook к использованию встроенных webhook и триггеров в dj-stripe. Но прежде чем начать этот переход, я хотел бы убедиться, что конечная точка webhook действительно работает. Я что-то упускаю, как заставить Stripe CLI работать с URL-адресами dj-stripe? В моем settings.py у меня есть DJSTRIPE_WEBHOOK_URL = "my_product_webhook/"
только для того, чтобы сделать URL более явным. Одна вещь, которая меня беспокоит, это то, что мой URL при просмотре вывода DEBUG, кажется, имеет пробел в нем: stripe/ my_product_webhook/ [name='webhook']
. Поскольку я следую документации по установке dj-stripe, я не понимаю, почему в этом URL должен быть пробел после добавления path("stripe/", include("djstripe.urls", namespace="djstripe")),
в мой urls.py.