PluginProbe
Pay with Vipps and MobilePay for WooCommerce / 6.3.1
Pay with Vipps and MobilePay for WooCommerce v6.3.1
6.3.1 6.2.6 6.3.0 6.2.5 6.2.4 6.2.3 6.2.2 6.2.1 6.2.0 6.1.10 6.1.9 6.1.8 6.1.7 6.1.6 6.1.5 6.1.4 6.1.3 6.1.2 6.1.1 6.1.0 6.0.5 6.0.4 6.0.3 6.0.2 6.0.1 All 190 releases
← All changes | payment/Vipps.class.php +530 -583 6.2.3 → 6.3.1 View file →
@@ -54,11 +54,8 @@
54 54
55 55 // True if HPOS is being used
56 56 public $HPOSActive = null;
57 57
58 - // used in the fake locking mechanism using transients
59 - private $lockKey = null;
60 -
61 58 public $vippsJSConfig = array();
62 59
63 60 public $button_options_version = '2.0';
64 61 public $button_options_express_version = '2.0';
@@ -117,9 +114,10 @@
117 114 add_action('wp_footer', array($Vipps,'footer'));
118 115 }
119 116 add_action( 'plugins_loaded', array($Vipps,'plugins_loaded'));
120 117 add_action( 'after_setup_theme', array($Vipps,'after_setup_theme'));
121 - add_action('init',array($Vipps,'init'));
118 + add_action( 'init',array($Vipps,'init'));
119 + add_action( 'rest_api_init', array($Vipps, 'rest_api_init'));
122 120 add_action( 'woocommerce_loaded', array($Vipps,'woocommerce_loaded'));
123 121 add_filter( 'woocommerce_available_payment_gateways', array($Vipps, 'payment_gateway_filter'));
124 122 add_action( 'woocommerce_blocks_loaded', [$Vipps, 'woocommerce_blocks_loaded']);
125 123 // Express Checkout and Checkout supports the new pickup_location shipping method, but the admin interface for this may
@@ -227,8 +225,9 @@
227 225 // Register certain scripts in wp_loaded because they will be added to the backend as well - the gutenberg checkout block
228 226 // needs these to be defined in the backend. IOK 2024-04-16
229 227 add_action('wp_loaded', array($this, 'wp_register_scripts'));
230 228 add_action('wp_enqueue_scripts', array($this, 'wp_enqueue_scripts'));
229 + add_action('wp_enqueue_scripts', array($this, 'enqueue_classic_checkout_scripts'), 20);
231 230
232 231 // Remove the possibility of restarting failed orders etc. This will be fixed in the future. IOK 2023-05-26
233 232 add_filter('woocommerce_my_account_my_orders_actions', array($this,'woocommerce_my_account_my_orders_actions'), 10, 2);
234 233
@@ -244,16 +243,8 @@
244 243
245 244 // Extra order actions on the order screen, now using ajax to be compatible with HPOS. IOK 2022-12-02
246 245 add_action('wp_ajax_woo_vipps_order_action', array($this, 'order_handle_vipps_action'));
247 246
248 - // Fetch wc products, but filter those only purchasable by VMP express checkout. LP 2026-01-22
249 - add_action('rest_api_init', function() {
250 - register_rest_route(self::get_rest_namespace('v1'), '/express-products', [
251 - 'methods' => 'GET',
252 - 'callback' => [$this, 'rest_express_checkout_products'],
253 - 'permission_callback' => '__return_true',
254 - ]);
255 - });
256 247
257 248 // We need a 5-minute scheduled event for the handler for missed callbacks. Using the
258 249 // action scheduler would be better, but we can't do that just yet because of backwards
259 250 // compatibility. At some point, support for older woo-versions should be dropped; then this
@@ -276,15 +267,8 @@
276 267 // because it is self-updating or because it has been deactivated just now or something, we won't have access to it.
277 268 // Therefore test it first. IOK 2022-12-08
278 269 $gw = $this->gateway();
279 270
280 - // This is a developer-mode level feature because flock() is not portable. This ensures callbacks and shopreturns do not
281 - // simultaneously update the orders, in particular not the express checkout order lines wrt shipping. IOK 2020-05-19
282 - if ($gw && $gw->get_option('use_flock') == 'yes') {
283 - add_filter('woo_vipps_lock_order', array($this,'flock_lock_order'));
284 - add_action('woo_vipps_unlock_order', array($this, 'flock_unlock_order'));
285 - }
286 -
287 271 // Set default button options, migrating any older setup IOK 2026-07-15
288 272 $this->init_button_options();
289 273
290 274 /*
@@ -314,9 +298,32 @@
314 298 add_action('woo_vipps_before_handling_special_page', array($this, 'pre_special_page_actions'));
315 299
316 300 // Add an admin interface for this page as well IOK 2026-09-11
317 301 add_action('woocommerce_settings_pages', array($this, 'woocommerce_settings_pages'));
302 + }
318 303
304 +
305 + public function rest_api_init () {
306 +
307 + // Fetch wc products, but filter those only purchasable by VMP express checkout. LP 2026-01-22
308 + register_rest_route(self::get_rest_namespace('v1'), '/express-products', [
309 + 'methods' => 'GET',
310 + 'callback' => [$this, 'rest_express_checkout_products'],
311 + 'permission_callback' => '__return_true',
312 + ]);
313 +
314 + // Start a single product express checkout process. IOK 2026-08-25
315 + register_rest_route(self::get_rest_namespace('v1'), '/express_checkout_single', [
316 + 'methods' => 'POST',
317 + 'callback' => [$this, 'rest_do_single_product_express_checkout'],
318 + 'permission_callback' => '__return_true',
319 + ]);
320 + // And one for the cart. IOK 2026-09-04
321 + register_rest_route(self::get_rest_namespace('v1'), '/express_checkout', [
322 + 'methods' => 'POST',
323 + 'callback' => [$this, 'rest_do_express_checkout'],
324 + 'permission_callback' => '__return_true',
325 + ]);
319 326 }
320 327
321 328 public function admin_init () {
322 329 $gw = $this->gateway();
@@ -345,10 +352,8 @@
345 352 // Styling etc
346 353 add_action('admin_head', array($this, 'admin_head'));
347 354
348 355 // Scripts
349 - $this->vippsJSConfig['vippssecnonce'] = wp_create_nonce('vippssecnonce');
350 - wp_localize_script('vipps-gw', 'VippsConfig', $this->vippsJSConfig);
351 356 add_action('admin_enqueue_scripts', array($this,'admin_enqueue_scripts'));
352 357
353 358 // IOK 2026-05-26 redirect the old Woo-generated settings-screen to our own settings page.
354 359 add_action('current_screen', function ($screen) {
@@ -1043,12 +1048,30 @@
1043 1048
1044 1049 public function get_html_button_attrs_for_context($context = 'global') {
1045 1050 $options = get_option('vipps_button_options2', []);
1046 1051 if (!is_string($context)) $context = 'global';
1052 +
1053 + // Gutenberg express checkout buttons really want to be stretched, so we'll treat them somewhat differently.
1054 + $gutenberg = false;
1055 + if ($context == 'checkout_gutenberg') {
1056 + $context = 'checkout';
1057 + $gutenberg = true;
1058 + }
1059 + if ($context == 'cart_gutenberg') {
1060 + $context = 'cart';
1061 + $gutenberg = true;
1062 + }
1063 +
1047 1064 $config = $options['express']['configs'][$context] ?? [];
1048 - if (!$config || ($config['use-global-config'] ?? false)) {
1065 + $use_global = !$config || ($config['use-global-config'] ?? false);
1066 + if ($use_global) {
1049 1067 $config = $options['express']['configs']['global'] ?? $this->get_html_button_default_attrs();
1050 1068 }
1069 +
1070 + // see above.
1071 + if ($gutenberg) {
1072 + $config['stretched']='true';
1073 + }
1051 1074 return $config;
1052 1075 }
1053 1076
1054 1077 public function get_html_button_for_context($context = 'global') {
@@ -1068,8 +1091,10 @@
1068 1091 // Don't support these login verbs. LP 2026-06-04
1069 1092 if (in_array($attrs['verb'], ['login', 'register'])) $attrs['verb'] = 'buy';
1070 1093 // Looks like button and badge web components now use 'da' instead of 'dk' for danish. LP 2026-08-11
1071 1094 if ('dk' === $attrs['language']) $attrs['language'] = 'da';
1095 + // Fix swedish too. LP 2026-10-06
1096 + if ('se' === $attrs['language']) $attrs['language'] = 'sv';
1072 1097
1073 1098 $escaped_attrs = [];
1074 1099 foreach($attrs as $k => $v) {
1075 1100 $escaped_attrs[$k] = esc_attr($v);
@@ -1135,8 +1160,10 @@
1135 1160 private function button_menu_express_section() {
1136 1161 $options = get_option('vipps_button_options2', []);
1137 1162 $express = $options['express'] ?? [];
1138 1163 $configs = $express['configs'] ?? [];
1164 +
1165 +
1139 1166 $contexts = [
1140 1167 'global' => __('Global', 'woo-vipps'),
1141 1168 'product' => __('Product', 'woo-vipps'),
1142 1169 'catalog' => __('Catalog', 'woo-vipps'),
@@ -1309,8 +1336,9 @@
1309 1336
1310 1337 // Swap to new context: set all input fields to the stored values if exists. LP 2026-06-25
1311 1338 const newContext = jQuery("#context").val();
1312 1339 const newConfig = contextConfigs[newContext];
1340 +
1313 1341 setInputsFromConfig(newContext, newConfig);
1314 1342 currentContext = newContext;
1315 1343 }
1316 1344
@@ -1673,12 +1701,14 @@
1673 1701 <?php
1674 1702 }
1675 1703 // Scripts used in the backend
1676 1704 public function admin_enqueue_scripts($hook) {
1705 +
1706 + wp_register_script('vipps-admin',plugins_url('js/admin.js',__FILE__),array('jquery'),filemtime(dirname(__FILE__) . "/js/admin.js"), 'all');
1707 + $this->vippsJSConfig['vippssecnonce'] = wp_create_nonce('vippssecnonce');
1708 + wp_localize_script('vipps-admin', 'VippsConfig', $this->vippsJSConfig);
1677 1709 // Add certain translations very late so translation plugins get a chance to work. IOK 2026-02-02
1678 - $this->script_add_vippslocale();
1679 -
1680 - wp_register_script('vipps-admin',plugins_url('js/admin.js',__FILE__),array('jquery','vipps-gw'),filemtime(dirname(__FILE__) . "/js/admin.js"), 'all');
1710 + $this->script_add_vippslocale('vipps-admin');
1681 1711 wp_enqueue_script('vipps-admin');
1682 1712
1683 1713 wp_enqueue_style('vipps-admin-style',plugins_url('css/admin.css',__FILE__),array(),filemtime(dirname(__FILE__) . "/css/admin.css"), 'all');
1684 1714 wp_enqueue_style('vipps-fonts');
@@ -1748,12 +1778,9 @@
1748 1778
1749 1779 public function wp_register_scripts () {
1750 1780 // We are going to use the 'hooks' library introduced by WP 5.1, but we still support WP 4.7. So if this isn't enqueues
1751 1781 // (which it only is if Gutenberg is active) or not provided at all, add it now.
1752 - if (!wp_script_is( 'wp-hooks', 'registered')) {
1753 - wp_register_script('wp-hooks', plugins_url('/compat/hooks.min.js', __FILE__));
1754 - }
1755 - wp_register_script('vipps-gw',plugins_url('js/vipps.js',__FILE__),array('jquery','wp-hooks'),filemtime(dirname(__FILE__) . "/js/vipps.js"), 'true');
1782 + wp_register_script('vipps-gw',plugins_url('js/vipps.js',__FILE__),array('jquery','wp-hooks', 'wp-api-fetch','vipps-widget-sdk'),filemtime(dirname(__FILE__) . "/js/vipps.js"), true);
1756 1783
1757 1784 // Badges - web components provided by Vipps MobilePay to display payment options in-store.
1758 1785 wp_register_script('vipps-onsite-messageing',
1759 1786 plugins_url('js/vipps-on-site-messaging.js', WC_VIPPS_PAYMENT_MAIN_FILE),
@@ -1759,13 +1786,27 @@
1759 1786 plugins_url('js/vipps-on-site-messaging.js', WC_VIPPS_PAYMENT_MAIN_FILE),
1760 1787 array(),
1761 1788 filemtime(dirname(WC_VIPPS_PAYMENT_MAIN_FILE) . '/js/vipps-on-site-messaging.js'),
1762 1789 [
1763 - 'in_footer' => true,
1764 - 'strategy' => 'async',
1790 + 'in_footer' => true,
1791 + 'strategy' => 'async',
1765 1792 ],
1766 1793 );
1767 1794
1795 + add_filter( 'script_loader_tag', function($tag, $handle,$src) {
1796 + if ($handle == 'vipps-widget-sdk') {
1797 + $tag = preg_replace("!^<script!", "<script data-vipps-widget-sdk ", $tag);
1798 + return $tag;
1799 + }
1800 + return $tag;
1801 + },10,3);
1802 +
1803 + wp_register_script('vipps-widget-sdk', "https://cdn.vippsmobilepay.com/js/widget-sdk/vipps-widget.js",
1804 + array('vipps-button-webcomponent'),
1805 + filemtime(dirname(WC_VIPPS_PAYMENT_MAIN_FILE) . '/js/vipps.js'),
1806 + ['in_footer' => true]
1807 + );
1808 +
1768 1809 // Button web component downloaded from https://cdn.vippsmobilepay.com/js/button/button.js. LP 2026-06-24
1769 1810 wp_register_script('vipps-button-webcomponent',
1770 1811 plugins_url('js/vipps-button.js', WC_VIPPS_PAYMENT_MAIN_FILE),
1771 1812 array(),
@@ -1771,27 +1812,45 @@
1771 1812 array(),
1772 1813 filemtime(dirname(WC_VIPPS_PAYMENT_MAIN_FILE) . '/js/vipps-button.js'),
1773 1814 [
1774 1815 'in_footer' => false
1775 - ],
1816 + ]
1776 1817 );
1777 1818 }
1778 1819
1779 1820 // Runs late in both wp_enqueue_scripts and admin_enqueue_scripts to make it more compatible with translation plugins IOK 2026-02-02
1780 - public function script_add_vippslocale () {
1821 + public function script_add_vippslocale ($handle) {
1781 1822 // This is actually for the payment block, where localize script has started to not-work in certain contexts. IOK 2022-12-13
1823 + $name = $this->get_payment_method_name();
1782 1824 $strings = array(
1783 - 'Continue with Vipps'=>sprintf(__('Continue with %1$s', 'woo-vipps'), $this->get_payment_method_name()),
1784 - 'Vipps'=> sprintf(__('%1$s', 'woo-vipps'), $this->get_payment_method_name()),
1785 - 'pay_with_card' => sprintf(__('Pay with card through %1$s', 'woo-vipps'), $this->get_payment_method_name()),
1825 + 'Continue with Vipps'=>sprintf(__('Continue with %1$s', 'woo-vipps'), $name),
1826 + 'Vipps'=> sprintf(__('%1$s', 'woo-vipps'), $name),
1827 + 'pay_with_card' => sprintf(__('Pay with card through %1$s', 'woo-vipps'), $name),
1828 + 'termsAndConditionsError' => __( 'Please read and accept the terms and conditions to proceed with your order.', 'woocommerce' ),
1829 + 'temporaryError' => sprintf(__('%1$s is temporarily unavailable.','woo-vipps'),$name),
1830 + 'successMessage' => sprintf(__('To the %1$s app!','woo-vipps'), $name),
1831 + 'cancel'=> __("Cancel", 'woo-vipps'),
1832 + 'close'=> __("Close", 'woo-vipps'),
1833 + 'missingPaymentUrl'=> __("Successful checkout response has no payment URL", 'woo-vipps'),
1834 + 'expressCheckoutFailed'=> __("Express checkout failed", 'woo-vipps'),
1835 + 'unexpectedCheckoutResponse'=> __("Unexpected express checkout response", 'woo-vipps'),
1836 + 'vippsCheckoutFailed'=> __("Vipps Mobilepay checkout failed", 'woo-vipps'),
1837 + 'correctHighlightedFields'=> __("Please correct the highlighted fields.", 'woo-vipps'),
1838 + 'checkFormBeforeContinuing'=> __("Please check the form before continuing.", 'woo-vipps'),
1839 + 'cartCheckoutUnavailable'=> __("Cannot start express checkout: cart checkout is unavailable", 'woo-vipps'),
1840 + 'productIdentifiersMissing'=> __("Cannot buy product: product id, variation id and sku are missing", 'woo-vipps'),
1841 + 'productFormNotFound'=> __("Cannot buy product: product form not found", 'woo-vipps'),
1842 + 'paymentSuccessfulRedirecting' => __("Payment successful. Redirecting…", 'woo-vipps'),
1786 1843 );
1787 - wp_localize_script('vipps-gw', 'VippsLocale', $strings);
1844 + wp_localize_script($handle, 'VippsLocale', $strings);
1788 1845 }
1789 1846
1790 1847 public function wp_enqueue_scripts() {
1848 + // Add late: if this value isn't 'yes' we wil not add order attribution to express orders. IOK 2026-09-10
1849 + $this->vippsJSConfig['expressOrderAttribution'] = $this->gateway()->get_option('vippsorderattribution');
1791 1850 wp_localize_script('vipps-gw', 'VippsConfig', $this->vippsJSConfig);
1792 1851 // Add certain translations very late so translation plugins get a chance to work. IOK 2026-02-02
1793 - $this->script_add_vippslocale();
1852 + $this->script_add_vippslocale('vipps-gw');
1794 1853
1795 1854 wp_enqueue_script('vipps-gw');
1796 1855 wp_enqueue_style('vipps-gw',plugins_url('css/vipps.css',__FILE__),array(),filemtime(dirname(__FILE__) . "/css/vipps.css"));
1797 1856 wp_enqueue_script('vipps-button-webcomponent');
@@ -1796,13 +1855,55 @@
1796 1855 wp_enqueue_style('vipps-gw',plugins_url('css/vipps.css',__FILE__),array(),filemtime(dirname(__FILE__) . "/css/vipps.css"));
1797 1856 wp_enqueue_script('vipps-button-webcomponent');
1798 1857 }
1799 1858
1859 + // These scripts should be loaded only on the checkout screen and is used only for the classic shortcode checkout and
1860 + // the pay-for-order screen. IOK 2026-09-15
1861 + public function enqueue_classic_checkout_scripts () {
1862 + if ( ! function_exists( 'is_checkout' ) || ! is_checkout() || is_order_received_page() ) {
1863 + return;
1864 + }
1865 + // Order-pay is rendered by the classic form even with a Blocks checkout page.
1866 + // It must bypass the check for the parent checkout page's block content.
1867 + if ( ! is_checkout_pay_page() ) {
1868 + $utils = '\\Automattic\\WooCommerce\\Blocks\\Utils\\CartCheckoutUtils';
1869 + $uses_checkout_block = is_callable( array( $utils, 'is_checkout_block_default' ) )
1870 + ? $utils::is_checkout_block_default()
1871 + : has_block( 'woocommerce/checkout', wc_get_page_id( 'checkout' ) );
1800 1872
1873 + if ( $uses_checkout_block ) {
1874 + return;
1875 + }
1876 + }
1877 +
1878 + // This script uses jQuery because the classic checkout screen does too. IOK 2026-09-15
1879 + $relative_path = 'js/vipps-classic-checkout.js';
1880 + wp_enqueue_script(
1881 + 'vipps-classic-checkout',
1882 + plugins_url( $relative_path, __FILE__ ),
1883 + array( 'jquery', 'wc-checkout', 'vipps-gw' ),
1884 + filemtime( plugin_dir_path( __FILE__ ) . $relative_path ),
1885 + true
1886 + );
1887 +
1888 + if ( is_checkout_pay_page() ) {
1889 + $order = wc_get_order( absint( get_query_var( 'order-pay' ) ) );
1890 + wp_add_inline_script( 'vipps-classic-checkout', 'window.VippsOrderPayConfig = ' . wp_json_encode( array(
1891 + 'orderId' => $order ? $order->get_id() : 0,
1892 + 'orderKey' => $order ? $order->get_order_key() : '',
1893 + 'billingEmail' => $order ? $order->get_billing_email() : '',
1894 + 'endpoint' => $order ? rest_url( 'wc/store/v1/checkout/' . $order->get_id() ) : '',
1895 + 'nonce' => wp_create_nonce( 'wc_store_api' ),
1896 + 'billingAddress' => $order ? $order->get_address( 'billing' ) : array(),
1897 + 'shippingAddress' => $order ? $order->get_address( 'shipping' ) : array(),
1898 + ) ) . ';', 'before' );
1899 + }
1900 + }
1901 +
1902 +
1801 1903 public function add_shortcodes() {
1802 1904 add_shortcode('woo_vipps_buy_now', array($this, 'buy_now_button_shortcode'));
1803 1905 add_shortcode('woo_vipps_express_checkout_button', array($this, 'express_checkout_button_shortcode'));
1804 - add_shortcode('woo_vipps_express_checkout_banner', array($this, 'express_checkout_banner_shortcode'));
1805 1906
1806 1907 // Badges, if using shortcodes
1807 1908 // New vipps-mobilepay-badge shortcode. LP 19.11.2024
1808 1909 add_shortcode('vipps-mobilepay-badge', array($this, 'vipps_mobilepay_badge_shortcode'));
@@ -1848,83 +1949,57 @@
1848 1949 public function express_checkout_section_html() {
1849 1950 $payment_method = $this->get_payment_method_name();
1850 1951 $header_text = __('Express Checkout', 'woo-vipps');
1851 1952 $header = "<legend class='express-header'>$header_text</legend>";
1852 - $div_classes = "legacy-checkout vipps-express-checkout $payment_method";
1953 + $div_classes = "legacy-checkout express $payment_method";
1853 1954 echo "<fieldset class='$div_classes'>$header";
1854 1955 $this->checkout_express_checkout_button_html();
1855 1956 echo '</fieldset>';
1856 1957 }
1857 1958
1858 - public function express_checkout_banner() {
1959 + // Show the express button if reasonable to do so
1960 + public function cart_express_checkout_button() {
1859 1961 $gw = $this->gateway();
1860 - if (!$gw->show_express_checkout()) return;
1861 - return $this->express_checkout_banner_html();
1862 - }
1863 1962
1864 - public function express_checkout_banner_html() {
1865 - $url = $this->express_checkout_url();
1866 - $url = wp_nonce_url($url,'express','sec');
1867 - $text = __('Skip entering your address and just checkout using', 'woo-vipps');
1868 - $linktext = 'Express'; // dont translate. LP 2025-09-03
1869 - $logo = $this->get_express_banner_logo();
1870 - $payment_method = $this->get_payment_method_name();
1871 -
1872 - $img_classes = 'express-banner-logo inline negative ' . strtolower($payment_method) . '-logo';
1873 - $div_classes = 'woocommerce-info ' . strtolower($payment_method) . '-info';
1874 - $a_classes = 'express-banner-link ' . strtolower($payment_method) . '-link';
1875 -
1876 - $message = $text . "<a href='$url' class='$a_classes'><img class='$img_classes' border=0 src='$logo' alt='$payment_method'/>$linktext!</a>";
1877 - $message = apply_filters('woo_vipps_express_checkout_banner', $message, $url, $payment_method);
1878 - ?>
1879 - <div class="<?php echo $div_classes;?>"><?php echo $message;?></div>
1880 - <?php
1963 + if ($gw->show_express_checkout()){
1964 + return $this->cart_express_checkout_button_html();
1965 + }
1881 1966 }
1882 1967
1883 - public function checkout_express_checkout_button() {
1968 + public function minicart_express_checkout_button() {
1884 1969 $gw = $this->gateway();
1885 1970
1886 1971 if ($gw->show_express_checkout()){
1887 - return $this->checkout_express_checkout_button_html();
1972 + return $this->cart_express_checkout_button_html('minicart');
1888 1973 }
1889 1974 }
1890 1975
1891 - public function checkout_express_checkout_button_html() {
1892 - $url = $this->express_checkout_url();
1893 - $url = wp_nonce_url($url,'express','sec');
1894 - $button= apply_filters('woo_vipps_express_checkout_button', $this->get_html_button_for_context('checkout'));
1976 + // This is for the Vipps SDK button used instead of the normal "pay for order" and "confirm order" buttons
1977 + // on the classic checkout and pay-for-order pages. It gets swapped in when the user selects vipps, and swapped out otherwise.
1978 + public function add_checkout_button_for_classic () {
1979 + $button = $this->get_html_button_for_context('checkout');
1980 + $submit = "<div class='vipps-classic-checkout-container'><button id='vipps-classic-checkout-submit' class='hidden vipps-submit-wrapper' type='submit'>$button</button></div>";
1981 + echo $submit;
1982 + }
1983 +
1984 + public function cart_express_checkout_button_html($context= 'cart') {
1985 + $button = apply_filters('woo_vipps_express_checkout_button', $this->get_html_button_for_context($context));
1895 1986 $method = $this->get_payment_method_name();
1896 1987 $title = sprintf(__('Buy now with %1$s!', 'woo-vipps'), $method);
1897 - $html = "<a href='$url' class='vipps-express-checkout short $method' title='$title'>$button</a>";
1988 + $url = "#";
1989 + $sec = wp_create_nonce('express');
1990 + $html = "<a href='#' class='vipps-express-checkout short " . esc_attr($method) . "' title='" . esc_attr($title) . "' data-sec='" . esc_attr($sec) . "'>$button</a>";
1898 1991 $html = apply_filters('woo_vipps_cart_express_checkout_button', $html, $url);
1899 1992 echo $html;
1900 1993 }
1901 1994
1902 - // Show the express button if reasonable to do so
1903 - public function cart_express_checkout_button() {
1904 - $gw = $this->gateway();
1905 -
1906 - if ($gw->show_express_checkout()){
1907 - return $this->cart_express_checkout_button_html();
1908 - }
1909 - }
1910 -
1911 - public function minicart_express_checkout_button() {
1912 - $gw = $this->gateway();
1913 -
1914 - if ($gw->show_express_checkout()){
1915 - return $this->cart_express_checkout_button_html(true);
1916 - }
1917 - }
1918 -
1919 - public function cart_express_checkout_button_html($minicart = false) {
1920 - $url = $this->express_checkout_url();
1921 - $url = wp_nonce_url($url,'express','sec');
1922 - $context = $minicart ? 'minicart' : 'cart';
1923 - $button= apply_filters('woo_vipps_express_checkout_button', $this->get_html_button_for_context($context));
1995 + public function checkout_express_checkout_button_html() {
1996 + $button = apply_filters('woo_vipps_express_checkout_button', $this->get_html_button_for_context('checkout'));
1924 1997 $method = $this->get_payment_method_name();
1925 1998 $title = sprintf(__('Buy now with %1$s!', 'woo-vipps'), $method);
1926 - $html = "<a href='$url' class='vipps-express-checkout short $method' title='$title'>$button</a>";
1999 + $url = "#";
2000 + $sec = wp_create_nonce('express');
2001 + $html = "<a href='#' class='vipps-express-checkout short " . esc_attr($method) . "' title='" . esc_attr($title) . "' data-sec='" . esc_attr($sec) . "'>$button</a>";
1927 2002 $html = apply_filters('woo_vipps_cart_express_checkout_button', $html, $url);
1928 2003 echo $html;
1929 2004 }
1930 2005
@@ -1963,19 +2038,11 @@
1963 2038 public function express_checkout_button_shortcode() {
1964 2039 $gw = $this->gateway();
1965 2040 if (!$gw->cart_supports_express_checkout()) return;
1966 2041 ob_start();
1967 - $this->cart_express_checkout_button_html('shortcode');
2042 + $this->cart_express_checkout_button_html('cart');
1968 2043 return ob_get_clean();
1969 2044 }
1970 - // Show a banner normally shown for non-logged-in-users at the checkout page. It does not need to check if we are to show the button, obviously, but needs to see if the cart works
1971 - public function express_checkout_banner_shortcode() {
1972 - $gw = $this->gateway();
1973 - if (!$gw->cart_supports_express_checkout()) return;
1974 - ob_start();
1975 - $this->express_checkout_banner_html();
1976 - return ob_get_clean();
1977 - }
1978 2045
1979 2046 // Manage the various product meta fields
1980 2047 public function process_product_meta ($id, $post) {
1981 2048 // This is for the 'buy now' button
@@ -2501,82 +2568,9 @@
2501 2568 if ($ok) return $callbackdir;
2502 2569 return null;
2503 2570 }
2504 2571
2505 - // Unfortunately, we cannot do any form of portable locking, and we may get callbacks from Vipps arriving at the same moment as we check the status at Vipps,
2506 - // which in the very worst case, for Express Checkout orders, may lead to a double shipping line. Changing this to a queue system is non-trivial, because some of
2507 - // the operations done when modifying the order actually requires the customers session to be active. This operation will make conflicts a litte less probable
2508 - // by implementing something that isn't quite a lock, and the filter may be used to implement proper locking, using e.g. flock, where this can be used
2509 - // (non-distributed environments using unix on standard filesystems. IOK 2020-05-15
2510 - // Returns true if lock succeeds, or false.
2511 - public function lockOrder($order) {
2512 - $orderid = $order->get_id();
2513 - if (has_filter('woo_vipps_lock_order')) {
2514 - $ok = apply_filters('woo_vipps_lock_order', $order);
2515 - if (!$ok) return false;
2516 - } else {
2517 - if(get_transient('order_lock_'.$orderid)) return false;
2518 - $this->lockKey = uniqid();
2519 - set_transient('order_lock_' . $orderid, $this->lockKey, 30);
2520 - }
2521 - add_action('shutdown', function () use ($order) { global $Vipps; $Vipps->unlockOrder($order); });
2522 - return true;
2523 - }
2524 - // If the order is locked, it means it is in the process of being finalized, so for instance, we do *not* want to abandon it
2525 - // in checkout.
2526 - public function isLocked ($order) {
2527 - $orderid = $order->get_id();
2528 - $locked = get_transient('order_lock_'.$orderid);
2529 - return apply_filters('woo_vipps_order_locked', $locked, $order);
2530 - }
2531 - public function unlockOrder($order) {
2532 - $orderid = $order->get_id();
2533 - if (has_action('woo_vipps_unlock_order')) {
2534 - do_action('woo_vipps_unlock_order', $order);
2535 - } else {
2536 - if(get_transient('order_lock_'.$orderid) == $this->lockKey) {
2537 - delete_transient('order_lock_'.$orderid);
2538 - }
2539 - }
2540 - }
2541 2572
2542 - // Functions using flock() and files to lock orders. This is only guaranteed to work on certain setups, ie, non-distributed setups
2543 - // using Unix with normal filesystems (not NFS).
2544 - public function flock_lock_order($order) {
2545 - global $_orderlocks;
2546 - if (!$_orderlocks) $_orderlocks = array();
2547 - $dir = $this->callbackDir();
2548 - if (!$dir) {
2549 - $this->log(__("Cannot use flock() to lock orders: cannot create or write to directory", "woo-vipps"), 'error');
2550 - return true;
2551 - }
2552 - $fname = '.ht-vipps-lock-'.md5($order->get_order_key() . $order->get_meta('_vipps_transaction'));
2553 - $path = $dir . DIRECTORY_SEPARATOR . $fname;
2554 - touch($path);
2555 - if (!is_writable($path)) {
2556 - $this->log(__("Cannot use flock() to lock orders: cannot create lockfiles ", "woo-vipps"), 'error');
2557 - return true;
2558 - }
2559 - $handle = fopen($path, 'w+');
2560 - if (flock($handle, LOCK_EX | LOCK_NB)) {
2561 - $_orderlocks[$order->get_id()] = array($handle,$path);
2562 - return true;
2563 - }
2564 - return false;
2565 - }
2566 - public function flock_unlock_order($order) {
2567 - $orderid=$order->get_id();
2568 - global $_orderlocks;
2569 - if (!$_orderlocks) return;
2570 - if (!isset($_orderlocks[$orderid])) return;
2571 - list($handle, $path) = $_orderlocks[$orderid];
2572 - unset($_orderlocks[$orderid]);
2573 - flock($handle, LOCK_UN);
2574 - fclose($handle);
2575 - @unlink($path);
2576 - }
2577 -
2578 -
2579 2573 // Because the prefix used to create the Vipps order id is editable
2580 2574 // by the user, we will store that as a meta and use this for callbacks etc.
2581 2575 // IOK 2023-01-23 this function is no longer used, and kept only for backwards compatibility with
2582 2576 // debug filters and similar.
@@ -2665,11 +2659,17 @@
2665 2659 // Some validation is required for this action
2666 2660 if ($action == 'do_express_checkout') {
2667 2661 $this->vipps_express_checkout_consistency_check();
2668 2662 }
2663 + // These two actions require an extra script
2664 + if (in_array($action, ['buy_product','do_express_checkout'])) {
2665 + wp_enqueue_script('vipps-purchase', plugins_url('js/vipps-purchase.js',__FILE__), ['vipps-gw'],
2666 + filemtime(dirname(__FILE__) . "/js/vipps-purchase.js"),
2667 + ['in_footer'=>true]
2668 + );
2669 + }
2669 2670 }
2670 2671
2671 -
2672 2672 // Dynamic special page title depending on endpoint/action, only frontend. LP 2026-09-02
2673 2673 public function vipps_special_page_endpoint_title($title, $postid = 0) {
2674 2674 global $wp_query;
2675 2675 // Comment from woocommerce's wc_page_endpoint_title where this logic is from: LP 2026-09-02
@@ -2818,8 +2818,12 @@
2818 2818
2819 2819 add_action('woocommerce_after_add_to_cart_button', array($this, 'single_product_buy_now_button'));
2820 2820 add_action('woocommerce_after_shop_loop_item', array($this, 'loop_single_product_buy_now_button'), 20);
2821 2821
2822 + // For the classic checkout page and pay-for-order page, use a custom submit button when payment method
2823 + // is Vipps
2824 + add_action('woocommerce_review_order_after_submit', array($this, 'add_checkout_button_for_classic'));
2825 + add_action('woocommerce_pay_order_after_submit', array($this, 'add_checkout_button_for_classic'));
2822 2826
2823 2827 // Special pages and callbacks handled by template_redirect. IOK 2023-02-22
2824 2828 add_action('template_redirect', array($this,'template_redirect'),1);
2825 2829
@@ -2829,21 +2833,8 @@
2829 2833 // Ajax endpoints for checking the order status while waiting for confirmation
2830 2834 add_action('wp_ajax_nopriv_check_order_status', array($this, 'ajax_check_order_status'));
2831 2835 add_action('wp_ajax_check_order_status', array($this, 'ajax_check_order_status'));
2832 2836
2833 -
2834 - // Buying a single product directly using express checkout IOK 2018-09-28
2835 - add_action('wp_ajax_nopriv_vipps_buy_single_product', array($this, 'ajax_vipps_buy_single_product'));
2836 - add_action('wp_ajax_vipps_buy_single_product', array($this, 'ajax_vipps_buy_single_product'));
2837 -
2838 - // This is for express checkout which we will also do asynchronously IOK 2018-05-28
2839 - add_action('wp_ajax_nopriv_do_express_checkout', array($this, 'ajax_do_express_checkout'));
2840 - add_action('wp_ajax_do_express_checkout', array($this, 'ajax_do_express_checkout'));
2841 -
2842 - // Same thing, but for single products IOK 2018-05-28
2843 - add_action('wp_ajax_nopriv_do_single_product_express_checkout', array($this, 'ajax_do_single_product_express_checkout'));
2844 - add_action('wp_ajax_do_single_product_express_checkout', array($this, 'ajax_do_single_product_express_checkout'));
2845 -
2846 2837 // Handle the cancel unpaid order action when the "hold stock" times out.
2847 2838 // For *normal* vipps orders, we run another cronjob every 5. minute which checks order status,
2848 2839 // therefore here it suffices to check if the order is 'cancelled' at Vipps, and if so we return.
2849 2840 // For Checkout the rules are different though.
@@ -2922,9 +2913,8 @@
2922 2913 $this->vippsJSConfig = array();
2923 2914 $this->vippsJSConfig['vippsajaxurl'] = admin_url('admin-ajax.php');
2924 2915 $this->vippsJSConfig['BuyNowWith'] = __('Buy now with', 'woo-vipps');
2925 2916 $this->vippsJSConfig['BuyNowWithVipps'] = sprintf(__('Buy now with %1$s', 'woo-vipps'), $this->get_payment_method_name());
2926 - $this->vippsJSConfig['vippslogourl'] = plugins_url('img/vipps_logo_negativ_rgb_transparent.png',__FILE__);
2927 2917 $this->vippsJSConfig['vippssmileurl'] = plugins_url('img/vmp-logo.png',__FILE__);
2928 2918 $this->vippsJSConfig['vippsbuynowbutton'] = sprintf(__( '%1$s Buy Now button', 'woo-vipps' ), $this->get_payment_method_name());
2929 2919 $this->vippsJSConfig['vippsbuynowdescription'] = sprintf(__( 'Add a %1$s Buy Now-button to the product block or choose a product manually', 'woo-vipps'), $this->get_payment_method_name());
2930 2920 $this->vippsJSConfig['vippslanguage'] = $this->get_customer_language();
@@ -2929,10 +2919,17 @@
2929 2919 $this->vippsJSConfig['vippsbuynowdescription'] = sprintf(__( 'Add a %1$s Buy Now-button to the product block or choose a product manually', 'woo-vipps'), $this->get_payment_method_name());
2930 2920 $this->vippsJSConfig['vippslanguage'] = $this->get_customer_language();
2931 2921 $this->vippsJSConfig['vippslocale'] = get_locale();
2932 2922 $this->vippsJSConfig['vippsexpressbuttonurl'] = $this->get_payment_method_name();
2933 -
2923 + $this->vippsJSConfig['paymentMethodSlug'] = sanitize_title($this->get_payment_method_name());
2924 + $this->vippsJSConfig['paymentMethodName'] = $this->get_payment_method_name();
2925 + $wc_lang = $this->get_html_button_attrs_for_context()['language'];
2926 + if ('store' === $wc_lang) $wc_lang = $this->get_customer_language();
2927 + // Looks like button and badge web components now use 'da' instead of 'dk' for danish. LP 2026-08-11
2928 + if ('dk' === $wc_lang) $wc_lang = 'da';
2929 + $this->vippsJSConfig['webcomponentLanguage'] = $wc_lang;
2934 2930
2931 +
2935 2932 // If the site supports Gutenberg Blocks, support the Checkout block IOK 2020-08-10
2936 2933 if (class_exists('Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType')) {
2937 2934 // Ensure gateways are loaded at this point IOK 2026-05-27
2938 2935 require_once(dirname(__FILE__) . '/WC_Gateway_VippsCard.class.php');
@@ -3804,9 +3801,9 @@
3804 3801 $shipping_method = $methodclass ? new $methodclass($rate->get_instance_id()) : null;
3805 3802
3806 3803 $tax = $rate->get_shipping_tax() ?: 0;
3807 3804 $cost = $rate->get_cost() ?: 0;
3808 - $label = $rate->get_label();
3805 + $label = html_entity_decode($rate->get_label());
3809 3806
3810 3807 if ($cost == 0 && ($methodid != 'local_pickup' && $methodid != 'pickup_location')) {
3811 3808 $has_free_shipping = true;
3812 3809 }
@@ -3832,9 +3829,9 @@
3832 3829 $shippingcostB = sprintf("%.2F",wc_format_decimal($cost, '') + wc_format_decimal($tax,''));
3833 3830 $shippingcost = max($shippingcostA, $shippingcostB);
3834 3831
3835 3832 $vippsmethod['shippingCost'] = $shippingcost;
3836 - $vippsmethod['shippingMethod'] = $rate->get_label();
3833 + $vippsmethod['shippingMethod'] = html_entity_decode($rate->get_label());
3837 3834 $vippsmethod['shippingMethodId'] = $key;
3838 3835 $vippsmethods[]=$vippsmethod;
3839 3836
3840 3837 // Metadata and settings stored for later use for Checkout
@@ -4148,9 +4145,9 @@
4148 4145 WC()->cart->calculate_totals();
4149 4146 WC()->cart->set_session();
4150 4147 return true;
4151 4148 } catch (Exception $e) {
4152 - $this->log(sprintf(__("Error regenerating cart from order %1\$d: %2\$s", 'woo-vipps'), $order_id, $e->get_message()), 'error');
4149 + $this->log(sprintf(__("Error regenerating cart from order %1\$d: %2\$s", 'woo-vipps'), $order_id, $e->getMessage()), 'error');
4153 4150 return false;
4154 4151 }
4155 4152 }
4156 4153
@@ -4179,9 +4176,9 @@
4179 4176 $tax = $rate->get_shipping_tax() ?: 0;
4180 4177 $cost = $rate->get_cost() ?: 0;
4181 4178
4182 4179 $method['shippingCost'] = sprintf("%.2F",wc_format_decimal($cost+$tax,''));
4183 - $method['shippingMethod'] = $rate->get_label();
4180 + $method['shippingMethod'] = html_entity_decode($rate->get_label());
4184 4181 // We may not really need the tax stashed here, but just to be sure.
4185 4182 $method['shippingMethodId'] = $rate->get_id() . ";" . $tax;
4186 4183 $methods[]= $method;
4187 4184
@@ -4461,28 +4458,12 @@
4461 4458 $order = wc_get_order($order->get_id());
4462 4459 $order_status = $order->get_status();
4463 4460
4464 4461 if ($order_status != 'pending') return $order_status;
4465 - // No callback has occured yet. If this has been going on for a while, check directly with Vipps
4466 - // We can't use the vipps init timestamp here, because that may be in the past for Checkout at least. IOK 2025-08-13
4467 - if ($order_status == 'pending') {
4468 - if (WC()->session) {
4469 - $now = time();
4470 - $then = WC()->session->get('_vipps_check_' . $order->get_id());
4471 - if (!$then) {
4472 - $then = $now;
4473 - WC()->session->set('_vipps_check_' . $order->get_id(), $then);
4474 - }
4475 - if (($then + (1 * 30)) > $now) { // more than half a minute? Start checking at Vipps
4476 - return $order_status;
4477 - }
4478 - } else {
4479 - // No session shouldn't be possible, but if it is..
4480 - return $order_status;
4481 - }
4482 - }
4462 +
4463 + $gw = $this->gateway();
4483 4464 $this->log("Checking order status on Vipps for order id: " . $order->get_id(), 'info');
4484 - return $this->check_status_of_pending_order($order);
4465 + $newstatus = $gw->poll_and_check_order_status($order);
4485 4466 }
4486 4467
4487 4468 // In some situations we have to empty the cart when the user goes to Vipps, so
4488 4469 // we store it in the session and restore it if the users cancels. IOK 2018-05-07
@@ -4550,8 +4531,9 @@
4550 4531
4551 4532 // Maybe log in user
4552 4533 // It is done on the thank-you page of the order, and only for express checkout.
4553 4534 function maybe_log_in_user ($order) {
4535 +
4554 4536 if (is_user_logged_in()) return;
4555 4537 if (!$order || ! self::is_vipps_order($order)) return;
4556 4538
4557 4539 // We *do* want to log in express checkout customers, but not those that
@@ -4697,129 +4679,233 @@
4697 4679 }
4698 4680 if (!$o) return;
4699 4681 if (!$o->get_meta('_vipps_single_product_express')) return;
4700 4682 if ($failed && !apply_filters('woo_vipps_restore_cart_on_express_checkout_failure', true, $o)) return;
4701 - if ($failed) WC()->cart->empty_cart();
4683 + // Restoring cart! But clear it first so we dont add this single product to the restored cart. LP 2026-09-22
4684 + WC()->cart->empty_cart();
4702 4685 $this->restore_cart($o);
4703 4686 }
4704 4687
4705 4688
4706 - public function ajax_vipps_buy_single_product () {
4707 - Vipps::nocache();
4708 - static::set_locale_if_in_header();
4709 - // We're not checking ajax referer here, because what we do is creating a session and redirecting to the
4710 - // 'create order' page wherein we'll do the actual work. IOK 2018-09-28
4711 - $session = WC()->session;
4712 - if (!$session->has_session()) {
4713 - $session->set_customer_session_cookie(true);
4689 + // Actually create a express checkout order object, with no shipping or personal information, returning information about
4690 + // the result. The order should at this point be in a/the cart. For single product purchases, this is a different cart than
4691 + // the main one; for cart purchases, it's just the WC()->cart object. IOK 2026-08-25
4692 + private function create_and_process_express_order() {
4693 + $result = null;
4694 + $gw = $this->gateway();
4695 + try {
4696 + $orderid = $gw->create_partial_order();
4697 + do_action('woo_vipps_ajax_do_express_checkout', $orderid);
4698 + } catch (Exception $e) {
4699 + $result = array('ok'=>0, 'orderid'=>0, 'msg'=>__('Could not create order','woo-vipps') . ': ' . $e->getMessage(), 'url'=>false);
4700 + return $result;
4701 + }
4702 + if (!$orderid) {
4703 + $result = array('ok'=>0, 'orderid'=>0, 'msg'=>__('Could not create order','woo-vipps'), 'url'=>false);
4704 + return $result;
4714 4705 }
4715 - $session->set('__vipps_buy_product', json_encode($_REQUEST));
4716 4706
4717 - // Incredibly, some caches will cache this page even with cookies set and no-cache headers set. So we try to
4718 - // add yet another way to inform caches that this is, in fact, not cacheable. IOK 2023-06-12
4719 - $url = add_query_arg('nc', sha1(uniqid(WC()->session->get_customer_id(),true)), $this->buy_product_url());
4707 + try {
4708 + $this->maybe_add_static_shipping($gw,$orderid);
4709 + } catch (Exception $e) {
4710 + $this->log(__("Error calculating static shipping", 'woo-vipps'), 'error');
4711 + $this->log($e->getMessage(),'error');
4712 + $result = array('ok'=>0, 'orderid'=>0, 'msg'=>__('Could not create order','woo-vipps'), 'url'=>false);
4713 + return $result;
4714 + }
4720 4715
4721 - $result = array('ok'=>1, 'msg'=>__('Processing order... ','woo-vipps'), 'url'=> $url);
4722 - wp_send_json($result);
4723 - exit();
4716 + // Now pass this to the Woo gateway and get a redirect URL back IOK 2026-08-25
4717 + $ok = $gw->process_payment($orderid);
4718 + if ($ok && $ok['result'] == 'success') {
4719 + $result = array('ok'=>1, 'orderid'=>$orderid, 'msg'=>'', 'url'=>$ok['redirect']);
4720 + return $result;
4721 + }
4722 + $result = array('ok'=>0, 'orderid'=>$orderid, 'msg'=> sprintf(__('%1$s is temporarily unavailable.','woo-vipps'), $this->get_payment_method_name()), 'url'=>'');
4723 + return $result;
4724 4724 }
4725 4725
4726 - public function ajax_do_express_checkout () {
4727 - check_ajax_referer('do_express','sec');
4728 - Vipps::nocache();
4729 - static::set_locale_if_in_header();
4726 + // This creates a simple hash for the 'current order' which we will store in the session if we proceed to checkout. We use this to
4727 + // avoid/warn the user of duplicate purchases. IOK 2026-09-09
4728 + public function create_order_hash($args=null) {
4729 + // If we have no arguments, we'll hash the cart.
4730 + if (empty($args)) {
4731 + $cartitems = WC()->cart->get_cart();
4732 + $orderspec = array();
4733 + foreach($cartitems as $item => $values) {
4734 + $orderspec[] = array('sku'=> ($values['sku'] ?? ""), 'product_id'=>($values['product_id'] ?? 0), 'variation_id'=>($values['variation_id'] ?? 0), 'quantity'=>($values['quantity'] ?? 1));
4735 + }
4736 + $args = $orderspec;
4737 + }
4738 + return md5(serialize($args));
4739 + }
4740 +
4741 +
4742 + // This method may provide HTML form elements to ask a user questions after starting
4743 + // express checkout. It is used to detect duplicate orders, possibly for terms and conditions, and user-definiable customizations. IOK 2026-09-09
4744 + // NULL productinfo means use the cart; the "current hash" is used to detect duplicates, and is calculated by the caller.
4745 + public function express_order_needs_confirmation($args, $productinfo, $current_hash) {
4746 + $elements = [];
4747 + $html = "";
4748 +
4749 + // First, let's check if we need to confirm the purchase.
4750 + $last_express_purchase_hash = WC()->session->get('woo_vipps_last_express');
4751 + if ($last_express_purchase_hash) {
4752 + list($hash, $orderid, $stamp) = explode(":", $last_express_purchase_hash);
4753 + $cutoff = $stamp + apply_filters('woo_vipps_recent_order_cutoff', (3*60));
4754 + if ($hash == $current_hash && (time() <= $cutoff )) {
4755 + $order = wc_get_order($orderid);
4756 + $status = $order ? $order->get_status() : false;
4757 + // IOK TODO/FIXME actually, if the order is pending/failed/cancelled and *identical* to our current productinfo, we could plausibly do a restart here. Would probably require careful checking though, and
4758 + // a different flow. IOK 2026-09-17
4759 + if (in_array($status, ['on-hold', 'processing', 'completed'])) {
4760 + $header = __("Are you sure?",'woo-vipps');
4761 + $body = __("You recently completed an order with exactly the same products as you are buying now. There should be an email in your inbox from the previous purchase. Are you sure you want to order again?",'woo-vipps');
4762 + $elements['possible_duplicate'] = "<h1>$header</h1><p>$body</p>";
4763 + $this->log(__("It seems a customer is trying to re-order product(s) recently bought in the same session, asking user for confirmation", 'woo-vipps'), 'info');
4764 + }
4765 + }
4766 + }
4767 +
4730 4768 $gw = $this->gateway();
4769 + $askForTerms = function_exists('wc_terms_and_conditions_checkbox_enabled') ? wc_terms_and_conditions_checkbox_enabled() : true;
4770 + $askForTerms = $askForTerms && ($gw->get_option('expresscheckout_termscheckbox') == 'yes');
4771 + $askForTerms = apply_filters('woo_vipps_express_checkout_terms_and_conditions_checkbox_enabled', $askForTerms);
4731 4772
4732 - if (!$gw->express_checkout_available() || !$gw->cart_supports_express_checkout()) {
4733 - $result = array('ok'=>0, 'msg'=>sprintf(__('%1$s is not available for this order','woo-vipps'), Vipps::ExpressCheckoutName()), 'url'=>false);
4734 - wp_send_json($result);
4735 - exit();
4773 + if ($askForTerms) {
4774 + $termsHTML = '';
4775 + // Include shop terms
4776 + ob_start();
4777 + wc_get_template('checkout/terms.php');
4778 + $termsHTML = ob_get_clean();
4779 + $termsHTML = apply_filters('woo_vipps_express_checkout_terms_and_conditions_html',$termsHTML);
4780 + $elements['terms'] = $termsHTML;
4736 4781 }
4737 4782
4783 + // Custom fields
4784 + ob_start();
4785 + do_action('woo_vipps_express_checkout_orderspec_form', $productinfo, $args);
4786 + $extra_fields = ob_get_clean();
4787 + if (!empty($extra_fields)) {
4788 + $elements['extra'] = $extra_fields;
4789 + }
4738 4790
4739 -
4791 + if (!empty($elements)) {
4792 + $html = join("\n", array_values($elements));
4793 + $msg = join(",", array_keys($elements));
4794 + return ['ok'=>2, 'msg'=>$msg, 'html'=>$html, 'url'=>''];
4795 + }
4740 4796
4797 + return false;
4798 +
4799 + }
4800 +
4801 + public function rest_do_express_checkout ($request) {
4802 + Vipps::nocache();
4803 + check_ajax_referer('express', 'sec');
4804 + static::set_locale_if_in_header();
4805 + $args = $request->get_json_params();
4806 + if (!$args) {
4807 + return new WP_Error('no_data', __('No data passed to express checkout', 'woo-vipps'), ['status' => 400]);
4808 + }
4809 +
4810 + // Since this is the REST api, we need to load the cart manually here. IOK 2026-08-27
4811 + if ( is_null( WC()->cart ) ) {
4812 + WC()->frontend_includes();
4813 + if ( ! WC()->session instanceof WC_Session ) {
4814 + WC()->session = new WC_Session_Handler();
4815 + WC()->session->init();
4816 + }
4817 + if (is_null( WC()->customer)) {
4818 + WC()->customer = new WC_Customer( get_current_user_id(), true );
4819 + }
4820 + WC()->cart = new WC_Cart();
4821 + WC()->cart->get_cart_from_session();
4822 + }
4823 +
4824 +
4825 + $gw = $this->gateway();
4826 + if (!$gw->express_checkout_available() || !$gw->cart_supports_express_checkout()) {
4827 + $result = array('ok'=>0, 'msg'=>sprintf(__('%1$s is not available for this order','woo-vipps'), Vipps::ExpressCheckoutName()), 'url'=>false);
4828 + return $result;
4829 + }
4741 4830 // Validate cart going forward using same logic as WC_Cart->check_cart() but not adding notices.
4742 4831 $toolate = false;
4743 4832 $msg = "";
4744 4833 $valid = WC()->cart->check_cart_item_validity();
4745 4834 if ( is_wp_error( $valid) ) {
4746 - $toolate = true;
4747 - $msg = "<br>" . $valid->get_error_message();
4835 + $toolate = true;
4836 + $msg = "<br>" . $valid->get_error_message();
4748 4837 }
4749 4838 $stock = WC()->cart->check_cart_item_stock();
4750 - if ( is_wp_error( $stock) ) {
4751 - $toolate = true;
4752 - $msg = "<br>" . $stock->get_error_message();
4753 - }
4839 + if ( is_wp_error( $stock) ) {
4840 + $toolate = true;
4841 + $msg = "<br>" . $stock->get_error_message();
4842 + }
4754 4843
4755 4844 if ($toolate) {
4756 4845 $result = array('ok'=>0, 'msg'=>sprintf(__('Some of the products in your cart are no longer available in the quantities you have ordered. Please <a href="%1$s">edit your order</a> before continuing the checkout','woo-vipps'), wc_get_cart_url()) . $msg, 'url'=>false);
4757 - wp_send_json($result);
4758 - exit();
4846 + return $result;
4759 4847 }
4760 4848
4761 - try {
4762 - $orderid = $gw->create_partial_order();
4763 - do_action('woo_vipps_ajax_do_express_checkout', $orderid);
4764 - } catch (Exception $e) {
4765 - $this->log($e->getMessage(),'error');
4766 - $result = array('ok'=>0, 'msg'=>__('Could not create order','woo-vipps') . ': ' . $e->getMessage(), 'url'=>false);
4767 - wp_send_json($result);
4768 - exit();
4769 - }
4770 - if (!$orderid) {
4771 - $result = array('ok'=>0, 'msg'=>__('Could not create order','woo-vipps'), 'url'=>false);
4772 - wp_send_json($result);
4773 - exit();
4849 + // Then the cookies. These would be the _ga and sbjs_ cookies typically, but we'll let users handle these themselves.
4850 + // These are passed as arguments from the javascript, since proxies are likely to strip them. This should allow
4851 + // systems like MonsterInsights that look for the _GA cookie to succeed. IOK 2026-08-30
4852 + $cookies = $args['cookies'] ?? [];
4853 + foreach($cookies as $key => $value) {
4854 + if (!isset($_COOKIE[$key])) {
4855 + $_COOKIE[$key] = $value;
4856 + }
4774 4857 }
4858 + // There might be extra values here now, which would typically have been posted as POST arguments, in a form.
4859 + // User-defined stuff and so on. We'll initiate the POST value with these to simulate this for backwards compatibility.
4860 + $others =$args['post'] ?? [];
4861 + foreach($args['post'] as $key=>$value) {
4862 + $_POST[$key] = $value;
4863 + }
4775 4864
4776 - try {
4777 - $this->maybe_add_static_shipping($gw,$orderid);
4778 - } catch (Exception $e) {
4779 - $this->log(__("Error calculating static shipping", 'woo-vipps'), 'error');
4780 - $this->log($e->getMessage(),'error');
4781 - $result = array('ok'=>0, 'msg'=>__('Could not create order','woo-vipps'), 'url'=>false);
4782 - wp_send_json($result);
4783 - exit();
4865 + // Try to avoid re-purchasing the same order repeatedly. IOK 2026-09-02
4866 + $current_hash = $this->create_order_hash();
4867 + $confirmation = (bool) intval(($others['confirmed'] ?? 0));
4868 + if (!$confirmation) {
4869 + $result = $this->express_order_needs_confirmation($args, null, $current_hash);
4870 + if (!empty($result)) {
4871 + return $result;
4872 + }
4784 4873 }
4785 -
4786 - $ok = $gw->process_payment($orderid);
4787 - if ($ok && $ok['result'] == 'success') {
4788 - $result = array('ok'=>1, 'msg'=>'', 'url'=>$ok['redirect']);
4789 - wp_send_json($result);
4790 - exit();
4874 +
4875 + $result = $this->create_and_process_express_order();
4876 + if ($result['ok'] == 1) {
4877 + $orderid = $result['orderid'];
4878 + WC()->session->set('woo_vipps_last_express', "$current_hash:$orderid:" . time());
4879 + WC()->session->save_data();
4791 4880 }
4792 - $result = array('ok'=>0, 'msg'=> sprintf(__('%1$s is temporarily unavailable.','woo-vipps'), $this->get_payment_method_name()), 'url'=>'');
4793 - wp_send_json($result);
4794 - exit();
4881 + return $result;
4882 +
4795 4883 }
4796 4884
4797 - // Same as ajax_do_express_checkout, but for a single product/variation. Duplicate code because we want to manipulate the cart differently here. IOK 2018-09-25
4798 - public function ajax_do_single_product_express_checkout() {
4799 - check_ajax_referer('do_express','sec');
4800 - Vipps::nocache();
4885 +
4886 + // Rest handler for single product express checkout. Expects arguments as JSON. IOK 2026-08-25
4887 + public function rest_do_single_product_express_checkout ($request) {
4888 + Vipps::nocache();
4801 4889 static::set_locale_if_in_header();
4802 - require_once(dirname(__FILE__) . "/WC_Gateway_Vipps.class.php");
4803 - $gw = $this->gateway();
4804 -
4805 - if (!$gw->express_checkout_available()) {
4806 - $result = array('ok'=>0, 'msg'=>sprintf(__('%1$s is not available for this order','woo-vipps'), Vipps::ExpressCheckoutName()), 'url'=>false);
4807 - wp_send_json($result);
4808 - exit();
4890 + $args = $request->get_json_params();
4891 + if (!$args) {
4892 + return new WP_Error('no_data', __('No data passed to express checkout', 'woo-vipps'), ['status' => 400]);
4809 4893 }
4894 + $result = ['ok' => 0, 'msg'=>'', 'orderid'=>0, 'url'=>''];
4810 4895
4896 + // We receive the varid, prodid, sku and quantity directly. One of these. The sku is the dominant one. IOK 2026-08-27
4897 + $varid = intval($args['variation_id'] ?? 0);
4898 + $prodid = intval($args['product_id'] ?? 0);
4899 + $sku = sanitize_text_field($args['sku'] ?? "");
4900 + $quantity = max(1, intval($args['quantity'] ?? 0));
4811 4901
4812 - // Here we will either have a product-id, a variant-id and a product-id, or just a SKU. The product-id will not be a variant - but
4813 - // we'll double-check just in case. Also if we somehow *just* get a variant-id we should fix that too. But a SKU trumps all. IOK 2018-10-02
4814 - $varid = intval(@$_POST['variation_id']);
4815 - $prodid = intval(@$_POST['product_id']);
4816 - $sku = sanitize_text_field(@$_POST['sku']);
4817 - $quant = intval(@$_POST['quantity']);
4818 4902
4819 - // Get any attributes posted for variable products (where one of the dimensions is "any" for instance)
4820 - $variations = array();
4821 - foreach ($_POST as $key => $value ) {
4903 + // We expect the variations - that is, the fields named "attribute_..." to be sent as post fields.
4904 + // We just need to sanitize them.
4905 + $variations = [];
4906 + $invars = $args['post'] ?? [];
4907 + foreach ($invars as $key => $value) {
4822 4908 if ( 'attribute_' !== substr( $key, 0, 10 ) ) {
4823 4909 continue;
4824 4910 }
4825 4911 $variations[ sanitize_title( wp_unslash( $key ) ) ] = wp_unslash( $value );
@@ -4824,15 +4910,94 @@
4824 4910 }
4825 4911 $variations[ sanitize_title( wp_unslash( $key ) ) ] = wp_unslash( $value );
4826 4912 }
4827 4913
4828 - $product = null;
4829 - $variant = null;
4830 - $parent = null;
4831 - $parentid = null;
4832 - $quantity = 1;
4833 - if ($quant && $quant>1) $quantity=$quant;
4914 + // Then the cookies. These would be the _ga and sbjs_ cookies typically, but we'll let users handle these themselves.
4915 + // These are passed as arguments from the javascript, since proxies are likely to strip them. This should allow
4916 + // systems like MonsterInsights that look for the _GA cookie to succeed. IOK 2026-08-30
4917 + $cookies = $args['cookies'] ?? [];
4918 + foreach($cookies as $key => $value) {
4919 + if (!isset($_COOKIE[$key])) {
4920 + $_COOKIE[$key] = $value;
4921 + }
4922 + }
4834 4923
4924 + // There might be extra values here now, which would typically have been posted as POST arguments, in a form.
4925 + // User-defined stuff and so on. We'll initiate the POST value with these to simulate this for backwards compatibility.
4926 + $others =$args['post'] ?? [];
4927 + foreach($args['post'] as $key=>$value) {
4928 + $_POST[$key] = $value;
4929 + }
4930 +
4931 + // Since this is the REST api, we need to load the cart manually here. *Not* loading the cart could be an option but unpredictable. IOK 2026-08-27
4932 + if ( is_null( WC()->cart ) ) {
4933 + WC()->frontend_includes();
4934 + if ( ! WC()->session instanceof WC_Session ) {
4935 + WC()->session = new WC_Session_Handler();
4936 + WC()->session->init();
4937 +
4938 + // If we don't have a session cookie, we need to set it, and also initialize the $_COOKIE value. IOK 2026-09-29
4939 + if (! WC()->session->get_session_cookie()) {
4940 + $store_session_cookie = function ( $options, $name, $value ) { $_COOKIE[$name] = $value; return $options;};
4941 + add_filter('woocommerce_set_cookie_options', $store_session_cookie, 10, 3);
4942 + try {
4943 + WC()->session->set_customer_session_cookie( true ); // We have to explicitly set the cookie if this session is fresh. IOK 2026-09-29
4944 + } finally {
4945 + remove_filter('woocommerce_set_cookie_options', $store_session_cookie, 10);
4946 + }
4947 + }
4948 + }
4949 + if (is_null( WC()->customer)) {
4950 + WC()->customer = new WC_Customer( get_current_user_id(), true );
4951 + }
4952 + WC()->cart = new WC_Cart();
4953 + WC()->cart->get_cart_from_session();
4954 + }
4955 +
4956 + // Try to avoid re-purchasing the same order repeatedly. IOK 2026-09-02
4957 + // We calculate this here so we can add it to the session later. IOK 2026-09-09
4958 + $orderspec = array('sku'=> $sku, 'product_id'=>$prodid, 'variation_id'=>$varid, 'quantity'=>$quantity);
4959 + $current_hash = $this->create_order_hash($orderspec);
4960 +
4961 + // Now to handle "extra questions" for an order, including terms + conditions and "possible duplicate order" IOK 2026-09-09
4962 + $confirmation = (bool) intval(($others['confirmed'] ?? 0));
4963 + if (!$confirmation) {
4964 + $result = $this->express_order_needs_confirmation($args, $orderspec, $current_hash);
4965 + if (!empty($result)) {
4966 + $response = new WP_REST_Response($result);
4967 + $response->set_status(200);
4968 + return $response;
4969 + }
4970 + }
4971 +
4972 + // Basically always return 200 after this, and always return an object with an 'ok' and a 'msg' value, possibly 'orderid' and 'url'.
4973 + $result = $this->really_do_single_product_express_checkout($prodid, $varid, $sku, $quantity, $variations);
4974 + // And if we're going to express now so let's note the order. IOK 2026-08-27. Now this assumes success, but *basically* I think this is ok.
4975 + // We'll reset it on order failure I think. IOK 2026-08-20 FIXME
4976 + if ($result['ok'] == 1) {
4977 + $orderid = $result['orderid'];
4978 + WC()->session->set('woo_vipps_last_express', "$current_hash:$orderid:" . time());
4979 + WC()->session->save_data();
4980 + }
4981 +
4982 + $response = new WP_REST_Response($result);
4983 + $response->set_status(200);
4984 +
4985 + return $response;
4986 + }
4987 +
4988 + // Common private method to do single product express checkout, used by the new REST express. IOK 2026-08-25
4989 + private function really_do_single_product_express_checkout($prodid, $varid, $sku, $quantity=1, $variations=[]) {
4990 + require_once(dirname(__FILE__) . "/WC_Gateway_Vipps.class.php");
4991 + $gw = $this->gateway();
4992 +
4993 + if (!$gw->express_checkout_available()) {
4994 + $result = array('ok'=>0, 'msg'=>sprintf(__('%1$s is not available for this order','woo-vipps'), Vipps::ExpressCheckoutName()), 'url'=>false);
4995 + return $result;
4996 + }
4997 + // Here we will either have a product-id, a variant-id and a product-id, or just a SKU. The product-id will not be a variant - but
4998 + // we'll double-check just in case. Also if we somehow *just* get a variant-id we should fix that too. But a SKU trumps all. IOK 2018-10-02
4999 +
4835 5000 // Find the product, or variation, and get everything in order so we can check existence, availability etc. IOK 2018-10-02
4836 5001 // Moved rules around as the _sku variant broke in 3.6.1 for stores that didn't bother to update the database IOK 2019-04-24
4837 5002 // This broke single-product purchases for variable products; fixed IOK 2019-05-21 thanks to Gaute Terland Nilsen @ Easyweb for the report
4838 5003 try {
@@ -4845,17 +5010,14 @@
4845 5010 $product = wc_get_product($skuid);
4846 5011 }
4847 5012 } catch (Exception $e) {
4848 5013 $result = array('ok'=>0, 'msg'=>__('Error finding product - cannot create order','woo-vipps'), 'url'=>false);
4849 - wp_send_json($result);
4850 - exit();
5014 + return $result;
4851 5015 }
4852 5016
4853 -
4854 5017 if (!$product) {
4855 5018 $result = array('ok'=>0, 'msg'=>__('Unknown product, cannot create order','woo-vipps'), 'url'=>false);
4856 - wp_send_json($result);
4857 - exit();
5019 + return $result;
4858 5020 }
4859 5021
4860 5022 $parentid = $product ? $product->get_parent_id() : null; // If the product is a variation, then the parent product is the parentid.
4861 5023 $parent = $parentid ? wc_get_product($parentid) : null;
@@ -4862,34 +5024,30 @@
4862 5024
4863 5025 // This can't really happen, but if it did..
4864 5026 if ($prodid && $parentid && ($prodid != $parentid)) {
4865 5027 $result = array('ok'=>0, 'msg'=>__('Selected product variant is not available','woo-vipps'), 'url'=>false);
4866 - wp_send_json($result);
4867 - exit();
5028 + return $result;
4868 5029 }
4869 5030 if (!$gw->product_supports_express_checkout($product)) {
4870 5031 $result = array('ok'=>0, 'msg'=>sprintf(__('%1$s is not available for this order','woo-vipps'), Vipps::ExpressCheckoutName()), 'url'=>false);
4871 - wp_send_json($result);
4872 - exit();
5032 + return $result;
4873 5033 }
4874 5034
4875 5035 // Somebody addded the wrong SKU
4876 5036 if ($product->get_type() == 'variable'){
4877 5037 $result = array('ok'=>0, 'msg'=>__('Selected product variant is not available for purchase','woo-vipps'), 'url'=>false);
4878 - wp_send_json($result);
4879 - exit();
5038 + return $result;
4880 5039 }
4881 5040 // Final check of availability
4882 5041 if (!$product->is_purchasable() || !$product->is_in_stock()) {
4883 5042 $result = array('ok'=>0, 'msg'=>__('Your product is temporarily no longer available for purchase','woo-vipps'), 'url'=>false);
4884 - wp_send_json($result);
4885 - exit();
5043 + return $result;
4886 5044 }
4887 5045
4888 5046 // Now it should be safe to continue to the checkout process. IOK 2018-10-02
4889 -
4890 5047 // Create a new temporary cart for this order. We need to get (and save) the real session cart,
4891 5048 // because some plugins actually override this.
5049 + // NB: Please note the cart must have been loaded here, be aware when doing REST. IOK 2026-08-27
4892 5050 $current_cart = clone WC()->cart;
4893 5051 WC()->cart->empty_cart();
4894 5052
4895 5053 if ($parent && $parent->get_type() == 'variable') {
@@ -4896,50 +5054,22 @@
4896 5054 WC()->cart->add_to_cart($parent->get_id(),$quantity,$product->get_id(), $variations);
4897 5055 } else {
4898 5056 WC()->cart->add_to_cart($product->get_id(),$quantity);
4899 5057 }
5058 + WC()->session->save_data();
4900 5059
4901 - try {
4902 - $orderid = $gw->create_partial_order();
4903 - do_action('woo_vipps_ajax_do_express_checkout', $orderid);
4904 - } catch (Exception $e) {
4905 - $result = array('ok'=>0, 'msg'=>__('Could not create order','woo-vipps') . ': ' . $e->getMessage(), 'url'=>false);
4906 - wp_send_json($result);
4907 - exit();
4908 - }
5060 + $result = $this->create_and_process_express_order();
4909 5061
4910 - if (!$orderid) {
4911 - $result = array('ok'=>0, 'msg'=>__('Could not create order','woo-vipps'), 'url'=>false);
4912 - wp_send_json($result);
4913 - exit();
5062 + if ($result['ok'] ?? false) {
5063 + // Single product purchase, so save any contents of the real cart
5064 + $orderid = $result['orderid'];
5065 + $order = wc_get_order($orderid);
5066 + $order->update_meta_data('_vipps_single_product_express',true);
5067 + $order->save();
5068 + $this->save_cart($order,$current_cart);
4914 5069 }
4915 5070
4916 - try {
4917 - $this->maybe_add_static_shipping($gw,$orderid);
4918 - } catch (Exception $e) {
4919 - $this->log(__("Error calculating static shipping", 'woo-vipps'), 'error');
4920 - $this->log($e->getMessage(),'error');
4921 - $result = array('ok'=>0, 'msg'=>__('Could not create order','woo-vipps'), 'url'=>false);
4922 - wp_send_json($result);
4923 - exit();
4924 - }
4925 -
4926 -
4927 - // Single product purchase, so save any contents of the real cart
4928 - $order = wc_get_order($orderid);
4929 - $order->update_meta_data('_vipps_single_product_express',true);
4930 - $order->save();
4931 - $this->save_cart($order,$current_cart);
4932 -
4933 - $ok = $gw->process_payment($orderid);
4934 - if ($ok && $ok['result'] == 'success') {
4935 - $result = array('ok'=>1, 'msg'=>'', 'url'=>$ok['redirect']);
4936 - wp_send_json($result);
4937 - exit();
4938 - }
4939 - $result = array('ok'=>0, 'msg'=> sprintf(__('%1$s is temporarily unavailable.','woo-vipps'), $this->get_payment_method_name()), 'url'=>'');
4940 - wp_send_json($result);
4941 - exit();
5071 + return $result;
4942 5072 }
4943 5073
4944 5074 // This calculates and adds static shipping info to a partial order for express checkout if merchant has enabled this. IOK 2020-03-19
4945 5075 // Made visible for consistency with add_static_shipping. IOK 2021-10-22
@@ -5005,9 +5135,9 @@
5005 5135 $transaction = sanitize_text_field(@$_POST['transaction']);
5006 5136
5007 5137 $sessionorders= WC()->session->get('_vipps_session_orders');
5008 5138 if (!isset($sessionorders[$orderid])) {
5009 - wp_send_json(array('status'=>'error', 'msg'=>__('Not an order','woo-vipps')));
5139 + wp_send_json(array('status'=>'error', 'msg'=>__('Not a session order','woo-vipps')));
5010 5140 }
5011 5141
5012 5142 $order = wc_get_order($orderid);
5013 5143 if (!$order) {
@@ -5264,9 +5394,8 @@
5264 5394 echo "<div class='vipps_buy_now_wrapper loop'>$button</div>";
5265 5395 }
5266 5396
5267 5397
5268 -
5269 5398 // Checkout replaces the default checkout page, and currently uses its own page for this which needs to exist
5270 5399 // IOK 2026-04-30 remove this when checkout is end-of-life'd
5271 5400 // We now also use this for the vipps special page, previously a fakepage. LP 2026-08-18
5272 5401 public function woocommerce_create_pages ($data) {
@@ -5347,15 +5476,8 @@
5347 5476 // This URL will when accessed add a product to the cart and go directly to the express checkout page.
5348 5477 // The argument passed must be a shareable link created for a given product - so this in effect acts as a landing page for
5349 5478 // the buying thru Vipps Express Checkout of a single product linked to in for instance banners. IOK 2018-09-24
5350 5479 public function vipps_buy_product() {
5351 -
5352 - add_filter('body_class', function ($classes) {
5353 - $classes[] = 'vipps-express-checkout';
5354 - $classes[] = 'woocommerce-checkout'; // Required by Pixel Your Site IOK 2022-11-24
5355 - return apply_filters('woo_vipps_express_checkout_body_class', $classes);
5356 - });
5357 -
5358 5480 do_action('woo_vipps_express_checkout_page');
5359 5481
5360 5482 $session = WC()->session;
5361 5483 $posted = $session->get('__vipps_buy_product');
@@ -5389,23 +5511,26 @@
5389 5511 }
5390 5512
5391 5513 // Pass the productinfo to the express checkout form
5392 5514 $args = array();
5393 - $args['quantity'] = 1;
5394 - if (array_key_exists('product_id',$productinfo)) $args['product_id'] = intval($productinfo['product_id']);
5395 - if (array_key_exists('variation_id',$productinfo)) $args['variation_id'] = intval($productinfo['variation_id']);
5396 - if (array_key_exists('product_sku',$productinfo)) $args['sku'] = sanitize_text_field($productinfo['product_sku']);
5397 - if (array_key_exists('quantity',$productinfo)) $args['quantity'] = intval($productinfo['quantity']);
5515 + $args['product_id'] = esc_attr(intval($productinfo['product_id'] ?? 0));
5516 + $args['variation_id'] = esc_attr(intval($productinfo['variation_id'] ?? 0));
5517 + $args['sku'] = esc_attr(sanitize_text_field($productinfo['product_sku'] ?? ""));
5518 + $args['quantity'] = esc_attr(max(1, intval($productinfo['quantity'] ?? 0)));
5398 5519
5399 - // For variable products where some of the attributes are "any", we need to add these as well. This is from woos form-handler for these.
5400 - foreach ($productinfo as $key => $value) {
5401 - if ( 'attribute_' !== substr( $key, 0, 10 ) ) {
5402 - continue;
5403 - }
5404 - $args[sanitize_title(wp_unslash($key))] = sanitize_text_field(wp_unslash($value));
5405 - }
5520 + $payment_method = $this->get_payment_method_name();
5521 + $btitle = esc_attr(sprintf(__('Buy now with %1$s', 'woo-vipps'), $payment_method));
5522 + $bclass = esc_attr($payment_method);
5406 5523
5407 - return $this->express_checkout_page_html(true,'do_single_product_express_checkout',$args);
5524 + $content = "<p id=waiting>" . __("Please wait while we are preparing your order", 'woo-vipps') . "...</p>";
5525 + $content .= "<div class='vipps-qr-purchase' style='visibility:hidden'>";
5526 + $content .= "<a href='javascript:void(0)' class='single-product button vipps-buy-now $bclass' data-vipps-autostart='true' data-vipps-purchase='single' data-product_id='{$args['product_id']}' data-variation_id='{$args['variation_id']}' data-product_sku='{$args['sku']}' data-quantity='{$args['quantity']}' title='{$btitle}';
5527 + >";
5528 + $content .= $this->get_html_button_for_context('global');
5529 + $content .= "</a>";
5530 + $content .= "</div>";
5531 +
5532 + return $content;
5408 5533 }
5409 5534
5410 5535 public function vipps_express_checkout_consistency_check() {
5411 5536 // We need a nonce to get here, but we should only get here when we have a cart, so this will not be cached.
@@ -5429,9 +5554,10 @@
5429 5554
5430 5555 add_filter('woo_vipps_express_checkout_consistent', '__return_true');
5431 5556 }
5432 5557
5433 - // This is a landing page for the express checkout of then normal cart - it is done like this because this could take time on slower hosts.
5558 + // This is a landing page for the express checkout of the normal cart - it is done like this because this could take time on slower hosts.
5559 + // IOK 2026-09-09 - nowadays this is only used for compatibility mode. It will automatically start express checkout of the current cart when reached.
5434 5560 public function vipps_express_checkout() {
5435 5561 // Some checks are made in template_redirect, we check here if they are ok IOK 2026-09-21
5436 5562 if (!apply_filters('woo_vipps_express_checkout_consistent', false)) {
5437 5563 $content = __('Link expired, please try again', 'woo-vipps');
@@ -5436,217 +5562,30 @@
5436 5562 if (!apply_filters('woo_vipps_express_checkout_consistent', false)) {
5437 5563 $content = __('Link expired, please try again', 'woo-vipps');
5438 5564 return $content;
5439 5565 }
5440 -
5441 - add_filter('body_class', function ($classes) {
5442 - $classes[] = 'vipps-express-checkout';
5443 - $classes[] = 'woocommerce-checkout'; // Required by Pixel Your Site IOK 2022-11-24
5444 - return apply_filters('woo_vipps_express_checkout_body_class', $classes);
5445 - });
5446 -
5566 +
5447 5567 do_action('woo_vipps_express_checkout_page');
5448 5568
5449 - return $this->express_checkout_page_html(true, 'do_express_checkout');
5450 - }
5569 + $payment_method = $this->get_payment_method_name();
5570 + $btitle = esc_attr(sprintf(__('Buy now with %1$s', 'woo-vipps'), $payment_method));
5571 + $bclass = esc_attr($payment_method);
5572 + $sec = esc_attr($_REQUEST['sec']);
5573 + $content = "";
5574 + $content .= "<p id=waiting>" . __("Please wait while we are preparing your order", 'woo-vipps') . "...</p>";
5575 + $content .= '<div class="vipps-cart-purchase" style="visibility:hidden">"';
5576 + $content .= "<a href='javascript:void(0)' class='vipps-express-checkout short $bclass' data-vipps-autostart='true' data-sec='$sec' title='$btitle'>";
5577 + $content .= $this->get_html_button_for_context('global');
5578 + $content .="</a>";
5579 + $content .="</div>";
5451 5580
5452 - // This method tries to ensure that a customer does not 'lose' the return page and
5453 - // starts ordering the same products twice. IOK 2020-01-22
5454 - protected function validate_express_checkout_orderspec ($orderspec) {
5455 - if (empty($orderspec)) return true; // It's not a duplicate, it's nothing.
5456 -
5457 - // First build for the current order an array of hash-tables keyed by prodid, varid and quantity.
5458 - $orderset = array();
5459 - foreach($orderspec as $entry) $orderset[] = join(':', $entry);
5460 -
5461 - // Then get open orders
5462 - $sessionorders = array();
5463 - $sessionorderdata = WC()->session->get('_vipps_session_orders');
5464 - if ($sessionorderdata) {
5465 - foreach(array_keys($sessionorderdata) as $oid) {
5466 - $orderobject = wc_get_order($oid);
5467 - // Check to see that this hasn't been deleted yet IOK 2020-01-07
5468 - if ($orderobject instanceof WC_Order) {
5469 - $sessionorders[] = $orderobject;
5470 - }
5471 - }
5472 - }
5473 - // Nothing more to do here
5474 - if (empty($sessionorders)) return true;
5475 -
5476 - // And create a similar hash table for each of the open orders
5477 - $openorderdata = array();
5478 - foreach ($sessionorders as $open_order) {
5479 - $status = $open_order->get_status();
5480 - if ($status == 'cancelled' || $status == 'pending') continue;
5481 - $when = strtotime($open_order->get_date_modified());
5482 - $cutoff = $when + apply_filters('woo_vipps_recent_order_cutoff', (5*60));
5483 - if (time() > $cutoff) {
5484 - continue;
5485 - }
5486 - $orderdata = array();
5487 - foreach($open_order->get_items() as $item) {
5488 - $productspec = $item->get_product_id() . ':' . $item->get_variation_id() . ':' . $item->get_quantity();
5489 - $orderdata[] = $productspec;
5490 - }
5491 - $openorderdata[]=$orderdata;
5492 - }
5493 -
5494 - // Now: For each entry in the orderhash, check if there is an order that has a) all of them and b) not any more of them.
5495 - foreach($openorderdata as $prevorder) {
5496 - $a = array_diff($prevorder, $orderset);
5497 - $b = array_diff($orderset, $prevorder);
5498 - if (empty($a) && empty($b)) {
5499 - $this->log(__("It seems a customer is trying to re-order product(s) recently bought in the same session, asking user for confirmation", 'woo-vipps'), 'info');
5500 - return false;
5501 - }
5502 - }
5503 - // Else, order is good.
5504 - return true;
5581 + return $content;
5505 5582 }
5506 5583
5507 - // Returns a triple of productid, variantid and quantity from an array of arguments which can pass either these or a SKU value.
5508 - // Return value is like in a cart.
5509 - // Used to create an order in express checkout, and to see that this order isn't a repeat. IOK 2020-01-22
5510 - protected function get_orderspec_from_arguments ($productinfo) {
5511 - if (!$productinfo) return array();
5512 - $variantid = 0;
5513 - $productid = 0;
5514 - $quantity = intval(@$productinfo['quantity']);
5515 - if (!$quantity) $quantity = 1;
5516 - if (isset($productinfo['sku']) && $productinfo['sku']) {
5517 - $sku = $productinfo['sku'];
5518 - $skuid = wc_get_product_id_by_sku($sku);
5519 - $product = wc_get_product($skuid);
5520 - $parentid = $product ? $product->get_parent_id() : null;
5521 - if ($product) {
5522 - if ($parentid) {
5523 - $variantid = $skuid; $productid = $parentid;
5524 - } else {
5525 - $productid = $skuid;
5526 - }
5527 - }
5528 - } else if (isset($productinfo['product_id']) && $productinfo['product_id']) {
5529 - $productid = intval($productinfo['product_id']);
5530 - $variantid = intval(@$productinfo['variation_id']);
5531 - }
5532 - if ($productid) return array(array('product_id'=>$productid, 'variation_id'=>$variantid, 'quantity'=>$quantity));
5533 - return array();
5534 - }
5535 - // If no productinfo, this will produce an orderspec from the current cart IOK 2020-01-24
5536 - protected function get_orderspec_from_cart () {
5537 - $cartitems = WC()->cart->get_cart();
5538 - $orderspec = array();
5539 - foreach($cartitems as $item => $values) {
5540 - $orderspec[] = array('product_id'=>$values['product_id'], 'variation_id'=>$values['variation_id'], 'quantity'=>$values['quantity']);
5541 - }
5542 - return $orderspec;
5543 - }
5544 -
5545 - // Used as a landing page for launching express checkout - borh for the cart and for single products. IOK 2018-09-28
5546 - // Returns the html. LP 2026-08-27
5547 - protected function express_checkout_page_html($execute,$action,$productinfo=null) {
5548 - $gw = $this->gateway();
5549 -
5550 - $expressCheckoutMessages = array();
5551 - $expressCheckoutMessages['termsAndConditionsError'] = __( 'Please read and accept the terms and conditions to proceed with your order.', 'woocommerce' );
5552 - $expressCheckoutMessages['temporaryError'] = sprintf(__('%1$s is temporarily unavailable.','woo-vipps'), $this->get_payment_method_name());
5553 - $expressCheckoutMessages['successMessage'] = sprintf(__('To the %1$s app!','woo-vipps'), $this->get_payment_method_name());
5554 -
5555 - wp_register_script('vipps-express-checkout',plugins_url('js/express-checkout.js',__FILE__),array('jquery','wp-hooks'),filemtime(dirname(__FILE__) . "/js/express-checkout.js"), 'true');
5556 - wp_localize_script('vipps-express-checkout', 'VippsCheckoutMessages', $expressCheckoutMessages);
5557 - wp_enqueue_script('vipps-express-checkout');
5558 - // If we have a valid nonce when we get here, just call the 'create order' bit at once. Otherwise, make a button
5559 - // to actually perform the express checkout.
5560 - $buttonhtml = apply_filters('woo_vipps_express_checkout_button', $this->get_html_button());
5561 -
5562 -
5563 -
5564 - $orderspec = $this->get_orderspec_from_arguments($productinfo);
5565 - if (empty($orderspec)) {
5566 - $orderspec = $this->get_orderspec_from_cart();
5567 - }
5568 - $orderisOK = $this->validate_express_checkout_orderspec($orderspec);
5569 - $orderisOK = apply_filters('woo_vipps_validate_express_checkout_orderspec', $orderisOK, $orderspec);
5570 -
5571 - $askForTerms = function_exists('wc_terms_and_conditions_checkbox_enabled') ? wc_terms_and_conditions_checkbox_enabled() : true;
5572 - $askForTerms = $askForTerms && ($gw->get_option('expresscheckout_termscheckbox') == 'yes');
5573 - $askForTerms = apply_filters('woo_vipps_express_checkout_terms_and_conditions_checkbox_enabled', $askForTerms);
5574 -
5575 - $askForConfirmationHTML = '';
5576 - if (!$orderisOK) {
5577 - $header = __("Are you sure?",'woo-vipps');
5578 - $body = __("You recently completed an order with exactly the same products as you are buying now. There should be an email in your inbox from the previous purchase. Are you sure you want to order again?",'woo-vipps');
5579 - $askForConfirmationHTML = apply_filters('woo_vipps_ask_user_to_confirm_repurchase', "<h2 class='confirmVippsExpressCheckoutHeader'>$header</h2><p>$body</p>");
5580 - }
5581 - // Should we go directly to checkout, or do we need to stop and ask the user something (for instance?) IOK 2010-01-20
5582 - $execute = $execute && $orderisOK && !$askForTerms;
5583 - $execute = apply_filters('woo_vipps_checkout_directly_to_vipps', $execute, $productinfo);
5584 -
5585 - $content = $this->spinner();
5586 -
5587 - // We impersonate the woocommerce-checkout form here mainly to work with the Pixel Your Site plugin IOK 2022-11-24
5588 - // The form data below is sent on order creation; the sec is also used to poll session status
5589 - $classlist = apply_filters("woo_vipps_express_checkout_form_classes", "woocommerce-checkout");
5590 - $content .= "<form id='vippsdata' class='" . esc_attr($classlist) . "'>";
5591 - $content .= "<input type='hidden' name='action' value='" . esc_attr($action) ."'>";
5592 - if ($this->gateway()->get_option('vippsorderattribution') == 'yes') {
5593 - // This is for the new order attribution feature of woo. IOK 2024-01-09
5594 - $content .= '<input type="hidden" id="vippsorderattribution" value="1" />';
5595 - ob_start();
5596 - do_action( 'woocommerce_after_order_notes');
5597 - $content .= ob_get_clean();
5598 - }
5599 - $content .= wp_nonce_field('do_express','sec',1,false);
5600 -
5601 - $termsHTML = '';
5602 - if ($askForTerms) {
5603 - // Include shop terms
5604 - ob_start();
5605 - wc_get_template('checkout/terms.php');
5606 - $termsHTML = ob_get_clean();
5607 - $termsHTML = apply_filters('woo_vipps_express_checkout_terms_and_conditions_html',$termsHTML);
5608 - }
5609 - $termsHTML = apply_filters('woo_vipps_express_checkout_terms_and_conditions_html',$termsHTML);
5610 -
5611 - if ($productinfo) {
5612 - foreach($productinfo as $key=>$value) {
5613 - $k = esc_attr($key);
5614 - $v = esc_attr($value);
5615 - $content .= "<input type='hidden' name='$k' value='$v' />";
5616 - }
5617 - }
5618 - ob_start();
5619 - $content .= do_action('woo_vipps_express_checkout_orderspec_form', $productinfo);
5620 - $content .= ob_get_clean();
5621 - $content .= "</form>";
5622 -
5623 - $extraHTML = apply_filters('woo_vipps_express_checkout_final_html', '', $termsHTML,$askForConfirmationHTML);
5624 - $pressTheButtonHTML = "";
5625 - if (empty($termsHTML) && empty($askForConfirmationHTML) && empty($extraHTML)) {
5626 - $pressTheButtonHTML = "<p id=waiting>" . sprintf(__('Ready for %1$s - press the button', 'woo-vipps'), Vipps::ExpressCheckoutName()) . "</p>";
5627 - }
5628 -
5629 - if ($execute) {
5630 - $content .= "<p id=waiting>" . __("Please wait while we are preparing your order", 'woo-vipps') . "</p>";
5631 - $content .= "<div id='vipps-status-message'></div>";
5632 - return $this->special_page_html('', $content);
5633 - } else {
5634 - $content .= $askForConfirmationHTML;
5635 - $content .= $extraHTML;
5636 - $content .= $termsHTML;
5637 - $content .= apply_filters('woo_vipps_express_checkout_validation_elements', '');
5638 - $title = sprintf(__('Buy now with %1$s!', 'woo-vipps'), $this->get_payment_method_name());
5639 - $content .= "<div class='vipps_buy_now_wrapper noloop'><a href='#' id='do-express-checkout' class='vipps-express-checkout' title='$title'>$buttonhtml</a></div>";
5640 - $content .= "<div id='vipps-status-message'></div>";
5641 - return $this->special_page_html('', $content);
5642 - }
5643 - }
5644 -
5645 -
5646 5584 // Called in template_redirect before we get to the wait-for-payment page IOK 2026-09-21
5647 5585 private function handle_payment_poll_and_redirect () {
5648 5586 $orderid = WC()->session->get('_vipps_pending_order');
5587 +
5649 5588 $order = null;
5650 5589 $gw = $this->gateway();
5651 5590
5652 5591 // Failsafe for when the session disappears IOK 2018-11-19
@@ -5675,9 +5614,14 @@
5675 5614 $session = WC()->session;
5676 5615 if (!$session->has_session()) {
5677 5616 $session->set_customer_session_cookie(true);
5678 5617 }
5618 +
5619 + $sessionorders= WC()->session->get('_vipps_session_orders');
5620 + $sessionorders[$orderid] = 1;
5621 + WC()->session->set('_vipps_session_orders',$sessionorders);
5679 5622 $session->set('_vipps_pending_order', $orderid);
5623 + WC()->session->save_data();
5680 5624 }
5681 5625 }
5682 5626
5683 5627 $deleted_order=0;
@@ -5683,9 +5627,9 @@
5683 5627 $deleted_order=0;
5684 5628 if ($orderid && !$order) {
5685 5629 // If this happens, we actually did have an order, but it has been deleted, which must mean that it was cancelled.
5686 5630 // Concievably a hook on the 'cancel'-transition or in the callback handlers could clean that up before we get here. IOK 2019-09-26
5687 - $this->log(__("In order return: The order %1\$d seems to be deleted", 'woo-vipps'), 'debug');
5631 + $this->log(sprintf(__("In order return: The order %1\$d seems to be deleted", 'woo-vipps'), $orderid), 'debug');
5688 5632 $deleted_order=1;
5689 5633 }
5690 5634
5691 5635 if (!$order && !$deleted_order) wp_die(__('Unknown order', 'woo-vipps'));
@@ -5695,12 +5639,13 @@
5695 5639
5696 5640 // This is for debugging only - set to false to ensure we wait for the callback. IOK 2023-08-04
5697 5641 $do_poll = true;
5698 5642
5699 - // Still pending, no callback. Make a call to the server as the order might not have been created. IOK 2018-05-16
5643 + // Do a single poll here to check and set the order status at Woo using the order status at Vipps IOK 2026-09-29
5700 5644 if ($do_poll && $status == 'pending') {
5701 - // Just in case the callback hasn't come yet, do a quick check of the order status at Vipps.
5702 - $newstatus = $gw->callback_check_order_status($order);
5645 + // We will do *one* poll before waiting for the callback (for a while, at least.) IOK 2026-09-29
5646 + $newstatus = $gw->poll_and_check_order_status($order);
5647 + $this->log(sprintf(__("In order return: Order status of %1\$d is %2\$s", 'woo-vipps'), $orderid, $newstatus), 'info');
5703 5648 if ($status != $newstatus) {
5704 5649 $status = $newstatus;
5705 5650 clean_post_cache($orderid);
5706 5651 $order = wc_get_order($orderid); // Reload order object
@@ -5708,8 +5653,10 @@
5708 5653 } else {
5709 5654 // No need to do anyting here. IOK 2020-01-26
5710 5655 }
5711 5656
5657 + // Actually, this may cause a second poll if the first left us pending. Should be rewritten - but *mostly* it will just check
5658 + // the payment status at Vipps without polls, which will tell us if the payment succeeded in case people use custom order statuses and so on. IOK 2026-09-29
5712 5659 $payment = 'notchecked';
5713 5660 if ($do_poll) {
5714 5661 $payment = $deleted_order ? 'cancelled' : $gw->check_payment_status($order);
5715 5662 }
@@ -5744,8 +5691,10 @@
5744 5691 // If not, enqueue the status checker IOK 2026-09-21
5745 5692 wp_enqueue_script('check-vipps',plugins_url('js/check-order-status.js',__FILE__),array('jquery','vipps-gw'),filemtime(dirname(__FILE__) . "/js/check-order-status.js"), 'true');
5746 5693 }
5747 5694
5695 + $this->log(sprintf(__("Order status of %1\$d not ready in order return: payment status %2\$s", 'woo-vipps'), $orderid, $payment), 'info');
5696 +
5748 5697 // Communicate this to the shortcode IOK 2026-09-21
5749 5698 add_filter('woo_vipps_wait_for_payment_status', function () use($orderid, $status, $payment) {
5750 5699 return ['orderid'=>$orderid, 'status'=>$status, 'payment'=>$payment];
5751 5700 });
@@ -5752,9 +5701,8 @@
5752 5701
5753 5702 }
5754 5703
5755 5704 public function vipps_wait_for_payment() {
5756 -
5757 5705 // This will have been computed in template_redirect, but the status will be either still pending or failed. IOK 2026-09-21
5758 5706 $data = apply_filters('woo_vipps_wait_for_payment_status', []);
5759 5707
5760 5708 $orderid = $data['orderid'] ?? 0;
@@ -5794,9 +5742,8 @@
5794 5742 $content .= "<input type='hidden' name='key' value='".htmlspecialchars($order->get_order_key())."'>";
5795 5743 $content .= "<input type='hidden' name='action' value='check_order_status'>";
5796 5744 $content .= wp_nonce_field('vippsstatus','sec',1,false);
5797 5745 $content .= "</form>";
5798 -
5799 5746
5800 5747 $content .= "<div id='error' style='display:none'><p>".__('Error during order confirmation','woo-vipps'). '</p>';
5801 5748 $content .= "<p>" . __('An error occured during order confirmation. The error has been logged. Please contact us to determine the status of your order', 'woo-vipps') . "</p>";
5802 5749 $content .= "<p><a href='" . home_url() . "' class='btn button'>" . __('Continue shopping','woo-vipps') . '</a></p>';