'store_search', 'label' => __('Product search', 'webfon'), 'description' => 'Finds the store\'s products by words of their name or kind, a price range, those on sale or those in stock: their names, prices, stock and pages.', 'method' => 'GET', 'path' => 'wc/store/v1/products', 'query' => 'search={query}&per_page=10&_fields=id,name,permalink,prices,is_in_stock,short_description', 'parameters' => [ ['name' => 'query', 'type' => 'string', 'description' => 'Words of the product\'s name or kind, as the customer said them.', 'required' => false], ['name' => 'min_price', 'type' => 'integer', 'description' => 'The lowest price, in the currency\'s minor units as the prices come.', 'required' => false], ['name' => 'max_price', 'type' => 'integer', 'description' => 'The highest price, in the currency\'s minor units as the prices come.', 'required' => false], ['name' => 'on_sale', 'type' => 'boolean', 'description' => 'true: the products on sale alone.', 'required' => false], ['name' => 'stock_status', 'type' => 'string', 'description' => 'instock, outofstock or onbackorder: those alone.', 'required' => false], ], 'response_description' => 'Each match: name, permalink (its page), is_in_stock, short_description (HTML); prices: price, regular_price and sale_price in the currency\'s minor units (divide by 10 to the power of currency_minor_unit), currency_code; id: store_product\'s argument.', 'access' => 'everyone', ], [ 'name' => 'store_product', 'label' => __('Product details', 'webfon'), 'description' => 'One product\'s details: its description, attributes and variations with their prices and stock.', 'method' => 'GET', 'path' => 'wc/store/v1/products/{id}', 'parameters' => [ ['name' => 'id', 'type' => 'integer', 'description' => 'The product\'s id, from store_search\'s results, or a variation\'s.', 'required' => true], ], 'response_description' => 'The product: name, permalink (its page), description (HTML), is_in_stock, prices in the currency\'s minor units as in store_search, attributes and variations; a variation (a size, a colour) is a product of its own, whose stock and price store_product gives by its id. For the customer to add it to their cart, give the permalink with ?add-to-cart={id}&quantity={n}, a variation\'s id for a size or colour.', 'access' => 'everyone', ], [ 'name' => 'store_account', 'label' => __('Account details', 'webfon'), 'description' => 'The signed-in customer\'s account: their name, email, phone and saved billing and shipping addresses.', 'method' => 'GET', 'path' => $customer, 'parameters' => [], 'response_description' => 'first_name, last_name, email, phone; billing and shipping: the saved addresses (first_name, last_name, company, address_1, address_2, city, state, postcode, country, phone; billing\'s email too).', 'access' => 'member', 'callback' => 'webfon_tool_account', ], [ 'name' => 'store_orders', 'label' => __('Orders', 'webfon'), 'description' => 'The signed-in customer\'s latest orders: their numbers, dates, statuses, totals and items.', 'method' => 'GET', 'path' => $customer . '/orders', 'parameters' => [], 'response_description' => 'The latest 10 orders, the newest first: number (what the customer calls it, the other order tools\' argument), date_created, status (pending: awaiting payment, processing: paid and being prepared, on-hold: awaiting the store, completed: sent, cancelled, refunded, failed: its payment failed), total and currency, items (name and quantity).', 'access' => 'member', 'callback' => 'webfon_tool_orders', ], [ 'name' => 'store_order', 'label' => __('Order details', 'webfon'), 'description' => 'One of the signed-in customer\'s orders in full: its items, totals, addresses, status, the store\'s notes to the customer (shipping, tracking), its payment link while unpaid and its refunds.', 'method' => 'GET', 'path' => $order, 'parameters' => [ ['name' => 'order', 'type' => 'integer', 'description' => 'The order\'s number, as the customer gives it or store_orders lists it.', 'required' => true], ], 'response_description' => 'number, date_created, status (as in store_orders), total, currency, payment_method_title; items (name, quantity, total); shipping (method_title, total); billing and shipping addresses; notes: what the store wrote to the customer, the newest first (date_created, note: a tracking number is often here); payment_url while it awaits payment, where the customer pays; refunds (date_created, amount, reason); can_cancel: whether store_order_cancel may cancel it. A 404: the customer has no such order.', 'access' => 'member', 'callback' => 'webfon_tool_order', ], [ 'name' => 'store_order_cancel', 'label' => __('Order cancellation', 'webfon'), 'description' => 'Cancels one of the signed-in customer\'s orders when they ask to: one the store lets a customer cancel (by default one awaiting payment or whose payment failed).', 'method' => 'POST', 'path' => $order . '/cancel', 'parameters' => [ ['name' => 'order', 'type' => 'integer', 'description' => 'The order\'s number, as the customer gives it or store_orders lists it.', 'required' => true], ], 'response_description' => 'cancelled: true when the order is cancelled now (its items go back into stock); false with reason when it cannot be: its status is not one the store lets a customer cancel. A 404: the customer has no such order.', 'access' => 'member', 'callback' => 'webfon_tool_cancel', ], [ 'name' => 'store_order_note', 'label' => __('Order notes', 'webfon'), 'description' => 'Adds the customer\'s note to one of their orders for the store to read, such as a delivery instruction.', 'method' => 'POST', 'path' => $order . '/notes', 'parameters' => [ ['name' => 'order', 'type' => 'integer', 'description' => 'The order\'s number, as the customer gives it or store_orders lists it.', 'required' => true], ['name' => 'note', 'type' => 'string', 'description' => 'The note, in the customer\'s words.', 'required' => true], ], 'response_description' => 'added: true when the note is on the order. A 404: the customer has no such order.', 'access' => 'member', 'callback' => 'webfon_tool_note', ], [ 'name' => 'store_invoice', 'label' => __('Invoice email', 'webfon'), 'description' => 'Emails the signed-in customer an order\'s details again, WooCommerce\'s invoice email; their latest order when none is named.', 'method' => 'POST', 'path' => $customer . '/invoice', 'parameters' => [ ['name' => 'order', 'type' => 'integer', 'description' => 'The order\'s number, as the customer gives it or store_orders lists it; their latest order without one.', 'required' => false], ], 'response_description' => 'sent: true, with number (the order\'s) and email (where it went); an order awaiting payment gets a payment request. A 404: the customer has no such order, or none at all.', 'access' => 'member', 'callback' => 'webfon_tool_invoice', ], [ 'name' => 'store_downloads', 'label' => __('Downloads', 'webfon'), 'description' => 'The signed-in customer\'s downloadable files: their links, the downloads left and their expiry.', 'method' => 'GET', 'path' => $customer . '/downloads', 'parameters' => [], 'response_description' => 'Each file: product, file (its name), download_url (the customer\'s own link, which WooCommerce checks), downloads_remaining (null: unlimited), access_expires (null: never).', 'access' => 'member', 'callback' => 'webfon_tool_downloads', ], [ 'name' => 'store_coupons', 'label' => __('Coupons', 'webfon'), 'description' => 'The coupons meant for the signed-in customer: their codes, discounts, expiry and minimum spend.', 'method' => 'GET', 'path' => $customer . '/coupons', 'parameters' => [], 'response_description' => 'Each coupon with the customer\'s email on it they may still use: code, amount, discount_type (percent, fixed_cart or fixed_product), date_expires (null: never), minimum_amount, usage_left (null: unlimited). A coupon open to every customer is not here.', 'access' => 'member', 'callback' => 'webfon_tool_coupons', ], [ 'name' => 'store_stock_alert', 'label' => __('Back-in-stock emails', 'webfon'), 'description' => 'Signs the signed-in customer up for an email when an out-of-stock product or variation is back in stock.', 'method' => 'POST', 'path' => $customer . '/stock-alerts', 'parameters' => [ ['name' => 'product', 'type' => 'integer', 'description' => 'The product\'s id, a variation\'s for a size or colour, from store_search or store_product.', 'required' => true], ], 'response_description' => 'status: signed_up (an email goes to the customer when it is back), already (signed up before), in_stock (it is in stock now), unavailable (the store sends no back-in-stock emails).', 'access' => 'member', 'callback' => 'webfon_tool_stock_alert', ], ]; } /** The names of the tools ticked under Settings → Webfon: none until a Connect keeps a choice. */ function webfon_tools_ticked() { $ticked = get_option('webfon_tools'); return is_array($ticked) ? array_values(array_intersect(array_column(webfon_tools(), 'name'), $ticked)) : []; } /** * The ticked tools as the Webfon panel adds them to the AI agent: a custom tool's fields, on this site's addresses * (rest_url(), Plain permalinks' ?rest_route= too). */ function webfon_tools_sent() { $ticked = webfon_tools_ticked(); $sent = []; foreach (webfon_tools() as $tool) { if (!in_array($tool['name'], $ticked, true)) { continue; } $url = rest_url($tool['path']); if (isset($tool['query'])) { $url .= (false === strpos($url, '?') ? '?' : '&') . $tool['query']; } $sent[] = [ 'name' => $tool['name'], 'description' => $tool['description'], 'method' => $tool['method'], 'url' => $url, 'parameters' => $tool['parameters'], 'response_description' => $tool['response_description'], 'access' => $tool['access'], ]; } return $sent; } // The ticked tools' routes alone: an unticked one answers no call, an agent that still has it included. add_action('rest_api_init', function () { $ticked = webfon_tools_ticked(); foreach (webfon_tools() as $tool) { if (isset($tool['callback']) && in_array($tool['name'], $ticked, true)) { // Its path under webfon/v1, each placeholder the argument it names. $route = strtr(substr($tool['path'], strlen('webfon/v1')), ['{external_id}' => '(?P[^/]+)', '{order}' => '(?P\d+)']); register_rest_route('webfon/v1', $route, [ 'methods' => $tool['method'], 'callback' => fn(WP_REST_Request $request) => webfon_tool_response($tool['callback'], $request), 'permission_callback' => 'webfon_tool_signed', ]); } } }); /** * Whether Webfon signed the call (HTTP Message Signatures, RFC 9421, as its socket signs): the signing secret (whsec_ * and the key in base64) over the call's method, path, query and body, its created within 60 s, its nonce once. * Else 401. The method is the one WordPress routes the call by, so an override header cannot change it unsigned. */ function webfon_tool_signed(WP_REST_Request $request) { $key = base64_decode(substr((string) get_option('webfon_tool_secret'), 6), true); $unsigned = new WP_Error('webfon_unsigned', 'The call is not signed by Webfon.', ['status' => 401]); if (!$key || !preg_match('/^webfon=(\("@method" "@path" "@query" "content-digest"\);created=(\d+);nonce="([0-9a-f-]{36})")$/', (string) $request->get_header('signature-input'), $m) || abs(time() - (int) $m[2]) > 60) { return $unsigned; } // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- the address as sent, which the signature covers: compared alone, never output or stored. $uri = explode('?', isset($_SERVER['REQUEST_URI']) ? wp_unslash($_SERVER['REQUEST_URI']) : '', 2); // The body's own digest, not the Content-Digest header: a header that differs fails the signature alone. $base = '"@method": ' . $request->get_method() . "\n\"@path\": " . $uri[0] . "\n\"@query\": ?" . ($uri[1] ?? '') . "\n\"content-digest\": sha-256=:" . base64_encode(hash('sha256', $request->get_body(), true)) . ':' . "\n\"@signature-params\": " . $m[1]; $seen = 'webfon_call_' . $m[3]; if (!hash_equals('webfon=:' . base64_encode(hash_hmac('sha256', $base, (string) $key, true)) . ':', (string) $request->get_header('signature')) || get_transient($seen)) { return $unsigned; } set_transient($seen, 1, 2 * MINUTE_IN_SECONDS); return true; } /** * A tool's answer for the user {external_id} names; none (null): 404. A staff account (one that can edit posts) is 404 * too, so Webfon acts for no account that administers the site. No cache may keep it: it is this customer's alone, * and a cached copy would answer the same address without the signature. */ function webfon_tool_response(callable $tool, WP_REST_Request $request) { if (!defined('DONOTCACHEPAGE')) { define('DONOTCACHEPAGE', true); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- the page-cache plugins' shared constant } $id = (string) $request['external_id']; $user = ctype_digit($id) ? get_user_by('id', (int) $id) : false; $user = $user && !user_can($user, 'edit_posts') ? $user : false; $response = rest_ensure_response(($user ? $tool($user, $request) : null) ?? new WP_Error('webfon_not_found', 'Not found.', ['status' => 404])); $response = is_wp_error($response) ? rest_convert_error_to_response($response) : $response; $response->header('Cache-Control', 'no-store, private'); return $response; } /** The user's latest orders, the newest first; a checkout's draft is no order yet. */ function webfon_orders(WP_User $user, int $limit) { return wc_get_orders([ 'customer_id' => $user->ID, 'type' => 'shop_order', 'status' => array_diff(array_keys(wc_get_order_statuses()), ['wc-checkout-draft']), 'limit' => $limit, 'orderby' => 'date', 'order' => 'DESC', ]); } /** * The user's order of that number, else null: the number the customer calls it is its id, unless a plugin numbers the * store's orders, which maps its numbers back through the filter WooCommerce's order tracking asks. * shortcut: digits alone (the route's pattern, the tools' integer); a store numbering with letters needs a string argument. */ function webfon_order(WP_User $user, $number) { $order = wc_get_order((int) apply_filters('woocommerce_shortcode_order_tracking_order_id', (string) $number)); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WooCommerce's own hook, fired as WooCommerce fires it return $order instanceof WC_Order && $order->get_customer_id() === $user->ID && !$order->has_status('checkout-draft') ? $order : null; } function webfon_date($date) { return $date instanceof WC_DateTime ? $date->date('c') : null; } function webfon_order_summary(WC_Order $order) { return [ 'number' => $order->get_order_number(), 'date_created' => webfon_date($order->get_date_created()), 'status' => $order->get_status(), 'total' => $order->get_total(), 'currency' => $order->get_currency(), ]; } /** Its products: name and quantity, with their line's total (tax included) too. */ function webfon_items(WC_Order $order, bool $totals) { return array_values(array_map( fn($item) => ['name' => $item->get_name(), 'quantity' => $item->get_quantity()] + ($totals ? ['total' => $order->get_line_total($item, true)] : []), $order->get_items() )); } /** The statuses the store lets a customer cancel an order in: WooCommerce's own rule (by default pending and failed). */ function webfon_cancellable(WC_Order $order) { return apply_filters('woocommerce_valid_order_statuses_for_cancel', ['pending', 'failed'], $order); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WooCommerce's own hook, fired as WooCommerce fires it } /** store_account */ function webfon_tool_account(WP_User $user) { $customer = new WC_Customer($user->ID); return [ 'first_name' => $customer->get_first_name(), 'last_name' => $customer->get_last_name(), 'email' => $customer->get_email(), 'phone' => $customer->get_billing_phone(), 'billing' => $customer->get_billing(), 'shipping' => $customer->get_shipping(), ]; } /** store_orders */ function webfon_tool_orders(WP_User $user) { return array_map(fn(WC_Order $order) => webfon_order_summary($order) + ['items' => webfon_items($order, false)], webfon_orders($user, 10)); } /** store_order */ function webfon_tool_order(WP_User $user, WP_REST_Request $request) { $order = webfon_order($user, $request['order']); if (!$order) { return null; } return webfon_order_summary($order) + [ 'payment_method_title' => $order->get_payment_method_title(), 'items' => webfon_items($order, true), // How and where it ships: its method with its address. 'shipping' => ['method_title' => $order->get_shipping_method(), 'total' => $order->get_shipping_total()] + $order->get_address('shipping'), 'billing' => $order->get_address('billing'), // A list in JSON: wc_get_order_notes() filters its notes, keys and all. 'notes' => array_values(array_map( fn($note) => ['date_created' => webfon_date($note->date_created), 'note' => wp_strip_all_tags($note->content)], wc_get_order_notes(['order_id' => $order->get_id(), 'type' => 'customer']) )), 'payment_url' => $order->needs_payment() ? $order->get_checkout_payment_url() : null, 'refunds' => array_map( fn(WC_Order_Refund $refund) => ['date_created' => webfon_date($refund->get_date_created()), 'amount' => $refund->get_amount(), 'reason' => $refund->get_reason()], $order->get_refunds() ), 'can_cancel' => $order->has_status(webfon_cancellable($order)), ]; } /** store_order_cancel: as WooCommerce's own Cancel link does (WC_Form_Handler::cancel_order); the status puts its items back in stock. */ function webfon_tool_cancel(WP_User $user, WP_REST_Request $request) { $order = webfon_order($user, $request['order']); if (!$order) { return null; } $statuses = webfon_cancellable($order); if (!$order->has_status($statuses)) { return ['cancelled' => false, 'reason' => sprintf( 'The order is %s; the store lets a customer cancel an order only while it is %s.', wc_get_order_status_name($order->get_status()), implode(' or ', array_map('wc_get_order_status_name', $statuses)) )]; } $order->update_status('cancelled', __('Order cancelled by the customer through Webfon.', 'webfon')); do_action('woocommerce_cancelled_order', $order->get_id()); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WooCommerce's own hook, fired as WooCommerce fires it return ['cancelled' => true]; } /** store_order_note: a private note for the store; a customer note would be emailed back to the customer. */ function webfon_tool_note(WP_User $user, WP_REST_Request $request) { $order = webfon_order($user, $request['order']); if (!$order) { return null; } $note = trim(mb_substr(sanitize_textarea_field((string) $request['note']), 0, 2000)); if ('' === $note) { return new WP_Error('webfon_empty_note', 'The note is empty.', ['status' => 400]); } /* translators: %s: the customer's note. */ $order->add_order_note(sprintf(__('Note from the customer through Webfon: %s', 'webfon'), $note)); return ['added' => true]; } /** store_invoice: WooCommerce's order details email again, as its order action sends it; their latest order without one named. */ function webfon_tool_invoice(WP_User $user, WP_REST_Request $request) { $order = $request['order'] ? webfon_order($user, $request['order']) : (webfon_orders($user, 1)[0] ?? null); if (!$order) { return null; } do_action('woocommerce_before_resend_order_emails', $order, 'customer_invoice'); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WooCommerce's own hook, fired as WooCommerce fires it WC()->payment_gateways(); WC()->shipping(); WC()->mailer()->customer_invoice($order); $order->add_order_note(__('Order details sent to the customer through Webfon.', 'webfon')); do_action('woocommerce_after_resend_order_email', $order, 'customer_invoice'); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WooCommerce's own hook, fired as WooCommerce fires it return ['sent' => true, 'number' => $order->get_order_number(), 'email' => $order->get_billing_email()]; } /** store_downloads: a list in JSON, whatever keys a filter of WooCommerce's list leaves. */ function webfon_tool_downloads(WP_User $user) { return array_values(array_map(fn(array $download) => [ 'product' => $download['product_name'], 'file' => $download['download_name'], 'download_url' => $download['download_url'], 'downloads_remaining' => is_numeric($download['downloads_remaining']) ? (int) $download['downloads_remaining'] : null, 'access_expires' => webfon_date($download['access_expires']), ], wc_get_customer_available_downloads($user->ID))); } /** store_coupons: those whose allowed emails take the customer's (WooCommerce's own match, * patterns too), still usable by them. */ function webfon_tool_coupons(WP_User $user) { $emails = array_values(array_filter([$user->user_email, get_user_meta($user->ID, 'billing_email', true)])); $ids = get_posts([ 'post_type' => 'shop_coupon', 'post_status' => 'publish', 'numberposts' => 200, 'fields' => 'ids', 'meta_query' => [['key' => 'customer_email', 'value' => 'a:0:{}', 'compare' => '!=']], ]); $coupons = []; foreach ($ids as $id) { $coupon = new WC_Coupon($id); $allowed = class_exists(\Automattic\WooCommerce\Utilities\DiscountsUtil::class) ? \Automattic\WooCommerce\Utilities\DiscountsUtil::is_coupon_emails_allowed($emails, $coupon->get_email_restrictions()) : (bool) array_intersect(array_map('strtolower', $emails), array_map('strtolower', $coupon->get_email_restrictions())); $expires = $coupon->get_date_expires(); $left = []; if ($coupon->get_usage_limit()) { $left[] = $coupon->get_usage_limit() - $coupon->get_usage_count(); } if ($coupon->get_usage_limit_per_user()) { $left[] = $coupon->get_usage_limit_per_user() - count(array_intersect($coupon->get_used_by(), [(string) $user->ID, ...$emails])); } $usage_left = $left ? max(0, min($left)) : null; if (!$allowed || 0 === $usage_left || ($expires && $expires->getTimestamp() < time())) { continue; } $coupons[] = [ 'code' => $coupon->get_code(), 'amount' => $coupon->get_amount(), 'discount_type' => $coupon->get_discount_type(), 'date_expires' => webfon_date($expires), 'minimum_amount' => $coupon->get_minimum_amount(), 'usage_left' => $usage_left, ]; } return $coupons; } /** * store_stock_alert: WooCommerce's back-in-stock emails (its Customer stock notifications feature), signed up through * its internal service, as it has no public one: unavailable while the feature is off, or once that code moves. */ function webfon_tool_stock_alert(WP_User $user, WP_REST_Request $request) { $product = wc_get_product((int) $request['product']); if (!$product) { return null; } if ($product->is_in_stock()) { return ['status' => 'in_stock']; } $service = 'Automattic\WooCommerce\Internal\StockNotifications\Frontend\SignupService'; if (!class_exists($service) || !\Automattic\WooCommerce\Utilities\FeaturesUtil::feature_is_enabled('customer_stock_notifications')) { return ['status' => 'unavailable']; } // As the customer: WooCommerce limits sign-ups by the user, a guest's by the address, here Webfon's for every customer. wp_set_current_user($user->ID); try { $signups = wc_get_container()->get($service); // Before its rate limit, which turns away a second sign-up within 30 s. if ($signups->is_already_signed_up($product->get_id(), $user->ID, $user->user_email)) { return ['status' => 'already']; } $result = $signups->signup($product->get_id(), $user->ID, $user->user_email); } catch (Throwable $e) { return ['status' => 'unavailable']; } if (is_wp_error($result)) { return 'rate_limited' === $result->get_error_code() ? new WP_Error('webfon_rate_limited', 'Too many sign-ups for this customer: try again later.', ['status' => 429]) : ['status' => 'unavailable']; } return ['status' => 'signed_up']; }