5 ) ); return ! is_wp_error( $response ) && wp_remote_retrieve_response_code( $response ) === 200; } /** * Validates the OpenAI API key and optionally stores available model IDs in session. * * @since 0.1.0 * * @param string $api_key The OpenAI API key. * @return bool True if the key is valid or empty (gracefully), false on failure. */ public static function aistma_validate_aistma_openai_api_key( $api_key ) { $api_key = sanitize_text_field( wp_unslash( $api_key ) ); if ( '' === $api_key ) { return true; // Optional field accepted. } $response = wp_remote_get( 'https://api.openai.com/v1/models', array( 'timeout' => 5, 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), ) ); if ( is_wp_error( $response ) ) { return false; } $body = wp_remote_retrieve_body( $response ); $data = json_decode( $body, true ); $models = array(); if ( isset( $data['data'] ) && is_array( $data['data'] ) ) { foreach ( $data['data'] as $model ) { if ( isset( $model['id'] ) ) { $models[] = $model['id']; } } return true; } return false; } }