| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Controllers\GoogleSheets; |
| 4 |
|
| 5 |
use IvyForms\Services\GoogleSheets\Helpers\GoogleSheetsOAuthStateHelper; |
| 6 |
use IvyForms\Services\GoogleSheets\GoogleSheetsService; |
| 7 |
use WP_REST_Request; |
| 8 |
use WP_REST_Response; |
| 9 |
|
| 10 |
/** |
| 11 |
* Handles OAuth callback via middleware one-time exchange handoff. |
| 12 |
*/ |
| 13 |
class GoogleSheetsOAuthCallbackController |
| 14 |
{ |
| 15 |
private GoogleSheetsService $googleSheetsService; |
| 16 |
|
| 17 |
public function __construct(GoogleSheetsService $googleSheetsService) |
| 18 |
{ |
| 19 |
$this->googleSheetsService = $googleSheetsService; |
| 20 |
} |
| 21 |
|
| 22 |
public function handle(WP_REST_Request $data): WP_REST_Response |
| 23 |
{ |
| 24 |
$error = sanitize_text_field((string) $data->get_param('error')); |
| 25 |
|
| 26 |
if ($error !== '') { |
| 27 |
return $this->redirectTo($this->settingsRedirectUrl(['google_sheets_error' => '1'])); |
| 28 |
} |
| 29 |
|
| 30 |
$state = (string) $data->get_param('state'); |
| 31 |
|
| 32 |
if (!GoogleSheetsOAuthStateHelper::validateState($state)) { |
| 33 |
return $this->redirectTo($this->settingsRedirectUrl(['google_sheets_error' => '1'])); |
| 34 |
} |
| 35 |
|
| 36 |
$exchangeKey = sanitize_text_field((string) $data->get_param('exchange')); |
| 37 |
|
| 38 |
if ($exchangeKey === '') { |
| 39 |
return $this->redirectTo($this->settingsRedirectUrl(['google_sheets_error' => '1'])); |
| 40 |
} |
| 41 |
|
| 42 |
$result = $this->googleSheetsService->exchangeMiddlewareHandoff($exchangeKey); |
| 43 |
|
| 44 |
if (!$result['success']) { |
| 45 |
return $this->redirectTo($this->settingsRedirectUrl(['google_sheets_error' => '1'])); |
| 46 |
} |
| 47 |
|
| 48 |
$this->googleSheetsService->saveOAuthTokens( |
| 49 |
(string) $result['accessToken'], |
| 50 |
(string) $result['refreshToken'], |
| 51 |
(int) ($result['expiresIn'] ?? 3600), |
| 52 |
(string) ($result['email'] ?? '') |
| 53 |
); |
| 54 |
|
| 55 |
return $this->redirectTo($this->settingsRedirectUrl(['google_sheets_connected' => '1'])); |
| 56 |
} |
| 57 |
|
| 58 |
/** |
| 59 |
* @param array<string, string> $params |
| 60 |
*/ |
| 61 |
private function settingsRedirectUrl(array $params): string |
| 62 |
{ |
| 63 |
return add_query_arg($params, admin_url('admin.php?page=ivyforms-settings')) |
| 64 |
. '#/integrations/google_sheets'; |
| 65 |
} |
| 66 |
|
| 67 |
private function redirectTo(string $url): WP_REST_Response |
| 68 |
{ |
| 69 |
$response = new WP_REST_Response(null, 302); |
| 70 |
$response->header('Location', $url); |
| 71 |
|
| 72 |
return $response; |
| 73 |
} |
| 74 |
} |
| 75 |
|