Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
WebhookRequestValidator.php
Go to the documentation of this file.
1 <?php
7 
10 
16 {
22  private $allowedTopicValues = [
23  'cases/creation',
24  'cases/rescore',
25  'cases/review',
26  'guarantees/completion',
27  'cases/test'
28  ];
29 
33  private $config;
34 
38  private $decoder;
39 
44  public function __construct(
45  Config $config,
46  DecoderInterface $decoder
47  ) {
48  $this->config = $config;
49  $this->decoder = $decoder;
50  }
51 
58  public function validate(WebhookRequest $webhookRequest)
59  {
60  $body = $webhookRequest->getBody();
61  $eventTopic = $webhookRequest->getEventTopic();
62  $hash = $webhookRequest->getHash();
63 
64  return $this->isValidTopic($eventTopic)
65  && $this->isValidBody($body)
66  && $this->isValidHash($eventTopic, $body, $hash);
67  }
68 
75  private function isValidTopic($topic)
76  {
77  return in_array($topic, $this->allowedTopicValues);
78  }
79 
86  private function isValidBody($body)
87  {
88  try {
89  $decodedBody = $this->decoder->decode($body);
90  } catch (\Exception $e) {
91  return false;
92  }
93 
94  return !empty($decodedBody);
95  }
96 
105  private function isValidHash($eventTopic, $body, $hash)
106  {
107  // In the case that this is a webhook test, the encoding ABCDE is allowed
108  $apiKey = $eventTopic == 'cases/test' ? 'ABCDE' : $this->config->getApiKey();
109  $actualHash = base64_encode(hash_hmac('sha256', $body, $apiKey, true));
110 
111  return $hash === $actualHash;
112  }
113 }
$config
Definition: fraud_order.php:17