share( Services\GoogleClient::class, static fn() => new Services\GoogleClient() ); } public function boot( Container $container ): void { add_action( 'rest_api_init', static function () use ( $container ): void { ( new Rest\GscController( $container->get( Services\GoogleClient::class ) ) )->register_routes(); } ); add_action( 'admin_post_airanksuite_gsc_callback', static function () use ( $container ): void { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You are not allowed to do this.', 'ai-rank-suite' ) ); } $client = $container->get( Services\GoogleClient::class ); $code = isset( $_GET['code'] ) ? sanitize_text_field( wp_unslash( $_GET['code'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended $state = isset( $_GET['state'] ) ? sanitize_text_field( wp_unslash( $_GET['state'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended $handoff = isset( $_GET['handoff'] ) ? sanitize_text_field( wp_unslash( $_GET['handoff'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended // Two ways back: Google itself (own credentials, ?code=) or the // vendor's connect service (Sign in with Google, ?handoff=). if ( '' !== $handoff ) { $result = $client->proxy_claim( $handoff, $state ); } else { $result = '' !== $code ? $client->handle_callback( $code, $state ) : new \WP_Error( 'airanksuite_gsc_denied', __( 'Google returned no authorization code.', 'ai-rank-suite' ) ); } if ( ! ( $result instanceof \WP_Error ) ) { // The sign-in worked; now pick the matching Search Console // property and GA4 account before the browser is back, so // the screen that loads next already shows real data. try { $client->auto_configure(); } catch ( \Throwable $e ) { unset( $e ); // Auto-pick is a convenience, never a failure. } } $anchor = $result instanceof \WP_Error ? '#/search-console?error=' . rawurlencode( $result->get_error_message() ) : '#/search-console?connected=1'; wp_safe_redirect( admin_url( 'admin.php?page=ai-rank-suite' . $anchor ) ); exit; } ); } }