admin_url( 'admin-ajax.php' ), 'action' => self::ACTION, 'working' => __( 'Checking…', 'maple-parcel' ), 'failed' => __( 'The check could not finish. Reload the page and try again.', 'maple-parcel' ), ) ); } public function handle(): void { check_ajax_referer( self::ACTION, 'nonce' ); if ( ! current_user_can( 'manage_woocommerce' ) ) { wp_send_json_error( array( 'message' => __( 'You are not allowed to do that.', 'maple-parcel' ) ), 403 ); } $result = $this->run( Settings::load() ); if ( $result['ok'] ) { wp_send_json_success( array( 'message' => $result['message'] ) ); } wp_send_json_error( array( 'message' => $result['message'] ) ); } /** * @return array{ok: bool, message: string} */ public function run( Settings $settings ): array { $credentials = $settings->credentials(); if ( $settings->secretUnreadable() ) { return self::fail( __( 'The saved secret can no longer be read on this site. Enter it again and save.', 'maple-parcel' ) ); } if ( ! $credentials->isComplete() ) { return self::fail( __( 'Save the key and secret for the chosen environment first.', 'maple-parcel' ) ); } $origin = $settings->originPostalCode(); if ( '' === $origin ) { return self::fail( __( 'Save the ship-from postal code first.', 'maple-parcel' ) ); } $logger = new Logger( $settings->debug() ); $tokens = new TokenProvider( $credentials, $logger ); try { $tokens->refresh(); } catch ( ApiException $e ) { /* translators: %s: what Canada Post said. */ return self::fail( sprintf( __( 'Signing in failed: %s', 'maple-parcel' ), $e->getMessage() ) ); } $rater = new Rater( new RatingClient( new Client( $tokens, $logger, $settings->language() ) ), new RateCache( 0, '' ), $settings ); $destination = Destination::fromPackage( array( 'country' => 'CA', 'postcode' => $origin, ) ); if ( null === $destination ) { return self::fail( __( 'The saved ship-from postal code is not valid.', 'maple-parcel' ) ); } try { $quotes = $rater->rate( $destination, array( new Parcel( 1.0, 20.0, 15.0, 10.0 ) ), array() ); } catch ( ApiException $e ) { /* translators: %s: what Canada Post said. */ return self::fail( sprintf( __( 'Signed in, but the sample rate failed: %s', 'maple-parcel' ), $e->getMessage() ) ); } Health::recordSuccess(); $environment = 'production' === $credentials->environment ? __( 'Production', 'maple-parcel' ) : __( 'Test', 'maple-parcel' ); return array( 'ok' => true, 'message' => sprintf( /* translators: 1: Test or Production, 2: number of services. */ _n( 'Connected to the %1$s app. A sample 1 kg parcel got %2$d price.', 'Connected to the %1$s app. A sample 1 kg parcel got %2$d prices.', count( $quotes ), 'maple-parcel' ), $environment, count( $quotes ) ), ); } /** @return array{ok: false, message: string} */ private static function fail( string $message ): array { return array( 'ok' => false, 'message' => wp_strip_all_tags( $message ), ); } }