-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathWebhooksStatusController.php
More file actions
90 lines (76 loc) · 2.83 KB
/
WebhooksStatusController.php
File metadata and controls
90 lines (76 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace StatamicRadPack\Shopify\Http\Controllers\CP;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Shopify\Clients\Graphql;
use Statamic\Http\Controllers\CP\CpController;
use Statamic\Support\Arr;
use StatamicRadPack\Shopify\Enums\WebhookTopic;
use StatamicRadPack\Shopify\Support\StoreConfig;
class WebhooksStatusController extends CpController
{
public function index(Request $request)
{
if ($request->user()->cannot('access shopify')) {
abort(403);
}
$storeHandle = $request->get('store');
try {
if ($storeHandle && StoreConfig::isMultiStore()) {
$storeConfig = StoreConfig::findByHandle($storeHandle);
$graphql = $storeConfig ? StoreConfig::makeGraphqlClient($storeConfig) : app(Graphql::class);
} else {
$graphql = app(Graphql::class);
}
$registered = $this->fetchWebhooks($graphql);
} catch (\Throwable $e) {
return response()->json(['error' => 'Could not connect to Shopify: '.$e->getMessage()], 500);
}
$expected = collect(WebhookTopic::cases())
->mapWithKeys(fn ($topic) => [$topic->value => $topic->callbackUrl()])
->all();
$webhooks = collect($registered)->map(fn ($webhook) => array_merge($webhook, [
'expected' => isset($expected[$webhook['topic']])
&& $webhook['callbackUrl'] === $expected[$webhook['topic']],
'last_received_at' => $this->getLastReceivedAt($webhook['topic'], $storeHandle),
]))->all();
return response()->json([
'webhooks' => $webhooks,
'expected' => $expected,
]);
}
private function getLastReceivedAt(string $topic, ?string $storeHandle): ?string
{
$cacheKey = $storeHandle
? "shopify::webhook_last_received::{$storeHandle}::{$topic}"
: "shopify::webhook_last_received::{$topic}";
return Cache::get($cacheKey);
}
private function fetchWebhooks(Graphql $graphql): array
{
$query = <<<'QUERY'
{
webhookSubscriptions(first: 100) {
nodes {
id
topic
endpoint {
... on WebhookHttpEndpoint {
callbackUrl
}
}
createdAt
}
}
}
QUERY;
$response = $graphql->query(['query' => $query]);
$nodes = Arr::get($response->getDecodedBody(), 'data.webhookSubscriptions.nodes', []);
return collect($nodes)->map(fn ($node) => [
'id' => $node['id'],
'topic' => $node['topic'],
'callbackUrl' => Arr::get($node, 'endpoint.callbackUrl', ''),
'createdAt' => $node['createdAt'],
])->all();
}
}