* @since x.x.x */ namespace AdvancedAds\License; use AdvancedAds\Framework\Interfaces\Integration_Interface; use AdvancedAds\Framework\Utilities\Params; use AdvancedAds\Utilities\Conditional; defined( 'ABSPATH' ) || exit; /** * Trades the one-time shop token for license rows and stores them. */ class Exchange_Handler implements Integration_Interface { /** * Admin-post action the shop redirects to. * * @var string */ public const ACTION = 'advanced-ads-license'; /** * Register WordPress hooks. * * @return void */ public function hooks(): void { add_action( 'admin_post_' . self::ACTION, [ $this, 'handle' ] ); } /** * Entry point: check access, verify nonce, exchange, save, redirect. * * @return void */ public function handle(): void { if ( ! Conditional::user_can( 'advanced_ads_manage_options' ) ) { wp_die( esc_html__( 'Forbidden.', 'advanced-ads' ), '', [ 'response' => 403 ] ); } if ( ! $this->has_valid_nonce() ) { $this->redirect( [ 'advads_exchange_error' => 'invalid_token' ] ); } $token = sanitize_text_field( (string) Params::request( 'token', '' ) ); if ( '' === $token ) { $this->redirect( [ 'advads_exchange_error' => 'invalid_token' ] ); } $rows = Shop_Client::exchange( [ 'site' => License::get_instance()->site_hostname(), 'token' => $token, ] ); if ( is_wp_error( $rows ) ) { $this->redirect( [ 'advads_exchange_error' => $rows->get_error_code() ] ); } License::get_instance()->connect( $rows ); // The shop sends `checkout_intent` back after a checkout; a plain sign-in sends none. $intent = sanitize_key( (string) Params::request( 'checkout_intent', '' ) ); $this->redirect( [ 'advads_connected' => in_array( $intent, [ 'buy', 'renew', 'upgrade' ], true ) ? $intent : 'connect' ] ); } /** * Whether the shop sent back the nonce we put on the outgoing link (CSRF guard). * * @return bool */ private function has_valid_nonce(): bool { return (bool) wp_verify_nonce( sanitize_text_field( (string) Params::request( '_wpnonce', '' ) ), self::ACTION ); } /** * Redirect to the License screen and exit. * * @param array $args Query args, e.g. an error code. * @return void */ private function redirect( array $args = [] ): void { wp_safe_redirect( add_query_arg( $args, admin_url( 'admin.php?page=advanced-ads-app&path=/license' ) ) ); exit; } }