\WP_REST_Server::CREATABLE, 'callback' => array( self::class, 'connect' ), 'permission_callback' => array( self::class, 'can_manage' ), 'args' => array( 'code' => array( 'type' => 'string', 'required' => true, ), 'code_verifier' => array( 'type' => 'string', 'required' => true, ), 'shop_data' => array( 'type' => 'boolean', 'default' => false, ), ), ) ); register_rest_route( self::NAMESPACE, '/status', array( 'methods' => \WP_REST_Server::READABLE, 'callback' => array( self::class, 'status' ), 'permission_callback' => array( self::class, 'can_manage' ), ) ); } /** * Only administrators. */ public static function can_manage(): bool { return current_user_can( 'manage_options' ); } /** * Connect with a one time code from the console. * * @param \WP_REST_Request $request Request. */ public static function connect( \WP_REST_Request $request ): \WP_REST_Response { $code = (string) $request->get_param( 'code' ); $verifier = (string) $request->get_param( 'code_verifier' ); if ( ! Connection::well_formed( $code ) || ! Connection::well_formed( $verifier ) ) { return new \WP_REST_Response( array( 'result' => 'invalid' ), 400 ); } if ( '' !== Connection::blocker() ) { return new \WP_REST_Response( array( 'result' => Connection::blocker() ), 409 ); } $result = Connection::exchange( $code, $verifier ); if ( 'connected' !== $result ) { return new \WP_REST_Response( array( 'result' => $result ), 'unreachable' === $result ? 502 : 400 ); } $shop = null; if ( (bool) $request->get_param( 'shop_data' ) && WooCommerce::available() ) { Store::save_settings( array( 'shop_data' => true ) ); $shop = WooCommerce::share(); } return new \WP_REST_Response( array_merge( self::state(), array( 'result' => 'connected', 'shop' => $shop ) ), 200 ); } /** * State for the console. */ public static function status(): \WP_REST_Response { return new \WP_REST_Response( self::state(), 200 ); } /** * Current state. Contains no secrets. * * @return array */ private static function state(): array { $settings = Store::settings(); return array( 'plugin_version' => FAMMRO_VERSION, 'connected' => null !== Store::connection(), 'enabled' => $settings['enabled'], 'woocommerce' => array( 'active' => WooCommerce::available(), 'shared' => WooCommerce::shared(), ), ); } }