'error', 'text' => __('WooCommerce is not installed/active.', 'agenized-for-woocommerce')];
} else {
$store_url = rtrim(home_url(), '/');
// Check if a WooCommerce connection already exists
$existing_connections_res = AgenizedApi::list_provider_connections('woocommerce');
$existing_connections = $existing_connections_res['ok'] ? ($existing_connections_res['connections'] ?? []) : [];
// Check if we already have keys stored (reconnecting to same store)
$existing_key_id = Options::get_string(Options::OPT_WC_KEY_ID, '');
$matching_connection = null;
if (count($existing_connections) > 0) {
// Try to find a matching connection (same base_url and consumer_key)
foreach ($existing_connections as $conn) {
if (!is_array($conn)) {
continue;
}
$conn_config = isset($conn['config']) && is_array($conn['config']) ? $conn['config'] : [];
$conn_base_url = isset($conn_config['base_url']) ? rtrim((string) $conn_config['base_url'], '/') : '';
$conn_consumer_key = isset($conn_config['consumer_key']) ? (string) $conn_config['consumer_key'] : '';
// If we have a stored key_id, check if it matches
if ($existing_key_id !== '') {
// Get the consumer key from WooCommerce database (table name from $wpdb->prefix + WooCommerce core table; no user input).
global $wpdb;
$table_name = $wpdb->prefix . 'woocommerce_api_keys';
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
$key_row = $wpdb->get_row($wpdb->prepare("SELECT consumer_key FROM {$table_name} WHERE key_id = %d", (int) $existing_key_id), ARRAY_A);
if ($key_row && isset($key_row['consumer_key'])) {
$stored_key_hash = (string) $key_row['consumer_key'];
// Compare hashed keys
if ($conn_consumer_key && function_exists('wc_api_hash')) {
$hashed_conn_key = wc_api_hash($conn_consumer_key);
if ($hashed_conn_key === $stored_key_hash && $conn_base_url === $store_url) {
$matching_connection = $conn;
break;
}
}
}
}
// Also check by base_url match (if keys match, we'll verify later)
if ($conn_base_url === $store_url && $conn_consumer_key) {
$matching_connection = $conn;
break;
}
}
}
if ($matching_connection !== null) {
// Same connection - just save the connection ID
$connection_id = is_array($matching_connection) && isset($matching_connection['id']) ? (string) $matching_connection['id'] : '';
if ($connection_id !== '') {
Options::update_string(Options::OPT_WC_ACTION_CONNECTION_ID, $connection_id);
if ($existing_key_id === '') {
// Try to find the key_id from the connection's consumer_key
$conn_config = isset($matching_connection['config']) && is_array($matching_connection['config']) ? $matching_connection['config'] : [];
$conn_consumer_key = isset($conn_config['consumer_key']) ? (string) $conn_config['consumer_key'] : '';
if ($conn_consumer_key) {
global $wpdb;
$table_name = $wpdb->prefix . 'woocommerce_api_keys';
$hashed_key = function_exists('wc_api_hash') ? wc_api_hash($conn_consumer_key) : hash_hmac('sha256', $conn_consumer_key, 'wc-api');
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
$key_row = $wpdb->get_row($wpdb->prepare("SELECT key_id FROM {$table_name} WHERE consumer_key = %s LIMIT 1", $hashed_key), ARRAY_A);
if ($key_row && isset($key_row['key_id'])) {
Options::update_string(Options::OPT_WC_KEY_ID, (string) $key_row['key_id']);
}
}
}
$notice = ['type' => 'success', 'text' => __('WooCommerce connection found and saved.', 'agenized-for-woocommerce')];
}
} elseif (count($existing_connections) > 0) {
// Different connection exists - ask for confirmation
$existing_connection = $existing_connections[0];
$existing_connection_id = is_array($existing_connection) && isset($existing_connection['id']) ? (string) $existing_connection['id'] : '';
$existing_connection_name = is_array($existing_connection) && isset($existing_connection['name']) ? (string) $existing_connection['name'] : __('WooCommerce Connection', 'agenized-for-woocommerce');
set_transient('agenized_wc_overwrite_' . get_current_user_id(), [
'connection_id' => $existing_connection_id,
'connection_name' => $existing_connection_name,
], 300);
$notice = ['type' => 'warning', 'text' => __('A different WooCommerce connection already exists. Please confirm if you want to overwrite it.', 'agenized-for-woocommerce')];
} else {
// No existing connection, proceed with creation
$key_res = self::create_woocommerce_keys();
if (!$key_res['ok']) {
$notice = ['type' => 'error', 'text' => $key_res['message'] ?? __('Failed to create WooCommerce keys', 'agenized-for-woocommerce')];
} else {
$ck = (string) $key_res['consumer_key'];
$cs = (string) $key_res['consumer_secret'];
$key_id = (string) $key_res['key_id'];
$payload = [
'name' => __('WooCommerce:', 'agenized-for-woocommerce') . ' ' . wp_parse_url($store_url, PHP_URL_HOST),
'auth_type' => 'api_key',
'config' => [
'base_url' => $store_url,
'consumer_key' => $ck,
'consumer_secret' => $cs,
],
];
$conn = AgenizedApi::create_provider_connection('woocommerce', $payload);
if (!$conn['ok']) {
$notice = ['type' => 'error', 'text' => __('Failed to create Agenized connection:', 'agenized-for-woocommerce') . ' ' . ($conn['message'] ?? '')];
} else {
$connection = $conn['connection'] ?? [];
$connection_id = is_array($connection) && isset($connection['id']) ? (string) $connection['id'] : '';
if ($connection_id === '') {
$notice = ['type' => 'error', 'text' => __('Agenized connection response missing id.', 'agenized-for-woocommerce')];
} else {
Options::update_string(Options::OPT_WC_ACTION_CONNECTION_ID, $connection_id);
Options::update_string(Options::OPT_WC_KEY_ID, $key_id);
$notice = ['type' => 'success', 'text' => __('WooCommerce connected to Agenized.', 'agenized-for-woocommerce')];
}
}
}
}
}
}
if ($action === 'confirm_overwrite_woocommerce') {
if (!$has_woocommerce) {
$notice = ['type' => 'error', 'text' => __('WooCommerce is not installed/active.', 'agenized-for-woocommerce')];
} else {
// Get stored connection info from transient
$overwrite_data = get_transient('agenized_wc_overwrite_' . get_current_user_id());
if (!$overwrite_data || !isset($overwrite_data['connection_id'])) {
$notice = ['type' => 'error', 'text' => __('Overwrite confirmation expired. Please try again.', 'agenized-for-woocommerce')];
} else {
$existing_connection_id = (string) $overwrite_data['connection_id'];
$key_res = self::create_woocommerce_keys();
if (!$key_res['ok']) {
$notice = ['type' => 'error', 'text' => $key_res['message'] ?? __('Failed to create WooCommerce keys', 'agenized-for-woocommerce')];
} else {
$ck = (string) $key_res['consumer_key'];
$cs = (string) $key_res['consumer_secret'];
$key_id = (string) $key_res['key_id'];
$store_url = home_url();
$payload = [
'name' => __('WooCommerce:', 'agenized-for-woocommerce') . ' ' . wp_parse_url($store_url, PHP_URL_HOST),
'auth_type' => 'api_key',
'config' => [
'base_url' => rtrim($store_url, '/'),
'consumer_key' => $ck,
'consumer_secret' => $cs,
],
];
$conn = AgenizedApi::update_provider_connection('woocommerce', $existing_connection_id, $payload);
if (!$conn['ok']) {
$notice = ['type' => 'error', 'text' => __('Failed to update Agenized connection:', 'agenized-for-woocommerce') . ' ' . ($conn['message'] ?? '')];
} else {
// Clear transient
delete_transient('agenized_wc_overwrite_' . get_current_user_id());
Options::update_string(Options::OPT_WC_ACTION_CONNECTION_ID, $existing_connection_id);
Options::update_string(Options::OPT_WC_KEY_ID, $key_id);
$notice = ['type' => 'success', 'text' => __('WooCommerce connection updated successfully.', 'agenized-for-woocommerce')];
}
}
}
}
}
if ($action === 'cancel_overwrite_woocommerce') {
// Clear transient
delete_transient('agenized_wc_overwrite_' . get_current_user_id());
$notice = ['type' => 'info', 'text' => __('Overwrite cancelled. Existing connection unchanged.', 'agenized-for-woocommerce')];
}
if ($action === 'enable_actions_for_agent') {
$agent_id = isset($_POST['agent_id']) ? sanitize_text_field(wp_unslash($_POST['agent_id'])) : '';
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Unslashed and sanitized per element in loop below.
$raw_action_keys = isset($_POST['action_keys']) ? (array) wp_unslash($_POST['action_keys']) : [];
$action_keys = is_array($raw_action_keys) ? $raw_action_keys : [];
$connection_id = Options::get_string(Options::OPT_WC_ACTION_CONNECTION_ID, '');
if ($agent_id === '' || $connection_id === '') {
$notice = ['type' => 'error', 'text' => __('Missing agent or WooCommerce connection.', 'agenized-for-woocommerce')];
} else {
// Check if a config already exists for this agent+connection
$configs_res = AgenizedApi::list_agent_provider_configs($agent_id, 'woocommerce');
$existing_config = null;
if ($configs_res['ok']) {
$configs = $configs_res['configs'] ?? [];
foreach ($configs as $config) {
if (is_array($config)) {
$config_connection_id = isset($config['connection_id']) ? (string) $config['connection_id'] : '';
if ($config_connection_id === $connection_id) {
$existing_config = $config;
break;
}
}
}
}
$actions_payload = [];
foreach ($action_keys as $k) {
$k = sanitize_text_field(wp_unslash($k));
if ($k !== '') {
$actions_payload[] = [
'action_key' => $k,
'enabled' => true,
];
}
}
if ($existing_config !== null) {
// Update existing config
$config_id = isset($existing_config['id']) ? (string) $existing_config['id'] : '';
if ($config_id === '') {
$notice = ['type' => 'error', 'text' => __('Existing config missing ID.', 'agenized-for-woocommerce')];
} else {
$payload = [
'actions' => $actions_payload,
];
$res = AgenizedApi::update_agent_provider_config($agent_id, 'woocommerce', $config_id, $payload);
if ($res['ok']) {
$notice = ['type' => 'success', 'text' => __('Agent permissions updated.', 'agenized-for-woocommerce')];
} else {
$notice = ['type' => 'error', 'text' => __('Failed to update agent permissions:', 'agenized-for-woocommerce') . ' ' . ($res['message'] ?? '')];
}
}
} else {
// Create new config
$payload = [
'connection_id' => $connection_id,
'name' => __('WooCommerce Store', 'agenized-for-woocommerce'),
'actions' => $actions_payload,
];
$res = AgenizedApi::create_agent_provider_config($agent_id, 'woocommerce', $payload);
if ($res['ok']) {
$notice = ['type' => 'success', 'text' => __('Agent configured for WooCommerce actions.', 'agenized-for-woocommerce')];
} else {
$notice = ['type' => 'error', 'text' => __('Failed to configure agent:', 'agenized-for-woocommerce') . ' ' . ($res['message'] ?? '')];
}
}
}
}
}
$connection_id = Options::get_string(Options::OPT_WC_ACTION_CONNECTION_ID, '');
$key_id = Options::get_string(Options::OPT_WC_KEY_ID, '');
// Verify the connection still exists in Agenized
if ($connection_id !== '') {
$connections_res = AgenizedApi::list_provider_connections('woocommerce');
$connections = $connections_res['ok'] ? ($connections_res['connections'] ?? []) : [];
$connection_exists = false;
foreach ($connections as $conn) {
if (is_array($conn)) {
$conn_id = isset($conn['id']) ? (string) $conn['id'] : '';
if ($conn_id === $connection_id) {
$connection_exists = true;
break;
}
}
}
if (!$connection_exists) {
// Connection was deleted in Agenized, clear it from WordPress
Options::update_string(Options::OPT_WC_ACTION_CONNECTION_ID, '');
Options::update_string(Options::OPT_WC_KEY_ID, '');
$connection_id = '';
$key_id = '';
if (!isset($notice)) {
$notice = ['type' => 'warning', 'text' => __('The WooCommerce connection was deleted in Agenized. Please reconnect.', 'agenized-for-woocommerce')];
}
}
}
$agents_res = AgenizedApi::list_agents();
$actions_res = AgenizedApi::list_provider_actions('woocommerce');
$agents = $agents_res['ok'] ? ($agents_res['agents'] ?? []) : [];
$actions = $actions_res['ok'] ? ($actions_res['actions'] ?? []) : [];
// Get selected agent's current config if agent_id is provided
$selected_agent_id = isset($_GET['agent_id']) ? sanitize_text_field(wp_unslash($_GET['agent_id'])) : '';
$agent_configs = [];
$agent_enabled_actions = [];
if ($selected_agent_id !== '' && $connection_id !== '') {
$configs_res = AgenizedApi::list_agent_provider_configs($selected_agent_id, 'woocommerce');
if ($configs_res['ok']) {
$agent_configs = $configs_res['configs'] ?? [];
// Find configs that use our connection_id
foreach ($agent_configs as $config) {
if (is_array($config)) {
$config_connection_id = isset($config['connection_id']) ? (string) $config['connection_id'] : '';
if ($config_connection_id === $connection_id) {
// Get enabled actions from this config
$config_actions = isset($config['actions']) && is_array($config['actions']) ? $config['actions'] : [];
foreach ($config_actions as $action) {
if (is_array($action)) {
$action_key = isset($action['action_key']) ? (string) $action['action_key'] : '';
$action_enabled = isset($action['enabled']) ? (bool) $action['enabled'] : false;
if ($action_key && $action_enabled) {
$agent_enabled_actions[$action_key] = true;
}
}
}
}
}
}
}
}
?>
false, 'message' => __('WooCommerce is not active.', 'agenized-for-woocommerce')];
}
$user_id = get_current_user_id();
if (!$user_id) {
return ['ok' => false, 'message' => __('No current user.', 'agenized-for-woocommerce')];
}
try {
// Generate random hash (WooCommerce uses 40 character hashes)
$rand_hash = function_exists('wc_rand_hash')
? wc_rand_hash()
: bin2hex(random_bytes(20)); // 40 character hex string
// Generate consumer key and secret (WooCommerce format: ck_... and cs_...)
$consumer_key = 'ck_' . $rand_hash;
$consumer_secret = 'cs_' . bin2hex(random_bytes(20));
// Hash the consumer key for storage (WooCommerce stores hashed keys)
$hashed_key = function_exists('wc_api_hash')
? wc_api_hash($consumer_key)
: hash_hmac('sha256', $consumer_key, 'wc-api');
// Insert into WooCommerce API keys table (required; no WooCommerce API for creating keys).
$table_name = $wpdb->prefix . 'woocommerce_api_keys';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$result = $wpdb->insert(
$table_name,
[
'user_id' => $user_id,
'description' => __('Agenized Integration', 'agenized-for-woocommerce'),
'permissions' => 'read_write',
'consumer_key' => $hashed_key,
'consumer_secret' => $consumer_secret,
'truncated_key' => substr($consumer_key, -7),
'last_access' => null,
],
['%d', '%s', '%s', '%s', '%s', '%s', '%s']
);
if ($result === false) {
return ['ok' => false, 'message' => __('Failed to insert WooCommerce API key into database:', 'agenized-for-woocommerce') . ' ' . $wpdb->last_error];
}
$key_id = (string) $wpdb->insert_id;
return [
'ok' => true,
'consumer_key' => $consumer_key,
'consumer_secret' => $consumer_secret,
'key_id' => $key_id,
];
} catch (\Throwable $e) {
return ['ok' => false, 'message' => __('Failed to create WooCommerce keys:', 'agenized-for-woocommerce') . ' ' . $e->getMessage()];
}
}
}