1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\WebhookClient; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Illuminate\Http\Request; |
7
|
|
|
use Spatie\WebhookClient\Events\InvalidSignatureEvent; |
8
|
|
|
use Spatie\WebhookClient\Exceptions\WebhookFailed; |
9
|
|
|
use Spatie\WebhookClient\Models\WebhookCall; |
10
|
|
|
|
11
|
|
|
class WebhookProcessor |
12
|
|
|
{ |
13
|
|
|
protected Request $request; |
|
|
|
|
14
|
|
|
|
15
|
|
|
protected WebhookConfig $config; |
16
|
|
|
|
17
|
|
|
public function __construct(Request $request, WebhookConfig $config) |
18
|
|
|
{ |
19
|
|
|
$this->request = $request; |
20
|
|
|
|
21
|
|
|
$this->config = $config; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function process() |
25
|
|
|
{ |
26
|
|
|
$this->ensureValidSignature(); |
27
|
|
|
|
28
|
|
|
if (! $this->config->webhookProfile->shouldProcess($this->request)) { |
29
|
|
|
return $this->createResponse(); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$webhookCall = $this->storeWebhook(); |
33
|
|
|
|
34
|
|
|
$this->processWebhook($webhookCall); |
35
|
|
|
|
36
|
|
|
return $this->createResponse(); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
protected function ensureValidSignature() |
40
|
|
|
{ |
41
|
|
|
if (! $this->config->signatureValidator->isValid($this->request, $this->config)) { |
42
|
|
|
event(new InvalidSignatureEvent($this->request)); |
43
|
|
|
|
44
|
|
|
throw WebhookFailed::invalidSignature(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return $this; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
protected function storeWebhook(): WebhookCall |
51
|
|
|
{ |
52
|
|
|
return $this->config->webhookModel::storeWebhook($this->config, $this->request); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
protected function processWebhook(WebhookCall $webhookCall): void |
56
|
|
|
{ |
57
|
|
|
try { |
58
|
|
|
$job = new $this->config->processWebhookJobClass($webhookCall); |
59
|
|
|
|
60
|
|
|
$webhookCall->clearException(); |
61
|
|
|
|
62
|
|
|
dispatch($job); |
63
|
|
|
} catch (Exception $exception) { |
64
|
|
|
$webhookCall->saveException($exception); |
65
|
|
|
|
66
|
|
|
throw $exception; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
protected function createResponse() |
71
|
|
|
{ |
72
|
|
|
return $this->config->webhookResponse->respondToValidWebhook($this->request, $this->config); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|