delete($wpdb->prefix.'woocommerce_api_keys', ['key_id' => (int) $stored['key_id']], ['%d']); } delete_option(self::OPTION); } /** * @return array{key_id: int, consumer_key: string, consumer_secret: string}|null */ private static function create(): ?array { global $wpdb; $user_id = self::resolveUserId(); if (! $user_id) { return null; } $consumer_key = 'ck_'.wc_rand_hash(); $consumer_secret = 'cs_'.wc_rand_hash(); $inserted = $wpdb->insert( $wpdb->prefix.'woocommerce_api_keys', [ 'user_id' => $user_id, 'description' => __('Afileasy', 'afileasy-for-woocommerce'), 'permissions' => 'read_write', 'consumer_key' => wc_api_hash($consumer_key), 'consumer_secret' => $consumer_secret, 'truncated_key' => substr($consumer_key, -7), ], ['%d', '%s', '%s', '%s', '%s', '%s'] ); if (! $inserted) { return null; } $credentials = [ 'key_id' => (int) $wpdb->insert_id, 'consumer_key' => $consumer_key, 'consumer_secret' => $consumer_secret, ]; update_option(self::OPTION, $credentials, false); return $credentials; } private static function exists(int $key_id): bool { global $wpdb; if ($key_id <= 0) { return false; } $found = $wpdb->get_var($wpdb->prepare( "SELECT key_id FROM {$wpdb->prefix}woocommerce_api_keys WHERE key_id = %d", $key_id )); return $found !== null; } /** * The key inherits its owner's capabilities, so it must belong to someone * who can manage WooCommerce — the merchant connecting the store, or the * oldest administrator when running without a current user (cron). */ private static function resolveUserId(): int { $current = get_current_user_id(); if ($current && user_can($current, 'manage_woocommerce')) { return (int) $current; } $admins = get_users([ 'role' => 'administrator', 'number' => 1, 'orderby' => 'ID', 'order' => 'ASC', 'fields' => 'ID', ]); return $admins ? (int) $admins[0] : 0; } }