array( 'On hold', 'International', 'Tobacco refused' ), 'one_acc_user_status' => array( 'AV_FAILED', 'NON_UK_USER', 'TOBACCO_REFUSED' ), ); } public static function status_settings( $stored ) { if ( ! self::is_status_settings( $stored ) ) { $stored = self::default_status_settings(); } return self::without_fixed_results( self::rename_result_keys( $stored ) ); } /** * NO_UK_USER is the older name for NON_UK_USER. * * @param array $settings * @return array */ private static function rename_result_keys( array $settings ) { $results = array(); $renamed = false; foreach ( $settings['one_acc_user_status'] as $result ) { $normalized = strtoupper( str_replace( array( ' ', '-' ), '_', (string) $result ) ); if ( 'NO_UK_USER' === $normalized ) { $results[] = 'NON_UK_USER'; $renamed = true; continue; } $results[] = $result; } if ( ! $renamed ) { return $settings; } $settings['one_acc_user_status'] = $results; return $settings; } /** * AV_PENDING, AV_SUCCESS, and AV_SKIPPED are fixed. A saved row for any of them is ignored. * * @param array $settings * @return array{oneacc_status: array, one_acc_user_status: array} */ public static function without_fixed_results( array $settings ) { if ( ! self::is_status_settings( $settings ) ) { return self::default_status_settings(); } $statuses = array(); $results = array(); $removed = false; foreach ( $settings['one_acc_user_status'] as $key => $result ) { if ( self::is_fixed_result( $result ) || ! isset( $settings['oneacc_status'][ $key ] ) ) { $removed = true; continue; } $statuses[] = $settings['oneacc_status'][ $key ]; $results[] = $result; } if ( ! $removed ) { return $settings; } return array( 'oneacc_status' => $statuses, 'one_acc_user_status' => $results, ); } /** * @param mixed $stored */ private static function is_status_settings( $stored ) { return is_array( $stored ) && isset( $stored['oneacc_status'], $stored['one_acc_user_status'] ) && is_array( $stored['oneacc_status'] ) && is_array( $stored['one_acc_user_status'] ); } /** * WooCommerce calls this status Completed. The slug is completed. * Complete is accepted as the same status. */ public static function is_completed_status( $status ) { $slug = strtolower( (string) $status ); if ( 0 === strpos( $slug, 'wc-' ) ) { $slug = substr( $slug, 3 ); } $slug = str_replace( array( '-', '_', ' ' ), '', $slug ); return 'completed' === $slug || 'complete' === $slug; } /** * Whether a public status request is for this order. * WooCommerce puts the same key on the thank-you URL for guests and logged-in customers. * * @param object|null $order Order that owns the key. * @param mixed $order_key Key posted with the request. */ public static function order_key_matches( $order, $order_key ) { if ( ! is_object( $order ) || ! is_string( $order_key ) || '' === $order_key ) { return false; } if ( is_callable( array( $order, 'key_is_valid' ) ) ) { return (bool) $order->key_is_valid( $order_key ); } if ( ! is_callable( array( $order, 'get_order_key' ) ) ) { return false; } $stored = $order->get_order_key(); return is_string( $stored ) && '' !== $stored && hash_equals( $stored, $order_key ); } /** * WooCommerce order-status slug for a mapped label. * * Names WooCommerce already displays map to its slugs, so "Pending payment" * stays pending. Other labels turn spaces into underscores, so * "Tobacco refused" stays tobacco_refused. */ public static function order_status_slug( $label ) { $normalized = strtolower( trim( (string) $label ) ); $normalized = str_replace( array( '-', '_' ), ' ', $normalized ); $normalized = preg_replace( '/\s+/', ' ', $normalized ); $reserved = array( 'pending' => 'pending', 'pending payment' => 'pending', 'processing' => 'processing', 'on hold' => 'on-hold', 'completed' => 'completed', 'complete' => 'completed', 'cancelled' => 'cancelled', 'canceled' => 'cancelled', 'refunded' => 'refunded', 'failed' => 'failed', 'checkout draft' => 'checkout-draft', 'av pending' => self::AV_PENDING_STATUS, ); if ( isset( $reserved[ $normalized ] ) ) { return $reserved[ $normalized ]; } return str_replace( ' ', '_', $normalized ); } /** * Statuses this plugin must not register over. WooCommerce owns the shop-order * statuses. AV Pending is registered on its own. */ public static function is_core_order_status( $slug ) { $slug = strtolower( (string) $slug ); if ( 0 === strpos( $slug, 'wc-' ) ) { $slug = substr( $slug, 3 ); } return in_array( $slug, array( 'pending', 'processing', 'on-hold', 'completed', 'cancelled', 'refunded', 'failed', 'checkout-draft', self::AV_PENDING_STATUS, ), true ); } /** * Plugin-owned statuses from the mapping. Reserved WooCommerce statuses are left out. * * @param array $settings * @return array Slug => merchant label. */ public static function statuses_to_register( array $settings ) { if ( ! self::is_status_settings( $settings ) ) { return array(); } $register = array(); foreach ( $settings['oneacc_status'] as $label ) { $name = trim( (string) $label ); if ( '' === $name ) { continue; } $slug = self::order_status_slug( $name ); if ( '' === $slug || self::is_core_order_status( $slug ) || isset( $register[ $slug ] ) ) { continue; } $register[ $slug ] = $name; } return $register; } /** * Status slug without a wc- prefix. */ public static function normalize_status_slug( $status ) { $slug = strtolower( (string) $status ); if ( 0 === strpos( $slug, 'wc-' ) ) { $slug = substr( $slug, 3 ); } return $slug; } public static function same_status( $left, $right ) { $left_slug = self::normalize_status_slug( $left ); return '' !== $left_slug && $left_slug === self::normalize_status_slug( $right ); } public static function is_av_pending_status( $status ) { return self::AV_PENDING_STATUS === self::normalize_status_slug( $status ); } /** * AV_FAIL is the older name for the same result. */ public static function is_failed_result( $result ) { $value = strtoupper( str_replace( array( ' ', '-' ), '_', (string) $result ) ); return 'AV_FAILED' === $value || 'AV_FAIL' === $value; } /** * The thank-you page mounts the check while the order is waiting, and again * after a recorded failure so the customer can try once more. * Completed, Cancelled, Refunded, and Failed stay closed. * * @param string $status WooCommerce status. * @param string $tag av_order_tag_key stored on the order. */ public static function thankyou_shows_iframe( $status, $tag ) { if ( self::is_status_locked( $status ) ) { return false; } return self::is_av_pending_status( $status ) || self::is_failed_result( $tag ); } /** * A recorded failure opens the check on the next visit. The stored popup * flag only suppresses a repeat while the order is still waiting. * * @param string $stored Value of av_popups. * @param string $tag av_order_tag_key stored on the order. */ public static function thankyou_popup_value( $stored, $tag ) { if ( self::is_failed_result( $tag ) ) { return ''; } return (string) $stored; } /** * AV_PENDING, AV_SUCCESS, and AV_SKIPPED choose their outcome in code. * A saved mapping row for any of them is ignored. */ public static function is_fixed_result( $result ) { $normalized = strtolower( str_replace( array( ' ', '-' ), '_', (string) $result ) ); return in_array( $normalized, array( 'av_pending', 'av_success', 'av_skipped' ), true ); } /** * Tag to store when payment is recorded and every product skips the check. * Empty when a check is still required, or when a tag is already stored. * * @param bool $skip_av True when every item is SKIP_AV and none is tobacco. * @param string $existing_tag av_order_tag_key already stored on the order. */ public static function skipped_av_tag( $skip_av, $existing_tag ) { if ( ! $skip_av ) { return ''; } $existing = strtoupper( str_replace( array( ' ', '-' ), '_', (string) $existing_tag ) ); if ( '' !== $existing ) { return ''; } return self::AV_SKIPPED_TAG; } /** * Failed, Cancelled, Refunded, and Completed are never moved by a check result. */ public static function is_status_locked( $status ) { if ( self::is_completed_status( $status ) ) { return true; } return in_array( self::normalize_status_slug( $status ), array( 'failed', 'cancelled', 'refunded' ), true ); } /** * A check result may change status only from AV Pending, or from the status this plugin last wrote. * On hold a merchant set does not match an empty plugin status, so it stays. * * @param string $current_status Current WooCommerce status. * @param string $plugin_status Value of _oneaccount_plugin_status. Empty when a person chose the current status. */ public static function can_apply_check_status( $current_status, $plugin_status ) { if ( self::is_status_locked( $current_status ) ) { return false; } if ( self::is_av_pending_status( $current_status ) ) { return true; } return self::same_status( $current_status, $plugin_status ); } /** * WooCommerce slug for a mapped result. AV_PENDING and AV_SUCCESS have no mapped slug. * * @param array $settings */ public static function mapped_status_for_result( $result, array $settings ) { if ( self::is_fixed_result( $result ) || ! self::is_status_settings( $settings ) ) { return ''; } $wanted = strtolower( str_replace( array( ' ', '-' ), '_', (string) $result ) ); foreach ( $settings['one_acc_user_status'] as $key => $user_status ) { if ( self::is_fixed_result( $user_status ) || ! isset( $settings['oneacc_status'][ $key ] ) ) { continue; } $normalized = strtolower( str_replace( array( ' ', '-' ), '_', (string) $user_status ) ); if ( $normalized === $wanted ) { return self::order_status_slug( $settings['oneacc_status'][ $key ] ); } } return ''; } /** * Status to set when a payment is recorded. * A UK order that still needs a check waits in AV Pending. Card payments for a non-UK * order use the NON_UK_USER row. Cash on delivery leaves that row for after WooCommerce's own status. * An order that is already Completed keeps the status WooCommerce passed in. * * @param bool $completed True when the WooCommerce order is already Completed. * @param array $settings */ public static function status_for_paid_order( $default_status, $billing_country, $skip_av, $completed, $existing_tag, array $settings, $apply_non_uk ) { if ( self::should_start_age_check( $billing_country, $skip_av, $completed, $existing_tag ) ) { return self::AV_PENDING_STATUS; } if ( ! $completed && $apply_non_uk && ! $skip_av && 'GB' !== strtoupper( (string) $billing_country ) ) { $mapped = self::mapped_status_for_result( 'non_uk_user', $settings ); if ( '' !== $mapped ) { return $mapped; } } return $default_status; } /** * Lowercase result statuses whose WooCommerce label matches the posted status. * * Posted values look like wc-processing or wc-on-hold. The wc- prefix is * removed and the rest of the slug is compared with the saved label. * Hyphens and underscores are treated as spaces, so wc-on-hold and * wc-tobacco_refused match "On hold" and "Tobacco refused". * * @return string[] */ public static function matched_results( $posted_status, array $settings ) { $matched = array(); if ( ! isset( $settings['oneacc_status'], $settings['one_acc_user_status'] ) || ! is_array( $settings['oneacc_status'] ) || ! is_array( $settings['one_acc_user_status'] ) ) { return $matched; } if ( self::is_completed_status( $posted_status ) ) { return $matched; } $slug = strtolower( (string) $posted_status ); if ( 0 === strpos( $slug, 'wc-' ) ) { $slug = substr( $slug, 3 ); } $normalized_slug = str_replace( array( '-', '_' ), ' ', $slug ); foreach ( $settings['one_acc_user_status'] as $key => $user_status ) { if ( self::is_fixed_result( $user_status ) || ! isset( $settings['oneacc_status'][ $key ] ) ) { continue; } $label = str_replace( array( '-', '_' ), ' ', strtolower( $settings['oneacc_status'][ $key ] ) ); if ( $normalized_slug === $label ) { $matched[] = strtolower( str_replace( ' ', '_', $user_status ) ); } } return $matched; } public static function status_after_72_hours( $created_timestamp, $now, $current_status ) { $deadline = (int) $created_timestamp + ( 72 * 3600 ); if ( (int) $now >= $deadline && $current_status != 'av_success' ) { return 'av_failed'; } return $current_status; } /** * Whether this order should call 1account. * A customer's saved verification status is not an input. * * @param string $billing_country Billing country code, for example GB. * @param bool $skip_av True when every item is SKIP_AV and none is tobacco. * @param bool $completed True when the WooCommerce order is Completed. * @param string $existing_tag av_order_tag_key already stored on the order. */ public static function should_start_age_check( $billing_country, $skip_av, $completed, $existing_tag ) { if ( $skip_av || $completed ) { return false; } if ( 'GB' !== strtoupper( (string) $billing_country ) ) { return false; } $tag = strtolower( str_replace( array( ' ', '-' ), '_', (string) $existing_tag ) ); $finished = array( 'av_success', 'av_pass', 'av_failed', 'av_fail', 'av_skipped', 'tobacco_refused', 'non_uk_user', 'no_uk_user' ); return ! in_array( $tag, $finished, true ); } /** * Thank-you page fallback for the incomplete-record create. * Payment hooks create the record when they run. A gateway can show this * page before its webhook marks the order paid, so that order still creates * here. BACS and cheque are not paid at checkout; a later paid status creates * the record. * * @param string $payment_method Gateway id, for example bacs or stripe. * @param bool $is_paid True when WooCommerce treats the order as paid. */ public static function thankyou_should_create_record( $payment_method, $is_paid ) { if ( $is_paid ) { return true; } $method = strtolower( (string) $payment_method ); return 'bacs' !== $method && 'cheque' !== $method; } /** * @param array{has_tobacco?: bool, all_no_av?: bool} $tags * @return array{client_id: string, client_secret: string, skip_av: string} */ public static function script_choice( array $tags, $client_id, $tobacco_client_id, $client_secret = '', $tobacco_client_secret = '' ) { $selected = $client_id; $secret = $client_secret; if ( ! empty( $tags['has_tobacco'] ) && $tobacco_client_id ) { $selected = $tobacco_client_id; $secret = $tobacco_client_secret; } $skip = ! empty( $tags['all_no_av'] ) && empty( $tags['has_tobacco'] ); return array( 'client_id' => $selected, 'client_secret' => $secret, 'skip_av' => $skip ? 'yes' : 'no', ); } /** * Whether checkout must collect a date of birth. * Always-request wins over the tobacco rule. * * @param bool $always Always request date of birth at checkout. * @param bool $tobacco_enabled Request date of birth for tobacco purchases. * @param string $tobacco_project_id Tobacco Project ID. * @param bool $has_tobacco Cart contains a TOBACCO product. */ public static function should_request_checkout_dob( $always, $tobacco_enabled, $tobacco_project_id, $has_tobacco ) { if ( $always ) { return true; } return (bool) $tobacco_enabled && '' !== trim( (string) $tobacco_project_id ) && (bool) $has_tobacco; } /** * A checkout date of birth on or before today. * Accepts YYYY-MM-DD, or a UK date DD/MM/YYYY. The stored value is YYYY-MM-DD. * An empty string means the value cannot be stored or sent. * * @param string $value Posted date. * @param string $today Today's date, YYYY-MM-DD. */ public static function valid_checkout_dob( $value, $today ) { $value = trim( (string) $value ); $iso = ''; if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $value ) ) { $iso = $value; } elseif ( preg_match( '/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/', $value, $parts ) ) { $iso = sprintf( '%04d-%02d-%02d', (int) $parts[3], (int) $parts[2], (int) $parts[1] ); } if ( '' === $iso ) { return ''; } $date = \DateTime::createFromFormat( '!Y-m-d', $iso ); if ( ! $date || $date->format( 'Y-m-d' ) !== $iso ) { return ''; } if ( $iso > (string) $today ) { return ''; } return $iso; } /** * The push iframe date box expects DD/MM/YYYY. An ISO value is read as digits, * so 1990-01-01 is shown as 19/90/0101. * * @param string $value Posted or stored date. * @param string $today Today's date, YYYY-MM-DD. */ public static function checkout_dob_for_iframe( $value, $today ) { $iso = self::valid_checkout_dob( $value, $today ); if ( '' === $iso ) { return ''; } return substr( $iso, 8, 2 ) . '/' . substr( $iso, 5, 2 ) . '/' . substr( $iso, 0, 4 ); } /** * Combine a UK day, month, and year into YYYY-MM-DD. * * @param string $day Day, 1-31. * @param string $month Month, 1-12. * @param string $year Four-digit year. * @param string $today Today's date, YYYY-MM-DD. */ public static function checkout_dob_from_parts( $day, $month, $year, $today ) { $day = trim( (string) $day ); $month = trim( (string) $month ); $year = trim( (string) $year ); if ( '' === $day || '' === $month || '' === $year ) { return ''; } return self::valid_checkout_dob( $day . '/' . $month . '/' . $year, $today ); } /** * Checkout block rules that show and require the date field when the cart * contains one of these product or variation IDs. * Draft-07 has no "contains" keyword, so "at least one item is in the list" * is expressed by negating "every item is outside the list". * * @param array $product_ids Tobacco product and variation IDs. * @return array{required: array, hidden: array}|null Null when there is nothing to match. */ public static function tobacco_checkout_field_schema( array $product_ids ) { $ids = array(); foreach ( $product_ids as $product_id ) { $product_id = (int) $product_id; if ( $product_id > 0 ) { $ids[] = $product_id; } } $ids = array_values( array_unique( $ids ) ); if ( ! $ids ) { return null; } $in_cart = array( 'enum' => $ids ); return array( 'required' => array( 'type' => 'object', 'required' => array( 'cart' ), 'properties' => array( 'cart' => array( 'type' => 'object', 'required' => array( 'items' ), 'properties' => array( 'items' => array( 'type' => 'array', 'not' => array( 'items' => array( 'not' => $in_cart, ), ), ), ), ), ), ), 'hidden' => array( 'type' => 'object', 'required' => array( 'cart' ), 'properties' => array( 'cart' => array( 'type' => 'object', 'required' => array( 'items' ), 'properties' => array( 'items' => array( 'type' => 'array', 'items' => array( 'not' => $in_cart, ), ), ), ), ), ), ); } /** * A failed check stays AV_FAILED even when noTobacco is set. Tobacco refused * is only a successful check where the customer declined tobacco. * * @return array{status: string, user_status: string, order_tag: string} */ public static function thankyou_outcome( $posted_status, $no_tobacco_value, $no_tobacco_present ) { $status = strtolower( str_replace( array( ' ', '-' ), '_', (string) $posted_status ) ); $no_tobacco = $no_tobacco_present && $no_tobacco_value !== '' && $no_tobacco_value !== 'false' && $no_tobacco_value !== '0' && $no_tobacco_value !== false; $passed = in_array( $status, array( 'av_success', 'av_pass', 'success' ), true ); $failed = in_array( $status, array( 'av_failed', 'av_fail', 'failed', 'fail' ), true ); if ( ( $no_tobacco && $passed ) || $status === 'tobacco_refused' ) { $status = 'tobacco_refused'; } elseif ( $passed ) { $status = 'av_success'; } elseif ( $failed ) { $status = 'av_failed'; } $order_tag = ''; if ( $status === 'tobacco_refused' ) { $order_tag = 'TOBACCO_REFUSED'; } elseif ( $status === 'av_success' ) { $order_tag = 'AV_SUCCESS'; } elseif ( $status === 'av_failed' ) { $order_tag = 'AV_FAILED'; } return array( 'status' => $status, 'user_status' => ( $status === 'av_success' ) ? 'av_success' : '', 'order_tag' => $order_tag, ); } public static function incomplete_item( $name, $description ) { return array( 'itemName' => $name, 'itemDescription' => $description, ); } public static function incomplete_create_payload( $email, $phone, $order_id, array $items, $av_url, $customer_name, $store_url ) { return array( 'userEmail' => $email, 'userPhone' => $phone, 'orderId' => $order_id, 'items' => $items, 'avUrl' => $av_url, 'platformId' => 'WOO', 'customerName' => $customer_name, 'storeUrl' => $store_url, 'keyVersion' => self::INCOMPLETE_AV_KEY_VERSION, ); } public static function incomplete_update_payload( $order_id, $result_status, $store_url ) { return array( 'orderId' => $order_id, 'status' => strtoupper( (string) $result_status ), 'platformId' => 'WOO', 'storeUrl' => $store_url, 'keyVersion' => self::INCOMPLETE_AV_KEY_VERSION, ); } /** * Callback WooCommerce posts the new REST key to. storeUrl and installToken * travel on the query string because the body is fixed by WooCommerce. * * @param string $install_endpoint Absolute platforms URL, without a query string. * @param string $store_url Shop home URL. * @param string $install_token Token stored in WordPress before the redirect. */ public static function install_callback_url( $install_endpoint, $store_url, $install_token ) { return $install_endpoint . '?' . http_build_query( array( 'storeUrl' => $store_url, 'installToken' => $install_token, ), '', '&', PHP_QUERY_RFC3986 ); } /** * Body posted when the merchant saves Project ID and Tobacco Project ID. * tobaccoProjectId is omitted when that field is blank. * * @param string $store_url Shop home URL. * @param string $install_token Token stored before the WooCommerce approval. * @param string $project_id Project ID. Empty clears it. * @param string $project_secret Project Secret. Sent only with a project id. * @param string $tobacco_project_id Tobacco Project ID. * @param string $tobacco_project_secret Tobacco Project Secret. Sent only with a tobacco id. * @param string $orders_url WooCommerce orders collection URL. * @return array */ public static function projects_payload( $store_url, $install_token, $project_id, $project_secret, $tobacco_project_id, $tobacco_project_secret, $orders_url ) { $project = trim( (string) $project_id ); $payload = array( 'storeUrl' => (string) $store_url, 'installToken' => (string) $install_token, 'projectId' => $project, 'ordersUrl' => (string) $orders_url, ); if ( '' !== $project ) { $payload['projectSecret'] = (string) $project_secret; } $tobacco = trim( (string) $tobacco_project_id ); if ( '' !== $tobacco ) { $payload['tobaccoProjectId'] = $tobacco; $payload['tobaccoProjectSecret'] = (string) $tobacco_project_secret; } return $payload; } /** * Admin notice when a project-link save did not reach 1account. * Empty when the store is disconnected, or when the request succeeded. * * A disconnected save stays silent. Date of birth and order status can still be saved. * * @param bool $store_connected Whether WooCommerce still has the REST key. * @param bool $has_install_token Whether the install token option is set. * @param int $http_code Response status. 0 when the request did not complete. Ignored until the store is connected and the token is set. * @return string */ public static function project_link_failure_message( $store_connected, $has_install_token, $http_code ) { if ( ! $store_connected ) { return ''; } if ( ! $has_install_token ) { return 'Settings were saved, but the project IDs were not sent to 1Account. Connect the store again.'; } $code = (int) $http_code; if ( $code >= 200 && $code < 300 ) { return ''; } return 'Settings were saved, but the project ID or secret was not accepted.'; } /** * Logged-in admin URL that asks WooCommerce to create a read/write REST key. * * @param string $store_url Shop home URL, no trailing slash required. * @param string $user_id Current admin id. WooCommerce echoes it back. * @param string $return_url Settings screen to open after approval. * @param string $callback_url Absolute callback from install_callback_url(). */ /** * Name WooCommerce stores on the REST key it creates at approval. * The key description is "{app name} - API ({time})". */ public static function install_app_name() { return '1Account'; } /** * Start of the REST key description. Uninstall and the settings screen match on this. */ public static function install_api_key_description_prefix() { return self::install_app_name() . ' - API'; } /** * Project ID and secret options. Delete removes them with the 1account store row. * Deactivate leaves them, because that store row and its project links stay. * * @return string[] */ public static function project_credential_options() { return array( 'wc_oneacc_settings_client_id', 'wc_oneacc_settings_client_secret', 'wc_oneacc_settings_tobacco_client_id', 'wc_oneacc_settings_tobacco_client_secret', ); } public static function install_authorize_url( $store_url, $user_id, $return_url, $callback_url ) { $base = rtrim( (string) $store_url, '/' ) . '/wc-auth/v1/authorize'; return $base . '?' . http_build_query( array( 'app_name' => self::install_app_name(), 'scope' => 'read_write', 'user_id' => $user_id, 'return_url' => $return_url, 'callback_url' => $callback_url, ), '', '&', PHP_QUERY_RFC3986 ); } }