| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Controllers\Square; |
| 4 |
|
| 5 |
use IvyForms\Services\Integrations\MiddlewareSignatureService; |
| 6 |
use IvyForms\Services\Payment\SquareOAuthService; |
| 7 |
use IvyForms\Services\Payment\WebhookEventDedupeStore; |
| 8 |
use IvyForms\Services\Translations\BackendStrings; |
| 9 |
use WP_REST_Request; |
| 10 |
use WP_REST_Response; |
| 11 |
|
| 12 |
/** |
| 13 |
* Public webhook endpoint — IvyForms middleware forwards signed Square revocation events here. |
| 14 |
*/ |
| 15 |
class SquareWebhookController |
| 16 |
{ |
| 17 |
private SquareOAuthService $squareOAuthService; |
| 18 |
private MiddlewareSignatureService $middlewareSignatureService; |
| 19 |
|
| 20 |
public function __construct( |
| 21 |
SquareOAuthService $squareOAuthService, |
| 22 |
MiddlewareSignatureService $middlewareSignatureService |
| 23 |
) { |
| 24 |
$this->squareOAuthService = $squareOAuthService; |
| 25 |
$this->middlewareSignatureService = $middlewareSignatureService; |
| 26 |
} |
| 27 |
|
| 28 |
public function __invoke(WP_REST_Request $data): WP_REST_Response |
| 29 |
{ |
| 30 |
return $this->handle($data); |
| 31 |
} |
| 32 |
|
| 33 |
public function handle(WP_REST_Request $data): WP_REST_Response |
| 34 |
{ |
| 35 |
$rawBody = $data->get_body(); |
| 36 |
$signature = (string) $data->get_header('X-IvyForms-Signature'); |
| 37 |
if (!$this->middlewareSignatureService->verifySignature($rawBody, $signature)) { |
| 38 |
return new WP_REST_Response( |
| 39 |
[ |
| 40 |
'message' => BackendStrings::getCommonStrings()['invalid_request_data'], |
| 41 |
'data' => ['success' => false], |
| 42 |
], |
| 43 |
403 |
| 44 |
); |
| 45 |
} |
| 46 |
|
| 47 |
$decoded = json_decode($rawBody, true); |
| 48 |
$eventId = is_array($decoded) |
| 49 |
? (string) ($decoded['event_id'] ?? $decoded['id'] ?? '') |
| 50 |
: ''; |
| 51 |
if (!WebhookEventDedupeStore::claim('square', $eventId)) { |
| 52 |
return new WP_REST_Response( |
| 53 |
[ |
| 54 |
'message' => BackendStrings::getCommonStrings()['ok'], |
| 55 |
'data' => ['success' => true], |
| 56 |
], |
| 57 |
200 |
| 58 |
); |
| 59 |
} |
| 60 |
|
| 61 |
$eventType = is_array($decoded) ? (string) ($decoded['type'] ?? '') : ''; |
| 62 |
if ($eventType !== 'oauth.authorization.revoked') { |
| 63 |
return new WP_REST_Response( |
| 64 |
[ |
| 65 |
'message' => BackendStrings::getCommonStrings()['ok'], |
| 66 |
'data' => ['success' => true, 'ignored' => true], |
| 67 |
], |
| 68 |
200 |
| 69 |
); |
| 70 |
} |
| 71 |
|
| 72 |
$this->squareOAuthService->clearSquareSettingsFromRevocationWebhook(); |
| 73 |
$this->squareOAuthService->notifyAdminDisconnected(); |
| 74 |
|
| 75 |
return new WP_REST_Response( |
| 76 |
[ |
| 77 |
'message' => BackendStrings::getCommonStrings()['ok'], |
| 78 |
'data' => ['success' => true], |
| 79 |
], |
| 80 |
200 |
| 81 |
); |
| 82 |
} |
| 83 |
} |
| 84 |
|