PluginProbe
ووسلام – همگام سازی ووکامرس و باسلام / 1.10.18
ووسلام – همگام سازی ووکامرس و باسلام v1.10.18
1.10.18 1.10.17 1.10.15 1.10.14 1.10.13 1.10.12 1.10.10 1.10.9 1.10.8 1.10.7 1.10.6 1.10.5 1.10.4 1.10.3 1.10.2 1.10.1 1.10.0 1.9.2 1.9.1 1.9.0 1.8.8 1.8.5 1.8.6 1.8.7 1.8.4 All 51 releases
sync-basalam / includes / Services / WebhookService.php

WebhookService.php in ووسلام – همگام سازی ووکامرس و باسلام 1.10.18, at includes/Services/WebhookService.php

183 lines 6.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace SyncBasalam\Services;
4
5 use SyncBasalam\Admin\Settings\SettingsConfig;
6 use SyncBasalam\Admin\Settings;
7 use SyncBasalam\Config\Endpoints;
8 use SyncBasalam\Logger\Logger;
9
10 defined('ABSPATH') || exit;
11 class WebhookService
12 {
13 private $apiService;
14 private $basalamToken;
15 private $webhookToken;
16
17
18 public const TARGET_EVENT_IDS = [3, 5, 7];
19
20 public function __construct()
21 {
22 $this->apiService = syncBasalamContainer()->get(ApiServiceManager::class);
23 $this->basalamToken = Settings::getSettings(SettingsConfig::TOKEN);
24 $this->webhookToken = Settings::getSettings(SettingsConfig::WEBHOOK_HEADER_TOKEN);
25
26 if (!$this->webhookToken) {
27 $newToken = Settings::generateToken();
28 Settings::updateSettings([SettingsConfig::WEBHOOK_HEADER_TOKEN => $newToken]);
29 $this->webhookToken = $newToken;
30 }
31 }
32
33 public function setupWebhook()
34 {
35 if (!$this->canCreateWebhook()) return false;
36
37 try {
38 $existingWebhooks = $this->fetchWebhooks();
39 if (!$existingWebhooks) return false;
40
41 $existingWebhooks = json_decode($existingWebhooks, true);
42 if (!is_array($existingWebhooks) || !isset($existingWebhooks['data']) || !is_array($existingWebhooks['data'])) {
43 Logger::error('پاسخ نا�
44 عتبر از API وبهوک دریافت شد.');
45 return false;
46 }
47
48 $webhookUrl = get_site_url() . "/wp-json/sync-basalam/v1/order-manager";
49
50 $correctWebhook = null;
51 $webhooksMarkedForDeletion = [];
52
53 foreach ($existingWebhooks['data'] as $webhook) {
54 if (isset($webhook['events']) && is_array($webhook['events'])) {
55 $webhookEventIds = [];
56 foreach ($webhook['events'] as $event) {
57 if (isset($event['id'])) {
58 $webhookEventIds[] = $event['id'];
59 }
60 }
61
62 $hasTargetEvents = !empty(array_intersect($webhookEventIds, self::TARGET_EVENT_IDS));
63
64 if ($hasTargetEvents) {
65 $hasAllEvents = count(array_intersect($webhookEventIds, self::TARGET_EVENT_IDS)) == count(self::TARGET_EVENT_IDS);
66
67 if ($hasAllEvents) $correctWebhook = $webhook['id'];
68 else $webhooksMarkedForDeletion[] = $webhook['id'];
69 }
70 }
71 }
72
73 foreach (array_unique($webhooksMarkedForDeletion) as $webhookId) {
74 $this->removeCurrentWebhook($webhookId);
75 }
76
77 if ($correctWebhook) return $this->updateCurrentWebhook($correctWebhook, self::TARGET_EVENT_IDS, $webhookUrl);
78
79 return $this->createNewWebhook(self::TARGET_EVENT_IDS, $webhookUrl);
80 } catch (\Exception $e) {
81 Logger::error('خطا در تنظی�
82 وبهوک: ' . $e->getMessage());
83 return false;
84 }
85 }
86
87 private function fetchWebhooks()
88 {
89 $header = ['Authorization' => 'Bearer ' . $this->basalamToken];
90
91 try {
92 $response = $this->apiService->get(Endpoints::WEBHOOKS, $header);
93 } catch (\Exception $e) {
94 Logger::error('خطا در دریافت لیست وبهوک‌ها: ' . $e->getMessage());
95 return null;
96 }
97
98 if ($response && $response['status_code'] == 200) return $response['body'];
99
100 return null;
101 }
102
103 private function createNewWebhook($eventIds, $webhookUrl)
104 {
105 $header = ['Authorization' => 'Bearer ' . $this->basalamToken];
106
107 $data = [
108 'event_ids' => array_values($eventIds),
109 'request_headers' => json_encode(['token' => $this->webhookToken]),
110 'request_method' => 'POST',
111 'url' => $webhookUrl,
112 'is_active' => true,
113 'register_me' => true,
114 ];
115
116 try {
117 $response = $this->apiService->post(Endpoints::WEBHOOKS, $data, $header);
118 } catch (\Exception $e) {
119 Logger::error('خطا در ساخت وبهوک جدید: ' . $e->getMessage());
120 return false;
121 }
122
123 if ($response && $response['status_code'] == 200) return true;
124 else return false;
125 }
126
127 private function updateCurrentWebhook($webhookId, $eventIds, $webhookUrl)
128 {
129 $header = ['Authorization' => 'Bearer ' . $this->basalamToken];
130
131 $data = [
132 'event_ids' => array_values($eventIds),
133 'request_headers' => json_encode(['token' => $this->webhookToken]),
134 'request_method' => 'POST',
135 'url' => $webhookUrl,
136 'is_active' => true,
137 ];
138
139 $updateWebhookUrl = Endpoints::WEBHOOKS . '/' . $webhookId;
140
141 try {
142 $response = $this->apiService->patch($updateWebhookUrl, $data, $header);
143 } catch (\Exception $e) {
144 Logger::error('خطا در بروزرسانی وبهوک: ' . $e->getMessage());
145 return false;
146 }
147
148 if ($response && $response['status_code'] == 200) return true;
149 else return false;
150 }
151
152 private function removeCurrentWebhook($webhookId)
153 {
154 $deleteWebhookUrl = Endpoints::WEBHOOKS . '/' . $webhookId;
155 $header = ['Authorization' => 'Bearer ' . $this->basalamToken];
156
157 try {
158 $response = $this->apiService->delete($deleteWebhookUrl, $header);
159 } catch (\Exception $e) {
160 Logger::error('خطا در حذف وبهوک: ' . $e->getMessage());
161 return false;
162 }
163
164 if ($response && ($response['status_code'] == 200 || $response['status_code'] == 204)) return true;
165 else return false;
166 }
167
168 private function canCreateWebhook(): bool
169 {
170 $siteUrl = get_site_url();
171
172 if (str_contains($siteUrl, 'localhost')) {
173 Logger::error("وبهوک برای �
174 حیط لوکال تنظی�
175 ن�
176 ی‌شود.");
177 return false;
178 }
179
180 return true;
181 }
182 }
183