1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bencoderus\Webhook\Traits; |
4
|
|
|
|
5
|
|
|
use Bencoderus\Webhook\Exceptions\WebhookException; |
6
|
|
|
use Bencoderus\Webhook\Http\Clients\HttpClient; |
7
|
|
|
use Bencoderus\Webhook\Jobs\OutgoingWebhookJob; |
8
|
|
|
use Bencoderus\Webhook\Models\WebhookLog; |
9
|
|
|
use Exception; |
10
|
|
|
use Illuminate\Support\Facades\Schema; |
11
|
|
|
|
12
|
|
|
trait SendWebhook |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Send Webhook synchronously. |
16
|
|
|
* |
17
|
|
|
* @param array $data |
18
|
|
|
* |
19
|
|
|
* @return bool |
20
|
|
|
*/ |
21
|
|
|
private function sendViaHttp(array $data): bool |
22
|
|
|
{ |
23
|
|
|
try { |
24
|
|
|
$response = (new HttpClient())->withHeaders($data['signature'])->post($data['url'], $data['payload']); |
25
|
|
|
|
26
|
|
|
$this->logWebhook($response, $data); |
27
|
|
|
|
28
|
|
|
return $response->statusCode() >= 200 && $response->statusCode() <= 205; |
29
|
|
|
} catch (Exception $exception) { |
30
|
|
|
if ($exception instanceof WebhookException) { |
31
|
|
|
return false; |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Generate a webhook log. |
38
|
|
|
* |
39
|
|
|
* @param $response |
40
|
|
|
* @param array $data |
41
|
|
|
* |
42
|
|
|
* @return void |
43
|
|
|
*/ |
44
|
|
|
private function logWebhook($response, array $data) |
45
|
|
|
{ |
46
|
|
|
if (! Schema::hasTable('webhook_logs')) { |
47
|
|
|
return; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
if (! config('webhook.log_webhook')) { |
51
|
|
|
return; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$data['response'] = $response->json(); |
55
|
|
|
$data['response_status_code'] = $response->statusCode(); |
56
|
|
|
|
57
|
|
|
if (! $webhook = WebhookLog::where('uuid', $data['webhook_id'])->first()) { |
58
|
|
|
return WebhookLog::create([ |
59
|
|
|
'uuid' => $data['webhook_id'], |
60
|
|
|
'url' => $data['url'], |
61
|
|
|
'response_status_code' => $data['response_status_code'], |
62
|
|
|
'response' => $data['response'], |
63
|
|
|
'payload' => $data['payload'], |
64
|
|
|
]); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$webhook->update([ |
68
|
|
|
'response_status_code' => $data['response_status_code'], |
69
|
|
|
'response' => $data['response'], |
70
|
|
|
'attempts' => $webhook->attempts + 1, |
71
|
|
|
]); |
72
|
|
|
|
73
|
|
|
return $webhook; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* Send using a Queue. |
78
|
|
|
* |
79
|
|
|
* @param array $data |
80
|
|
|
* |
81
|
|
|
* @return bool |
82
|
|
|
*/ |
83
|
|
|
private function sendViaQueue(array $data): bool |
84
|
|
|
{ |
85
|
|
|
OutgoingWebhookJob::dispatch($data); |
86
|
|
|
|
87
|
|
|
return true; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|