Webhook.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace Stripe;
  3. abstract class Webhook
  4. {
  5. const DEFAULT_TOLERANCE = 300;
  6. /**
  7. * Returns an Event instance using the provided JSON payload. Throws an
  8. * Exception\UnexpectedValueException if the payload is not valid JSON, and
  9. * an Exception\SignatureVerificationException if the signature
  10. * verification fails for any reason.
  11. *
  12. * @param string $payload the payload sent by Stripe
  13. * @param string $sigHeader the contents of the signature header sent by
  14. * Stripe
  15. * @param string $secret secret used to generate the signature
  16. * @param int $tolerance maximum difference allowed between the header's
  17. * timestamp and the current time
  18. *
  19. * @throws Exception\UnexpectedValueException if the payload is not valid JSON,
  20. * @throws Exception\SignatureVerificationException if the verification fails
  21. *
  22. * @return Event the Event instance
  23. */
  24. public static function constructEvent($payload, $sigHeader, $secret, $tolerance = self::DEFAULT_TOLERANCE)
  25. {
  26. WebhookSignature::verifyHeader($payload, $sigHeader, $secret, $tolerance);
  27. $data = \json_decode($payload, true);
  28. $jsonError = \json_last_error();
  29. if (null === $data && \JSON_ERROR_NONE !== $jsonError) {
  30. $msg = "Invalid payload: {$payload} "
  31. . "(json_last_error() was {$jsonError})";
  32. throw new Exception\UnexpectedValueException($msg);
  33. }
  34. return Event::constructFrom($data);
  35. }
  36. }