PluginProbe
Pay with Vipps and MobilePay for WooCommerce / 6.1.5
Pay with Vipps and MobilePay for WooCommerce v6.1.5
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 6.0.0 5.4.3 5.4.2 5.4.1 5.4.0 5.3.4 All 184 releases
woo-vipps / payment / WC_Gateway_Vipps.class.php

WC_Gateway_Vipps.class.php in Pay with Vipps and MobilePay for WooCommerce 6.1.5, at payment/WC_Gateway_Vipps.class.php

4,442 lines 245.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /*
3 Delegate class for talking to Vipps MobilePay, encapsulating all the low-level behaviour and mapping error codes to exceptions
4
5 This file is part of the plugin Pay with Vipps and MobilePay for WooCommerce
6 Copyright (c) 2019 WP-Hosting AS
7
8 MIT License
9
10 Copyright (c) 2019 WP-Hosting AS
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29
30 */
31 if ( ! defined('ABSPATH') ) {
32 exit; // Exit if accessed directly
33 }
34 require_once(dirname(__FILE__) . "/VippsApi.class.php");
35
36 class WC_Gateway_Vipps extends WC_Payment_Gateway {
37 public $form_fields = null;
38 public $dev_form_fields = null;
39 public $id = 'vipps';
40 public $icon = '';
41 public $has_fields = true;
42 public $method_title = 'Vipps MobilePay';
43 public $title = 'Vipps MobilePay';
44 public $method_description = "";
45 public $apiurl = null;
46 public $testapiurl = null;
47 public $api = null;
48 public $supports = null;
49 public $express_checkout_supported_product_types;
50
51 public $captured_statuses;
52
53 private static $instance = null; // This class uses the singleton pattern to make actions easier to handle
54
55 protected $keyset = null; // This will contain all api keys etc for the gateway, keyed on the merchant serial number.
56
57 // Just to avoid calculating these alot
58 private $page_templates = null;
59 private $page_list = null;
60
61
62
63 // This returns the singleton instance of this class
64 public static function instance() {
65 if (null === self::$instance) {
66 self::$instance = new self();
67 }
68 return self::$instance;
69 }
70
71 public function add_image_upload_setting_widget () {
72 add_action('admin_enqueue_scripts', function ($suff) {
73 if ($suff == 'woocommerce_page_wc-settings' && (($_REQUEST['section'] ?? false) == 'vipps')) {
74 if (!did_action('wp_enqueue_media')) {
75 wp_enqueue_media();
76 }
77 }
78 });
79 }
80
81
82 // Generates html for the woo_vipps_image settings widget type
83 public function generate_woo_vipps_image_html ($key, $field) {
84 $field_key = $this->get_field_key( $key );
85 $defaults = array(
86 'title' => '',
87 'disabled' => false,
88 'class' => '',
89 'css' => '',
90 'placeholder' => '',
91 'type' => 'woo_vipps_image',
92 'desc_tip' => false,
93 'description' => '',
94 'custom_attributes' => array(),
95 );
96 $data = wp_parse_args( $field, $defaults );
97
98 $imgid = intval($this->get_option($key));
99 $image = $imgid ? wp_get_attachment_image_src($imgid) : "";
100
101 ob_start();
102 ?>
103 <tr valign="top">
104 <th scope="row" class="titledesc">
105 <label for="<?php echo esc_attr( $field_key ); ?>"><?php echo wp_kses_post( $data['title'] ); ?> <?php echo $this->get_tooltip_html( $data ); // WPCS: XSS ok. ?></label>
106 </th>
107 <td class="forminp">
108 <fieldset>
109 <legend class="screen-reader-text"><span><?php echo wp_kses_post( $data['title'] ); ?></span></legend>
110 <?php if ($image): ?>
111 <a href="#" class="woo-vipps-image-upload"><img style="max-width: 360px; max-height: 360px" src="<?php echo $image[0]; ?>" /><span style="display:none" class='uploadtext'><?php _e('Upload image', 'woo-vipps'); ?></span></a>
112 <a href="#" class="woo-vipps-image-remove"><?php _e('Remove image', 'woo-vipps');?></a>
113 <?php else: ?>
114 <a href="#" class="woo-vipps-image-upload"><img style="display:none; max-width:360px; max-height: 360px"/><span class='uploadtext'><?php _e('Upload image', 'woo-vipps'); ?></span></a>
115 <a href="#" class="woo-vipps-image-remove" style="display:none;"><?php _e('Remove image', 'woo-vipps');?></a>
116 <?php endif; ?>
117 <input type="hidden" class="woo-vipps-image-input <?php echo esc_attr( $data['class'] ); ?>" name="<?php echo esc_attr( $field_key ); ?>" id="<?php echo esc_attr( $field_key ); ?>" value="<?php echo esc_attr($imgid); ?>" <?php echo $this->get_custom_attribute_html( $data ); // WPCS: XSS ok. ?> />
118 <?php echo $this->get_description_html( $data ); // WPCS: XSS ok. ?>
119 </fieldset>
120 </td>
121 </tr>
122 <?php
123
124 return ob_get_clean();
125 }
126
127 // Attempts to detect the current country based on the store's currency NT-2024-10-15
128 private function detect_country_from_currency() {
129 $currency = get_woocommerce_currency();
130 switch ($currency) {
131 case 'DKK':
132 return 'DK';
133 case 'NOK':
134 return 'NO';
135 case 'SEK':
136 return 'SE';
137 case 'EUR':
138 return 'FI';
139 default:
140 return null;
141 }
142 }
143 // Migrates the keysets to include the country setting if it's missing
144 // This is an initial migration step to ensure the country setting is explicitly set.
145 // We do this because we no longer want to automatically guess payment method name. NT-2024-10-15
146 private function migrate_keyset_with_country_detection() {
147 $settings = get_option('woocommerce_vipps_settings', array());
148 if ($settings['country'] ?? false) return; // Already set, do nothing IOK 2024-10-17
149
150 // Now we are only wanting to do this with people who have already configured the plugin. These will have at least this value set:
151 if ($settings['payment_method_name'] ?? false) {
152 // This assumes that EUR == FI which will be correct for all users reaching this branch IOK 2024-10-17
153 $detected_country = $this->detect_country_from_currency();
154 // If we can't detect the country, there's nothing to migrate. "this cannot happen" etc.
155 if (!$detected_country) return;
156
157 $settings['country'] = $detected_country;
158 update_option('woocommerce_vipps_settings', $settings);
159 delete_transient('_vipps_keyset');
160 return;
161 }
162 }
163
164 public function __construct() {
165 $this->testapiurl = 'https://apitest.vipps.no';
166 $this->apiurl = 'https://api.vipps.no';
167
168 $this->method_description = __('Offer Vipps or MobilePay as a payment method', 'woo-vipps');
169 $this->method_title = __('Vipps MobilePay','woo-vipps');
170 $this->title = __('Vipps MobilePay','woo-vipps');
171
172 $this->icon = plugins_url('img/vmp-logo.png',__FILE__);
173 $this->migrate_keyset_with_country_detection();
174 $this->init_form_fields();
175 $this->init_settings();
176
177
178 $this->api = new VippsApi($this);
179
180 $this->supports = array('products','refunds');
181
182 // we need to disallow certain types of refunds; mostly manual refunds done before capture. IOK 2026-02-24
183 add_action( 'woocommerce_create_refund', array($this, 'woocommerce_create_refund'), 10, 2);
184
185 // We can't guarantee any particular product type being supported, so we must enumerate those we are certain about
186 // IOK 2020-04-21 Add support for WooCommerce Product Bundles
187 $supported_types= array('simple','variable','variation','bundle', 'yith_bundle', 'gift-card');
188 $this->express_checkout_supported_product_types = apply_filters('woo_vipps_express_checkout_supported_product_types', $supported_types);
189
190 add_action('woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options') );
191 add_action('admin_init', array($this, 'add_image_upload_setting_widget'));
192
193 // Capturing, refunding and cancelling the order when transitioning states:
194 // This are the statuses for which the Vipps MobilePay plugin should try to ensure capture has been made.
195 // Normally, this is 'processing' and 'completed', but plugins may define other statuses. IOK 2018-10-05
196 // It is also possible to remove 'processing' from this list. If you do, you may use it as the end-state of the
197 // Vipps MobilePay transaction (see below in after_vipps_order_status) IOK 2018-12-05
198 $resultstatus = $this->get_option('result_status');
199 $captured_statuses = apply_filters('woo_vipps_captured_statuses', array('processing', 'completed'));
200 $captured_statuses = array_diff($captured_statuses, array($resultstatus));
201
202 $this->captured_statuses = $captured_statuses;
203
204 $non_completed_captured_statuses = array_diff($captured_statuses, array('completed'));
205
206 // This ensures that funds are captured when transitioning from 'on hold' to a status where the money
207 // should be captured, and refunded when moved from this status to cancelled or refunded
208 foreach($captured_statuses as $capstatus) {
209 add_action('woocommerce_order_status_' . $capstatus, array($this, 'maybe_capture_payment'));
210 }
211 // We will refund money on cancelled orders, but only if they are *relatively new*. This is to
212 // avoid accidents and issues where old orders are *somehow* cancelled even though they are complete. IOK 2024-08-12
213 add_action('woocommerce_order_status_cancelled', array($this, 'maybe_cancel_order'));
214 // Add a full refund if neccessary *before* woocommerce does, on priority 10 IOK 2026-01-28
215 add_action('woocommerce_order_status_refunded', array($this, 'maybe_refund_order'), 9, 1);
216
217 // Possibly delete orders that never went anywhere
218 add_action('woocommerce_order_status_pending_to_cancelled', array($this, 'maybe_delete_order'), 99999, 1);
219 // Handle orders when authorized
220 add_action('woocommerce_payment_complete', array($this, 'order_payment_complete'), 10, 1);
221
222 // when an order is complete, we need to check if there is reserved amount that is not captured
223 // if so, we need to cancel this amount PMB 2024-11-21
224 // nb: note very late priority - we must have captured before, please
225 // Also for orders that have been partially or completely refunded, or need to be set to cancelled IOK 2026-01-26
226 add_action('woocommerce_order_status_completed', array($this, 'maybe_cancel_reserved_amount'), 99);
227 add_action('woocommerce_order_status_refunded', array($this, 'maybe_cancel_reserved_amount'), 99, 1);
228 add_action('woocommerce_order_status_cancelled', array($this, 'maybe_cancel_reserved_amount'), 99, 1);
229
230 // New handling for callbacks in the action scheduler. LP 2026-03-27
231 add_action('woo_vipps_action_process_callback', [$this, 'action_process_callback'], 10, 4);
232
233 // Endpoint for setting shipping data for express checkout orders. LP 2026-03-30
234 add_action('rest_api_init', function() {
235 register_rest_route(Vipps::get_rest_namespace('v1'), '/order-set-shipping', [
236 'methods' => 'POST',
237 'callback' => [$this, 'rest_order_set_shipping'],
238 'permission_callback' => function($request) {
239 // Note: permission callbacks run twice, on purpose. LP 2026-04-01
240 // https://github.com/WP-API/WP-API/issues/2400
241 $input_token = $request->get_header('X-WooVipps-Token');
242
243 $order_id = $request->get_param('order_id');
244
245 $order = wc_get_order($order_id);
246 if (!is_a($order, 'WC_Order')) {
247 return new WP_Error('order_not_found', __('Order not found', 'woo-vipps'), ['status' => 404, 'order_id' => $order_id]);
248 }
249
250 // a small bit of security
251 $auth_token = $order->get_meta('_vipps_authtoken');
252 if (!$input_token || !$auth_token || !hash_equals($input_token, $auth_token)) {
253 /* translators: endpoint path, order id */
254 $this->log(sprintf(__('Wrong authtoken for rest endpoint %1$s for order %2$s', 'woo-vipps'), '/order-set-shipping', $order_id), 'warning');
255 return false;
256 }
257 return true;
258
259 },
260 'args' => [
261 'order_id' => [
262 'required' => true,
263 'validate_callback' => fn($param, $request, $key) => is_numeric($param),
264 'sanitize_callback' => fn($param, $request, $key) => intval($param),
265 ],
266 /* Data from Vipps callback or api poll. LP 2026-03-30 */
267 'vipps_order_data' => [
268 'required' => true,
269 'validate_callback' => fn($param, $request, $key) => is_array($param),
270 'sanitize_callback' => fn($param, $request, $key) => map_deep($param, 'sanitize_text_field'),
271 ],
272 ],
273 ]);
274 });
275 }
276
277 // this function is called after an order is changed to complete/refunded/cancelled. It checks if there is reserved money that is not captured
278 // if there still is money reserved, then this amount is cancelled PMB 2024-11-21
279 // Ensure we've updated the vipps status before calling this. IOK 2026-01-28
280 public function maybe_cancel_reserved_amount ($orderid) {
281 $order = wc_get_order($orderid);
282 if (!$order) return;
283 if (! Vipps::is_vipps_order($order)) return false;
284 // Cannot partially cancel legacy ecom orders
285 if ('epayment' != $order->get_meta('_vipps_api')) return false;
286
287 // Check that the normal maybe_capture_order hook has actually ran *and* done something,
288 // it's only after this we know we have captured 'everything' so if there is anything left,
289 // it should be cancelled. IOK 2025-05-04
290 // Also set in maybe_cancel and maybe_refund now - in all "final status" hooks. IOK 2026-01-28
291 if (! $order->get_meta('_vipps_capture_complete')) {
292 return false;
293 }
294
295 $order_status = $order->get_status();
296
297 if ('completed' == $order_status) {
298 // For safety, on completed orders also only want to do this for orders that have had *something* captured. IOK 2025-02-04
299 $captured = intval($order->get_meta('_vipps_captured'));
300 if ($captured < 1) {
301 return false;
302 }
303 }
304 if ('cancelled' != $order_status) {
305 // If not in the 'cancelled' state, allow merchants that do not reserve large amounts to opt out for safety IOK 2025-02-04
306 if (apply_filters('woo_vipps_never_cancel_uncaptured_money', false, $order)) {
307 return false;
308 }
309 }
310
311 $ok = true;
312
313 $remaining = intval($order->get_meta('_vipps_capture_remaining'));
314
315 if ($remaining > 0) {
316 $this->log(sprintf(__("maybe_cancel_reserved_amount we have remaining reserved after capture of total %1\$s ",'woo-vipps'), $remaining),'debug');
317 } else {
318 // IOK 2026-06-15 Nothing left to cancel, just return
319 return false;
320 }
321
322 $currency = $order->get_currency();
323 try {
324 $ok = $this->cancel_payment($order);
325 if ($ok && $remaining && 'completed' == $order_status) {
326 $amount = number_format($remaining/100, 2) . " " . $currency;
327 $note = sprintf(__('Order %1$s: %2$s is cancelled to free up the reservation in the customers bank account.', 'woo-vipps'), $orderid, $amount);
328 $order->add_order_note($note);
329 }
330 } catch (Exception $e) {
331 $ok = false;
332 // if this happens, we just log it - we may not have an active admin
333 $msg = sprintf(__('Was not able to cancel remaining amount for the order %1$s: %2$s','woo-vipps'), $orderid, $e->getMessage());
334 $order->add_order_note($msg);
335 $this->log($msg,'error');
336 }
337
338 // We need to update the order details after the fact. We can't fix errors here though. IOK 2024-11-22
339 try {
340 $this->update_vipps_payment_details($order);
341 } catch (Exception $e) {
342 // noop
343 }
344
345 // we just return true from this function for now PMB 2024-11-21
346 // return false if we couldn't cancel reserved. IOK 2024-11-22
347 return $ok;
348 }
349
350
351 public function get_icon () {
352 $src = $this->icon;
353 if ($this->get_payment_method_name() == "Vipps") {
354 $src = plugins_url('img/vipps-mark.svg',__FILE__);
355 } else {
356 $src = plugins_url('img/mobilepay-mark.png',__FILE__);
357 }
358 return '<img src="' . esc_attr($src) . '" alt="' . $this->get_payment_method_name() . '">';
359 }
360
361
362 // True iff this gateway is currently in test mode. IOK 2019-08-30
363 public function is_test_mode() {
364 if (VIPPS_TEST_MODE) return true;
365 if ($this->get_option('developermode') == 'yes' && $this->get_option('testmode') == 'yes') return true;
366 return false;
367 }
368 // These abstraction gets the correct client id and so forth based on whether or not test mode is on
369 // "test mode" is now per MSN, so we accept that as an argument IOK 2023-12-19
370 public function apiurl ($msn="") {
371 $msn = $msn ?? $this->get_merchant_serial();
372 $keyset = $this->get_keyset();
373 $entry = $keyset ? ($keyset[$msn] ?? null) : null;
374 if (!$entry) {
375 $testmode = $this->is_test_mode();
376 } else {
377 $testmode = $entry['testmode'];
378 }
379 if ($testmode) return $this->testapiurl;
380 return $this->apiurl;
381 }
382
383 // This returns the *current* merchant serial number. There may be more than one, for instance if the test mode is on.
384 // IOK 2023-12-19
385 public function get_merchant_serial() {
386 $merch = $this->get_option('merchantSerialNumber');
387 $testmerch = @$this->get_option('merchantSerialNumber_test');
388 if (!empty($testmerch) && $this->is_test_mode()) return $testmerch;
389 return $merch;
390 }
391
392 // Returns a table of all the keydata of this instance, keyed on MSN. IOK 2023-12-19
393 public function get_keyset() {
394 if ($this->keyset) return $this->keyset;
395 $stored = get_transient('_vipps_keyset');
396 if ($stored) {
397 return $stored;
398 }
399
400 $keyset = [];
401 $main = $this->get_option('merchantSerialNumber');
402 if ($main) {
403 $data = ['client_id'=>$clientid=$this->get_option('clientId'),
404 'client_secret' => $this->get_option('secret'),
405 'sub_key'=>$this->get_option('Ocp_Apim_Key_eCommerce'),
406 'country' => $this->get_option('country'),
407 'gw' => 'vipps'
408 ];
409 if (! in_array(false, array_map('boolval', array_values($data)))) {
410 $data['testmode'] = 0; // Must add after
411 $keyset[$main] = $data;
412 }
413 }
414
415 $test = @$this->get_option('merchantSerialNumber_test');
416 $testmode = @$this->get_option('testmode');
417 if ($testmode === 'yes' && $test) {
418 $data = [
419 'client_id'=>$clientid=$this->get_option('clientId_test'),
420 'client_secret' => $this->get_option('secret_test'),
421 'sub_key'=>$this->get_option('Ocp_Apim_Key_eCommerce_test'),
422 'country' => $this->get_option('country'),
423 'gw' => 'vipps'
424 ];
425
426 if (! in_array(false, array_map('boolval', array_values($data)))) {
427 $data['testmode'] = 1;
428 $keyset[$test] = $data;
429 }
430 }
431
432 $this->keyset = $keyset;
433 set_transient('_vipps_keyset', $keyset, DAY_IN_SECONDS);
434 return $keyset;
435 }
436
437 // Get and show any keysets from the Vipps Recurring plugin too IOK 2024-11-29
438 private function get_recurring_keysets () {
439 $res = [];
440 $settings = get_option( 'woocommerce_vipps_recurring_settings' );
441 if (empty($settings)) return $res;
442
443 $country = $this->get_option('country');
444
445 $client_id = $settings["client_id"] ?? "";
446 $client_secret = $settings["secret_key"] ?? "";
447 $subscription_key = $settings["subscription_key"] ?? "";
448 $merchant_serial_number = $settings["merchant_serial_number"] ?? "";
449 if ($merchant_serial_number && $client_id && $client_secret && $subscription_key ) {
450 $res[$merchant_serial_number] = ['client_id' => $client_id, 'client_secret' => $client_secret, 'sub_key' => $subscription_key, 'country' => $country, 'testmode' => 0, 'gw'=>'vipps_recurring'];
451 }
452
453 $client_id = $settings["test_client_id"] ?? "";
454 $client_secret = $settings["test_secret_key"] ?? "";
455 $subscription_key = $settings["test_subscription_key"] ?? "";
456 $merchant_serial_number = $settings["test_merchant_serial_number"] ?? "";
457 if ($merchant_serial_number && $client_id && $client_secret && $subscription_key ) {
458 $res[$merchant_serial_number] = ['client_id' => $client_id, 'client_secret' => $client_secret, 'sub_key' => $subscription_key, 'country' => $country, 'testmode' => 1, 'gw'=>'vipps_recurring'];
459 }
460 return $res;
461 }
462
463 // Return all webhooks for our MSNs
464 public function get_webhooks_from_vipps () {
465 $keys = $this->get_keyset();
466 $hooks = [];
467 foreach($keys as $msn=>$data) {
468 try {
469 $hooks[$msn] = $this->api->get_webhooks($msn);
470 } catch (Exception $e) {
471 $this->log(sprintf(__('Could not get webhooks for Merchant Serial Number %1$s: %2$s', 'woo-vipps'), $msn, $e->getMessage()), 'error');
472 $hooks[$msn]=[];
473 }
474 }
475 return $hooks;
476 }
477
478
479 // The rest of the settings gets the correct client id, secret, sub key and order prefix based on the MSN.
480 public function get_clientid($msn="") {
481 if (!$msn) $msn = $this->get_merchant_serial();
482 $keyset = $this->get_keyset();
483 if (!isset($keyset[$msn])) return false;
484 return $keyset[$msn]['client_id'];
485 }
486 public function get_secret($msn="") {
487 if (!$msn) $msn = $this->get_merchant_serial();
488 $keyset = $this->get_keyset();
489 if (!isset($keyset[$msn])) return false;
490 return $keyset[$msn]['client_secret'];
491 }
492 public function get_key($msn="") {
493 if (!$msn) $msn = $this->get_merchant_serial();
494 $keyset = $this->get_keyset();
495 if (!isset($keyset[$msn])) return false;
496 return $keyset[$msn]['sub_key'];
497 }
498 public function get_country($msn="") {
499 if (!$msn) $msn = $this->get_merchant_serial();
500 $keyset = $this->get_keyset();
501 if (!isset($keyset[$msn])) return false;
502 return $keyset[$msn]['country'];
503 }
504
505 public function get_orderprefix() {
506 $prefix = $this->get_option('orderprefix');
507 return $prefix;
508 }
509
510 // We did shenanigans here earlier, we don't have to do that anymore. IOK 2022-12-09
511 public function get_return_url($order=null) {
512 $url = parent::get_return_url($order);
513 return $url;
514 }
515
516
517 // Delete express checkout orders with no customer information - these were abandonend before the app started.
518 // IOK 2019-08-26
519 public function maybe_delete_order ($orderid) {
520 $order = wc_get_order($orderid);
521 if (!$order) return;
522 if (! Vipps::is_vipps_order($order)) return false;
523 $express = $order->get_meta('_vipps_express_checkout');
524 if (!$express) return false;
525 $email = $order->get_billing_email();
526 if ($email) return false;
527
528 // Only delete if we have to
529 if ($this->get_option('deletefailedexpressorders') != 'yes') return false;
530 // Mark this order that an order that wasn't completed with any user info - it can be deleted. IOK 2019-11-13
531 $order->update_meta_data('_vipps_delendum',1);
532 $order->save();
533 return true;
534 }
535
536
537 // Return the status to use after return from Vipps MobilePay for orders that are not both "virtual" and "downloadable".
538 // These orders are *not* complete, and payment is *not* captured, which is why the default status is 'on-hold'.
539 // If you use custom order statuses, or if you don't capture on 'processing' - see filter 'woo_vipps_captured_statuses' -
540 // you can instead use 'processing' here - which is much nicer.
541 // If you do so, remember to capture *before* shipping is done on the order - if you send the package and then do 'complete',
542 // the capture may fail. IOK 2018-12-05
543 //
544 // IOK As of 2023-12-22, the default is now 'processing', since this is more in line with what other gateways are using,
545 // what other integrations and plugins expect, the most popular choice by users; and because of the fact that "on-hold" is
546 // normally used to indicate "a problem with the order". Not being able to capture a reserved order has to my knowledge at this
547 // point only happened once, in 2018, with a completely different api and backend.
548 public function after_vipps_order_status($order=null) {
549 // Revert to on-hold if the user tries to set a payment status that is a 'captured' status IOK 2024-01-25
550 $defaultstatus = 'on-hold';
551
552 $chosen = $this->get_option('result_status');
553 $newstatus = apply_filters('woo_vipps_after_vipps_order_status', $chosen, $order);
554
555 if (in_array($newstatus, $this->captured_statuses)){
556 $this->log(sprintf(__("Cannot use %1\$s as status for non-autocapturable orders: payment is captured on this status. See the woo_vipps_captured_statuses-filter.",'woo-vipps'), $newstatus),'debug');
557 return $defaultstatus;
558 }
559 return $newstatus;
560 }
561
562 // Create callback urls' using WC's callback API in a way that works with Vipps MobilePay callbacks and both pretty and not so pretty urls.
563 private function make_callback_urls($forwhat,$token='', $reference=0) {
564 // Passing the token as GET arguments, as the Authorize header is stripped. IOK 2018-06-13
565 // This applies to Ecom, Checkout and Express Checkout callbacks. For epayment, we instead need to use
566 // the webhook api, which is altogether different. IOK 2023-12-19
567 $url = home_url("/", 'https');
568 $queryargs = [];
569 if ($token) $queryargs['tk']=$token;
570 if ($reference) $queryargs['id']=$reference;
571
572 // HTTPS required. IOK 2018-05-18
573 // If the user for some reason hasn't enabled pretty links, fall back to ancient version. IOK 2018-04-24
574 if ( !get_option('permalink_structure')) {
575 $queryargs['wc-api'] = $forwhat;
576 } else {
577 $url = trailingslashit(home_url("wc-api/$forwhat", 'https'));
578 }
579 // And we need to add an empty "callback" query arg as the very last arg to receive the actual callback.
580 // We can't use add_query_arg for that, as an empty argument will remove the equals-sign.
581 $callbackurl = add_query_arg($queryargs, $url) . "&callback=";
582 return $callbackurl;
583 }
584
585 // Webhook callbacks do not pass GET arguments at all, but do provide an X-Vipps-Authorization header for verification. IOK 2023-12-19
586 public function webhook_callback_url () {
587 $url = home_url("/", 'https');
588 $queryargs = ['callback'=>'webhook'];
589 $forwhat = 'wc_gateway_vipps'; // Same callback as for ecom, checkout, express checkout
590 // HTTPS required. IOK 2018-05-18
591 // If the user for some reason hasn't enabled pretty links, fall back to ancient version. IOK 2018-04-24
592 if ( !get_option('permalink_structure')) {
593 $queryargs['wc-api'] = $forwhat;
594 } else {
595 $url = trailingslashit(home_url("wc-api/$forwhat", 'https'));
596 }
597 $callbackurl = add_query_arg($queryargs, $url);
598 return $callbackurl;
599 }
600
601
602 // The main payment callback
603 public function payment_callback_url ($token='', $reference=0) {
604 return $this->make_callback_urls('wc_gateway_vipps',$token, $reference);
605 }
606 public function shipping_details_callback_url($token='',$reference=0) {
607 return $this->make_callback_urls('vipps_shipping_details',$token,$reference);
608 }
609 // Callback for the consetn removal callback. Must use template redirect directly, because wc-api doesn't handle DELETE.
610 // IOK 2018-05-18
611 public function consent_removal_callback_url () {
612 $queryargs = [];
613 $url = home_url("/", 'https');
614 if ( !get_option('permalink_structure')) {
615 $queryargs['vipps-consent-removal']=1;
616 } else {
617 $url = trailingslashit(home_url('vipps-consent-removal', 'https'));
618 }
619 // And we need to add an empty "callback" query arg as the very last arg to receive the actual callback.
620 // We can't use add_query_arg for that, as an empty argument will remove the equals-sign.
621 return add_query_arg($queryargs, $url) . "&callback=";
622 }
623
624 // Allow user to select the template to be used for the special Vipps MobilePay pages. IOK 2020-02-17
625 public function get_theme_page_templates() {
626 if (!$this->page_templates) {
627 $choices = array('' => __('Use default template', 'woo-vipps'));
628 foreach(wp_get_theme()->get_page_templates() as $filename=>$name) {
629 $choices[$filename]=$name;
630 }
631 $this->page_templates = $choices;
632 }
633 return $this->page_templates;
634 }
635
636 // We can't use get_pages to get a default list of pages for our settings, because it triggers
637 // actions that can be used by other plugins. Therefore we must use the database directly and cache the results. IOK 2023-08-22
638 public function get_pagelist () {
639 if (!$this->page_list) {
640 global $wpdb;
641 $page_list = array(''=>__('Use a simulated page (default)', 'woo-vipps'));
642 foreach($wpdb->get_results("SELECT ID,post_title FROM {$wpdb->prefix}posts WHERE post_type='page' and post_status='publish'") as $page) {
643 $page_list[$page->ID] = $page->post_title;
644 }
645 $this->page_list = $page_list;
646 }
647 return $this->page_list;
648 }
649
650 // Check to see if the product in question can be bought with express checkout IOK 2018-12-04
651 public function product_supports_express_checkout($product) {
652 // IOK 2023-12-12 Can only support express checkout for Vipps - not MobilePay (yet!)
653 // IOK 2025-09-01 Now supports mobilepay
654 return apply_filters('woo_vipps_product_supports_express_checkout', $this->product_supports_checkout($product), $product);
655 }
656
657 // Checkout and Express Checkout are very similarily restricted because they both replace the standard
658 // Woo Checkout page, but express checkout is even more restricted, so we need to separate out the commonalities. IOK 2024-01-11
659 public function product_supports_checkout($product) {
660 $type = $product->get_type();
661 $ok = in_array($type, $this->express_checkout_supported_product_types);
662 $ok = apply_filters('woo_vipps_product_supports_checkout',$ok,$product);
663 return $ok;
664 }
665
666 // Almost the same as express checkout - unfortunately not *entirely* the same. IOK 2024-01-11
667 public function cart_supports_checkout($cart=null) {
668 if (!$cart) $cart = WC()->cart;
669 if (!$cart) return false;
670 # Not supported by Vipps MobilePay
671 if ($cart->cart_contents_total <= 0) return false;
672
673 $supports = true;
674 foreach($cart->get_cart() as $key=>$val) {
675 $prod = $val['data'];
676 if (!is_a($prod, 'WC_Product')) continue;
677 $product_supported = $this->product_supports_checkout($prod);
678 if (!$product_supported) {
679 $supports = false;
680 break;
681 }
682 }
683 $supports = apply_filters('woo_vipps_cart_supports_checkout', $supports, $cart);
684 return $supports;
685 }
686
687 // Check to see if the cart passed (or the global one) can be bought with express checkout IOK 2018-12-04
688 public function cart_supports_express_checkout($cart=null) {
689 if (!$cart) $cart = WC()->cart;
690 $supports = true;
691 if (!$cart) return $supports;
692 # Not supported by Vipps MobilePay
693 if ($cart->cart_contents_total <= 0) return false;
694
695 foreach($cart->get_cart() as $key=>$val) {
696 $prod = $val['data'];
697 if (!is_a($prod, 'WC_Product')) continue;
698 $product_supported = $this->product_supports_express_checkout($prod);
699 if (!$product_supported) {
700 $supports = false;
701 break;
702 }
703 }
704 $supports = apply_filters('woo_vipps_cart_supports_express_checkout', $supports, $cart);
705 return $supports;
706 }
707
708 // True if "Express checkout" should be displayed IOK 2018-06-18
709 public function show_express_checkout() {
710 if (!$this->express_checkout_available()) return false;
711 $show = 'yes' == $this->enabled && $this->cart_supports_express_checkout();
712
713 if (is_checkout()) {
714 $show = $show && $this->get_option('express_show_in_checkout') == 'yes';
715 } else { // for cart, and all other contexts, since this is how the method functioned before we checked checkout explicitly. LP 2026-07-02
716 $show = $show && $this->get_option('cartexpress') == 'yes';
717 }
718 // Earlier, we disabled this if Checkout was active; but we will now respect the setting in all
719 // cases. Also, there is a filter. IOK 2026-02-19
720 // Now there is also a separate setting for just checkout, 'express_show_in_checkout'. See above branch. LP 2026-07-01
721
722 return apply_filters('woo_vipps_show_express_checkout', $show);
723 }
724
725 public function show_login_with_vipps() {
726 return false;
727 }
728
729 // Called when orders reach the 'refunded' status. We'll add a complete refund and note that any rest is to be cancelled.
730 public function maybe_refund_order($order_id) {
731 $order = wc_get_order($order_id);
732 if (! Vipps::is_vipps_order($order)) return false;
733 try {
734 $order = $this->update_vipps_payment_details($order);
735 } catch (Exception $e) {
736 //Do nothing with this for now
737 $this->log(__("Error getting payment details before doing refund: ", 'woo-vipps') . $e->getMessage(), 'warning');
738 }
739 $payment = $this->check_payment_status($order);
740 if ($payment == 'initiated' || $payment == 'cancelled') {
741 return true; // Can't refund these
742 }
743
744 // This will create + process a refund for the captured amount (if any). IOK 2026-01-26
745 // We always run this since woo will create a manual refund on this status change: we want the refund to be through our gw instead. LP 2026-06-10
746 $this->wc_order_fully_refunded ($order_id);
747
748 // In any case, note that this order is ready for cancellation - we don't actually do this here anymore
749 $order->update_meta_data('_vipps_capture_complete',true);
750 $order->save();
751 }
752
753 // Called when orders reach the 'cancelled'-status. When this happens, orders will be *refunded*
754 // when they have been captured, but for added safety, this is only done when the orders are relatively new.
755 public function maybe_cancel_order($order_id) {
756 $order = wc_get_order($order_id);
757 if (! Vipps::is_vipps_order($order)) return false;
758
759 try {
760 $order = $this->update_vipps_payment_details($order);
761 } catch (Exception $e) {
762 //Do nothing with this for now
763 $this->log(__("Error getting payment details before doing cancel: ", 'woo-vipps') . $e->getMessage(), 'warning');
764 }
765
766 $payment = $this->check_payment_status($order);
767 if ($payment == 'initiated' || $payment == 'cancelled') {
768 return true; // Can't cancel these
769 }
770
771 $days_threshold = apply_filters('woo_vipps_cancel_refund_days_threshold', 30);
772 $order_date = $order->get_date_created();
773 $days_since_order = (time() - $order_date->getTimestamp()) / (60 * 60 * 24);
774
775 $captured = intval($order->get_meta('_vipps_captured'));
776 $vippsstatus = $order->get_meta('_vipps_status');
777
778 // If we have captured some funds, we must first create a refund for the amount we've captured.
779 // However, we will only do this if the order is relatively fresh, to avoid accidentally refunding
780 // old orders.
781 if ($captured > 0 || $vippsstatus == 'SALE') {
782 // If this is true then the order is *too old to refund* which would happen on maybe_cancel_payment.
783 // add a note instead.
784 if ($days_since_order > $days_threshold) {
785 $note = sprintf(__('Order with captured funds older than %d days cancelled - because the order is this old, it will not be automatically refunded at Vipps. Manual refund may be required.', 'woo-vipps'), $days_threshold);
786 $order->add_order_note($note);
787 // Add an admin notice in case this is interactive
788 $msg = sprintf(__("Could not cancel %1\$s payment", 'woo-vipps'), $this->get_payment_method_name());
789 $this->adminerr(__('Order', 'woo-vipps') . " " . $order->get_id() . ": " . $note);
790 $order->save();
791 Vipps::instance()->store_admin_notices();
792 return false;
793 }
794 // This will create + process a refund for the captured amount. IOK 2026-01-26
795 $this->wc_order_fully_refunded ($order_id);
796 }
797 // In any case, note that this order is ready for cancellation - we don't actually do this here anymore
798 $order->update_meta_data('_vipps_capture_complete',true);
799 $order->save();
800 }
801
802 // IOK 2024-09-01 In general, we can refund most Vipps Mobilepay orders through the api,
803 // however, this is not the case for the Bank Transfer method available through Vipps Checkout.
804 public function can_refund_order( $order ) {
805 $method = $order->get_meta('_vipps_api');
806 switch ($method) {
807 case 'banktransfer':
808 return false;
809 break;
810 case 'epayment':
811 return true;
812 break;
813 // Default is old-style ecom v2.
814 default:
815 return true;
816 break;
817 }
818 }
819
820 // This is ran in woocommerce_order_status_refunded *before* woos own wc_order_fully_refunded (priority 9)
821 // so that we can create a through-the-gateway refund for this if neccessary. That way, *our* logic for refunds occur
822 // instead of the normal woo logic. IOK 2026-04-16
823 public function wc_order_fully_refunded ($orderid) {
824 $order = wc_get_order($orderid);
825 if (! Vipps::is_vipps_order($order)) return false;
826
827 // First check to see if we actually need to refund anything now IOK 2026-02-16
828 $max_refund = wc_format_decimal( $order->get_total() - $order->get_total_refunded() );
829 if ( ! $max_refund ) {
830 return;
831 }
832
833 // IOK 2019-10-03 it is now possible to do capture via other tools than Woo, so we must now first check to see if
834 // the order is capturable by getting full payment details.
835 try {
836 $order = $this->update_vipps_payment_details($order);
837 } catch (Exception $e) {
838 //Do nothing with this for now
839 $this->log(__("Error getting payment details before doing refund: ", 'woo-vipps') . $e->getMessage(), 'warning');
840 }
841
842 $data = [];
843 $data['amount'] = $max_refund;
844 $data['reason'] = __( 'Order fully refunded.', 'woocommerce' );
845 $data['order_id'] = $orderid;
846 $data['refund_payment'] = true; // This should call our "process_refund" instead of adding a manual refund
847
848 // IOK 2026-04-17 Should be all remaining un-refunded line items
849 $line_items = apply_filters('woo_vipps_order_fully_refunded_line_items', $this->get_remaining_refundable_line_items($order), $order);
850 $data['line_items'] = $line_items;
851
852 wc_switch_to_site_locale();
853 $the_refund = wc_create_refund($data);
854 wc_restore_locale();
855 if (is_wp_error($the_refund)) {
856 $msg = $the_refund->get_error_message();
857 $order->add_order_note(sprintf(__("Error when refunding payment through %1\$s:", 'woo-vipps'), $this->get_payment_method_name()) . ' ' . $msg);
858 $order->save();
859 $this->adminerr($msg);
860 }
861 return true;
862 }
863
864
865 // IOK 2026-04-16 Build wc_create_refund() line_items for all remaining refundable order items - used to provide line-item info for the refund to be processed when
866 // "fully refunded" is done.
867 // [ $item_id => ['qty' => 1, 'refund_total' => '100.00', 'refund_tax' => [ 1 => '25.00' ], * ], ... ]
868 // Includes line items, fees and shipping. For fees/shipping, qty is set to 0.
869 private function get_remaining_refundable_line_items( WC_Order $order ) {
870 $items = $order->get_items( array( 'line_item', 'fee', 'shipping' ));
871
872 $new_refund_line_items = [];
873 foreach($items as $item_id => $item) {
874 $new_refund_line = [];
875
876 // Calculate remaining tax for this line item; by tax id. The shape is [ [total] => [tax_id => value_for_this_tax_id] ].
877 // We want the tax id and the value.
878 $tax_data = wc_tax_enabled() ? $item->get_taxes() : false;
879 $remaining_tax = [];
880 if ($tax_data) {
881 foreach($tax_data['total'] as $tax_id => $value) {
882 if ('' === $value) continue; // don't add empty string as tax value, fatal crash. LP 2026-06-08
883 $remaining_tax[$tax_id] = $value;
884 }
885 }
886 // We can then subtract the tax already refunded for each of these items.
887 foreach($remaining_tax as $tax_id => $current) {
888 $refunded = $order->get_tax_refunded_for_item($item_id, $tax_id, $item->get_type());
889 $remaining = wc_format_decimal($current-$refunded);
890 if ($remaining > 0) {
891 $remaining_tax[$tax_id] = wc_format_decimal($current-$refunded);
892 } else {
893 unset($remaining_tax[$tax_id]);
894 }
895 }
896
897 // Then the quantity
898 $qty = (int) $item->get_quantity();
899 $refunded_quantity = abs((int) $order->get_qty_refunded_for_item($item_id, $item->get_type())); // Documented to be positive since 3.0, seems to be actually negative.
900 $remaining_quantity = $qty-$refunded_quantity;
901
902 $total = $item->get_total();
903 $refunded_total = $order->get_total_refunded_for_item($item_id, $item->get_type()); // A positive value
904 $remaining_total = wc_format_decimal($total-$refunded_total);
905
906
907 if ($remaining_quantity>0 || !empty($remaining_tax) || $remaining_total > 0) {
908 $new_refund_line['qty'] = max(0,$remaining_quantity);
909 $new_refund_line['refund_tax'] = $remaining_tax;
910 $new_refund_line['refund_total'] = $remaining_total;
911 $new_refund_line_items[$item_id] = $new_refund_line;
912 }
913
914 }
915
916 return $new_refund_line_items;
917
918 }
919
920
921 // This is for orders that are 'reserved' at Vipps but could actually be captured at once because
922 // they don't require payment. So we try to capture. IOK 2020-09-22
923 // do NOT call this unless the order is 'reserved' at Vipps!
924 protected function maybe_complete_payment($order) {
925 if (! Vipps::is_vipps_order($order)) return false;
926 if ($order->needs_processing()) return false; // No auto-capture for orders needing processing
927 // IOK 2018-10-03 when implementing partial capture, this must be modified.
928 $captured = intval($order->get_meta('_vipps_captured'));
929 $vippsstatus = $order->get_meta('_vipps_status');
930 if ($captured || $vippsstatus == 'SALE') {
931 return true;
932 }
933 $ok = 0;
934 try {
935 $ok = $this->capture_payment($order);
936 $order->add_order_note(sprintf(__('Payment automatically captured at %1$s for order not needing processing','woo_vipps'), $this->get_payment_method_name()));
937 } catch (Exception $e) {
938 $order->add_order_note(sprintf(__('Order does not need processing, but payment could not be captured at %1$s:','woo_vipps'), $this->get_payment_method_name()) . ' ' . $e->getMessage());
939 }
940 if (!$ok) return false;
941 $order->save();
942 return true;
943 }
944
945 // This filter runs on *all* refunds, including manual refunds. Its main job here is to
946 // disallow creating manual refunds on orders that have not been captured yet, since this makes the capture/cancel logic
947 // very confusing
948 public function woocommerce_create_refund ($refund, $args) {
949 $order_id = intval($args['order_id'] ?? 0);
950 $order = $order_id ? wc_get_order( $order_id ) : null;
951 if ( ! $order ) return;
952 if (! Vipps::is_vipps_order($order)) return;
953 // This is for manual refunds only IOK 2026-02-24
954 if (!($args['refund_payment'] ?? false)) {
955 try {
956 $order = $this->update_vipps_payment_details($order);
957 } catch (Exception $e) {
958 //Do nothing with this for now
959 $this->log(__("Error getting payment details before doing refund: ", 'woo-vipps') . $e->getMessage(), 'warning');
960 }
961 // This would be *per order line* in the fulfilment branch. IOK 2026-02-24 FIXME
962 $captured = intval($order->get_meta('_vipps_captured'));
963 if (!$captured) {
964 $msg = sprintf(__("Order %2\$d: It is not possible to create a manual refund for a %1\$s order before it has been captured - doing so makes it impossible to track how much to capture and how much to release. If you create the refund through %1\$s, a note will be made internally so that the amount to be refunded will *not* be captured - please do this instead if possible. Otherwise, capture the order then refund either manually or through %1\$s", 'woo-vipps'), $this->get_payment_method_name(), $order_id);
965 throw new Exception($msg);
966 }
967 }
968 }
969
970 // This is the Woocommerce refund api called by the "Refund" actions. IOK 2018-05-11
971 public function process_refund($orderid,$amount=null,$reason='') {
972 $order = wc_get_order($orderid);
973
974 $currency = $order->get_currency();
975
976 try {
977 $order = $this->update_vipps_payment_details($order);
978 } catch (Exception $e) {
979 //Do nothing with this for now
980 $this->log(__("Error getting payment details before doing refund: ", 'woo-vipps') . $e->getMessage(), 'warning');
981 }
982
983 $captured = intval($order->get_meta('_vipps_captured'));
984 $to_refund = intval($order->get_meta('_vipps_refund_remaining'));
985
986 // No funds captured, by epayment can do cancel of partial capture, so let's note that we are not to capture this.
987 if (!$captured) {
988 if ('epayment' != $order->get_meta('_vipps_api')) {
989 return new WP_Error('Vipps', sprintf(__("Cannot refund through %1\$s - the payment has not been captured yet.", 'woo-vipps'), $this->get_payment_method_name()));
990 }
991 if ($amount > $order->get_total()) {
992 return new WP_Error('Vipps', sprintf(__("Cannot refund through %1\$s - the refund amount is too large.", 'woo-vipps'), $this->get_payment_method_name()));
993 }
994 $msg = sprintf(__('The money for order %1$d has not been captured, only reserved. %2$s %3$s of the reserved funds will be released when the order is set to complete.', 'woo-vipps'), $orderid, $amount, $currency);
995 $this->log($msg, 'info');
996 $uncapturable = round($amount * 100) + intval($order->get_meta('_vipps_noncapturable'));
997
998 $order->update_meta_data('_vipps_noncapturable', $uncapturable);
999 $order->add_order_note($msg);
1000 $order->save();
1001 return true;
1002 }
1003
1004 if ($amount*100 > $to_refund) {
1005 return new WP_Error('Vipps', sprintf(__("Cannot refund through %1\$s - the refund amount is too large.", 'woo-vipps'), $this->get_payment_method_name()));
1006 }
1007 $ok = 0;
1008
1009 // Specialcase zero, because Vipps treats this as the entire amount IOK 2021-09-14
1010 if (is_numeric($amount) && $amount == 0) {
1011 $order->add_order_note($amount . ' ' . $currency . ' ' . sprintf(__(" refunded through %1\$s:",'woo-vipps'), Vipps::CompanyName()) . ' ' . $reason);
1012 return true;
1013 }
1014
1015 try {
1016 $ok = $this->refund_payment($order,$amount);
1017 } catch (TemporaryVippsApiException $e) {
1018 $this->log(sprintf(__('Could not refund %1$s payment for order id:', 'woo-vipps'), $this->get_payment_method_name()) . ' ' . $orderid . "\n" .$e->getMessage(),'error');
1019 return new WP_Error('Vipps',sprintf(__('%1$s is temporarily unavailable.','woo-vipps'), Vipps::CompanyName()) . ' ' . $e->getMessage());
1020 } catch (Exception $e) {
1021 $msg = sprintf(__('Could not refund %1$s payment','woo-vipps'), Vipps::CompanyName()) . ' ' . $e->getMessage();
1022 $order->add_order_note($msg);
1023 $this->log($msg,'error');
1024 return new WP_Error('Vipps',$msg);
1025 }
1026
1027 if ($ok) {
1028 $order->add_order_note($amount . ' ' . $currency . ' ' . sprintf(__(" refunded through %1\$s:",'woo-vipps'), Vipps::CompanyName()) . ' ' . $reason);
1029 }
1030 return $ok;
1031 }
1032
1033 // Detect default payment method based on country code NT-2024-10-15
1034 public function detect_default_payment_method_from_country($country_code) {
1035 // Default to MobilePay
1036 $payment_method_name = 'MobilePay';
1037 // Default to Vipps if country is Norway or Sweden
1038 if($country_code == 'NO' || $country_code == 'SE') {
1039 $payment_method_name = 'Vipps';
1040 }
1041 return $payment_method_name;
1042 }
1043
1044 // Returns true iff this is a store where Vipps will allow external payment methods.
1045 // Currently this is only Finland, and only Klarna is supported. We need to call this like so because
1046 // most of woocommerce will not be initialized when we need this info. IOK 2024-05-28
1047 public function allow_external_payments_in_checkout() {
1048 $store_location= wc_get_base_location();
1049 $store_country = $store_location['country'] ?? '';
1050 $finland = (get_woocommerce_currency() == "EUR" && $store_country == "FI");
1051 $norway = (get_woocommerce_currency() == "NOK" && $store_country == "NO");
1052 $sweden = (get_woocommerce_currency() == "SEK" && $store_country == "SE");
1053 return apply_filters('woo_vipps_allow_external_payment_methods', ($finland || $norway || $sweden));
1054 }
1055
1056 public function init_form_fields() {
1057 global $Vipps;
1058
1059 // Used for defaults in the admin interface; however this functions is called a loot more often than that.
1060 $page_templates = $this->get_theme_page_templates();
1061 $page_list = $this->get_pagelist();
1062
1063 $orderprefix = $Vipps->generate_order_prefix();
1064
1065 // Default handling based on other parameters and earlier values.
1066 $expresscreateuserdefault = "no";
1067 $vippscreateuserdefault = "no";
1068
1069 // Express checkout uses verified email addresses,so we'll create users if the Login plugin is installed and WooCommerce is set to allow user registration.
1070 if (class_exists('VippsWooLogin')) {
1071 $woodefault = 'yes' === get_option('woocommerce_enable_signup_and_login_from_checkout');
1072 if ($woodefault) {
1073 $expresscreateuserdefault = "yes";
1074 // $vippscreateuserdefault = "yes"; // However, for Vipps Checkout the email address is freetext so we'll treat the default a bit different.
1075 }
1076 }
1077
1078 // We will only show the Vipps Checkout options if the user has activated the feature (thus creating the pages involved etc). IOK 2021-10-01
1079 $vipps_checkout_activated = get_option('woo_vipps_checkout_activated', false);
1080
1081
1082 // This is used for new options,to set reasonable defaults based on older settings. We can't use WC_Settings->get_option for this unfortunately.
1083 $current = get_option('woocommerce_vipps_settings');
1084 // New defaults based on old defaults
1085 $default_static_shipping_for_checkout = 'no';
1086 $default_ask_address_for_express = 'no';
1087 $default_status_on_fail = 'failed';
1088 $default_express_show_in_checkout = 'yes';
1089 if ($current) {
1090 $default_static_shipping_for_checkout = (isset($current['enablestaticshipping'])) ? $current['enablestaticshipping'] : 'no';
1091 $default_ask_address_for_express = (isset($current['useExplicitCheckoutFlow']) && $current['useExplicitCheckoutFlow'] == "yes") ? "yes" : "no";
1092 // The old default used the same value as for Express Checkout. IOK 2023-07-27
1093 $vippscreateuserdefault = isset($current['expresscreateuser']) ? $current['expresscreateuser'] : $vippscreateuserdefault;
1094
1095 // For existing installs: set failed payments order status to cancelled to keep same default behaviour.
1096 // New installs will be set to failed instead of cancelled. LP 2026-03-26
1097 $default_status_on_fail = 'cancelled';
1098
1099 // New setting 'express_show_in_checkout', previously 'cartexpress' affected both cart and checkout.
1100 // Therefore, set new one equal to 'cartexpress' IF it isn't set yet, so that the functionality stays the same for users. LP 2026-07-02
1101 $default_express_show_in_checkout = 'yes';
1102 if (!isset($current['express_show_in_checkout']) && isset($current['cartexpress'])) {
1103 $default_express_show_in_checkout = $current['cartexpress'];
1104 }
1105 }
1106
1107 // Get the already-set country code. For existing sites, this will guess the country based on the currency; for new sites, use
1108 // the woo base country. IOK 2024-10-17 (previously used the currency here too).
1109 $countries = new WC_Countries(); // Can't use WC()->countries here - too early IOK 2024-10-17
1110 $country_code = $current['country'] ?? $countries->get_base_country();
1111
1112 // Same issue as above: We need the default payment method name before it is set to be able to provide defaults IOK 2023-12-01
1113 $payment_method_name = $current['payment_method_name'] ?? $this->detect_default_payment_method_from_country($country_code);
1114
1115 $checkoutfields = array(
1116 'checkout_options' => array(
1117 'title' => "Checkout", // Vipps::CheckoutName(), // Don't translate this, but save some space IOK 2024-12-06
1118 'type' => 'title',
1119 'class' => 'tab',
1120 'description' => sprintf(__("%1\$s is a new service from %2\$s which replaces the usual WooCommerce checkout page entirely, replacing it with a simplified checkout screen providing payment both with %2\$s and credit card. Additionally, your customers will get the option of providing their address information using their %2\$s app directly.", 'woo-vipps'), Vipps::CheckoutName(), Vipps::CompanyName()),
1121 ),
1122
1123
1124 'vipps_checkout_enabled' => array(
1125 'title' => sprintf(__('Activate Alternative %1$s', 'woo-vipps'), Vipps::CheckoutName()),
1126 'label' => sprintf(__('Enable Alternative %1$s screen, replacing the standard checkout page', 'woo-vipps'), Vipps::CheckoutName()),
1127 'type' => 'checkbox',
1128 'description' => sprintf(__('If activated, this will <strong>replace</strong> the standard Woo checkout screen with %1$s, providing easy checkout using %1$s or credit card, with no need to type in addresses.', 'woo-vipps'), Vipps::CheckoutName()),
1129 'default' => 'no',
1130 ),
1131
1132 'checkoutcreateuser' => array (
1133 'title' => sprintf(__('Create new customers on %1$s', 'woo-vipps'), Vipps::CheckoutName()),
1134 'label' => sprintf(__('Create new customers on %1$s', 'woo-vipps'), Vipps::CheckoutName()),
1135 'type' => 'checkbox',
1136 'description' => sprintf(__('Enable this to create and login customers when using %1$s. Otherwise these will all be guest checkouts. If using, you may want to install Login with Vipps too.', 'woo-vipps'), Vipps::CheckoutName()),
1137 'default' => $vippscreateuserdefault,
1138 ),
1139
1140 'enablestaticshipping_checkout' => array(
1141 'title' => sprintf(__('Enable static shipping for %1$s', 'woo-vipps'), Vipps::CheckoutName()),
1142 'label' => __('Enable static shipping', 'woo-vipps'),
1143 'type' => 'checkbox',
1144 'description' => sprintf(__('If your shipping options do not depend on the customers address, you can enable \'Static shipping\', which will precompute the shipping options when using %1$s so that this will be much faster. If you do this and the customer isn\'t logged in, the base location of the store will be used to compute the shipping options for the order. You should only use this if your shipping is actually \'static\', that is, does not vary based on the customers address. So fixed price/free shipping will work. If the customer is logged in, their address as registered in the store will be used, so if your customers are always logged in, you may be able to use this too.', 'woo-vipps'), Vipps::CheckoutName()),
1145 'default' => $default_static_shipping_for_checkout
1146 ),
1147
1148
1149 'requireUserInfo_checkout' => array(
1150 'title' => __('Ask the user to consent to share user information', 'woo-vipps'),
1151 'label' => __('Ask the user to consent to share user information', 'woo-vipps'),
1152 'type' => 'checkbox',
1153 'description' => sprintf(__('If using %1$s, ask for the users consent to share user information with the store. This will allow better integration between Login With %1$s but will add another step to first-time buyers.', 'woo-vipps'), Vipps::CompanyName()),
1154 'default' => 'no'
1155 ),
1156
1157 'noAddressFields' => array(
1158 'title' => __('Drop the address fields on the Checkout screen', 'woo-vipps'),
1159 'label' => __('Don\'t require the address fields', 'woo-vipps'),
1160 'type' => 'checkbox',
1161 'description' => __('If your products <i>don\'t require shipping</i>, either because they are digital downloads, immaterial products or delivering the products directly on purchase, you can check this box. The user will then not be required to provide an address, which should speed things up a bit. If your products require shipping, this will have no effect. NB: If you have plugins that require shipping information, then this is not going to work very well.','woo-vipps'),
1162 'default' => 'no'
1163 ),
1164
1165 'noContactFields' => array(
1166 'title' => __('Drop the contact fields on the Checkout screen', 'woo-vipps'),
1167 'label' => __('Don\'t require the contact fields', 'woo-vipps'),
1168 'type' => 'checkbox',
1169 'description' => __('If your products <i>don\'t require shipping</i> as above, and you also don\'t care about the customers name or contact information, you can drop this too! The customer fields will then be filled with a placeholder. NB: If you have plugins that require contact information, then this is not going to work very well. Also, for this to work you have to check the \'no addresses\' box as well.','woo-vipps'),
1170 'default' => 'no'
1171 ),
1172
1173
1174 );
1175
1176 $vipps_checkout_shipping_fields = array(
1177
1178 'checkout_shipping' => array(
1179 'title' => sprintf(__('%1$s Shipping Methods', 'woo-vipps'), Vipps::CheckoutName()),
1180 'type' => 'title',
1181 'description' => sprintf(__("When using %1\$s, you have the option to use %1\$s specific shipping methods with extended features for certain carriers. These will add an apropriate logo as well as extended delivery options for certain methods. For some of these, you need to add integration data from the carriers below. You can then add these shipping methods to your shipping zones the normal way, but they will only appear in the %1\$s screen.", 'woo-vipps'), Vipps::CheckoutName())
1182 ),
1183
1184 'vcs_posten' => array(
1185 'title' => __('Posten Norge', 'woo-vipps'),
1186 'class' => 'vcs_posten vcs_main',
1187 'custom_attributes' => array('data-vcs-show'=>'.vcs_depend.vcs_posten'),
1188 'label' => sprintf(__('Support Posten Norge as a shipping method in %1$s', 'woo-vipps'), Vipps::CheckoutName()),
1189 'type' => 'checkbox',
1190 'description' => sprintf(__('Activate this for Posten Norge as a %1$s Shipping method.', 'woo-vipps'), Vipps::CheckoutName()),
1191 'default' => 'yes'
1192 ),
1193
1194 'vcs_posti' => array(
1195 'title' => __('Posti', 'woo-vipps'),
1196 'class' => 'vcs_posti vcs_main',
1197 'custom_attributes' => array('data-vcs-show'=>'.vcs_depend.vcs_posti'),
1198 'label' => sprintf(__('Support Posti as a shipping method in %1$s', 'woo-vipps'), Vipps::CheckoutName()),
1199 'type' => 'checkbox',
1200 'description' => sprintf(__('Activate this for Posti as a %1$s Shipping method.', 'woo-vipps'), Vipps::CheckoutName()),
1201 'default' => 'yes'
1202 ),
1203
1204 'vcs_postnord' => array(
1205 'title' => __('PostNord', 'woo-vipps'),
1206 'class' => 'vcs_postnord vcs_main',
1207 'custom_attributes' => array('data-vcs-show'=>'.vcs_depend.vcs_postnord'),
1208 'label' => sprintf(__('Support PostenNord as a shipping method in %1$s', 'woo-vipps'), Vipps::CheckoutName()),
1209 'type' => 'checkbox',
1210 'description' => sprintf(__('Activate this for PostNord as a %1$s Shipping method.', 'woo-vipps'), Vipps::CheckoutName()),
1211 'default' => 'yes'
1212 ),
1213
1214 'vcs_porterbuddy' => array(
1215 'title' => __('Porterbuddy', 'woo-vipps'),
1216 'class' => 'vcs_porterbuddy vcs_main',
1217 'custom_attributes' => array('data-vcs-show'=>'.vcs_depend.vcs_porterbuddy'),
1218 'label' => sprintf(__('Support Porterbuddy as a shipping method in %1$s', 'woo-vipps'), Vipps::CheckoutName()),
1219 'type' => 'checkbox',
1220 'description' => sprintf(__('Activate this for Porterbuddy as a %1$s Shipping method. Your store address will be used as the pick-up point and your admin email will be used for booking information from Porterbuddy.' ,'woo-vipps'), Vipps::CheckoutName()),
1221 'default' => 'no'
1222 ),
1223
1224 'vcs_porterbuddy_publicToken' => array(
1225 'title' => __('Porterbuddy public token', 'woo-vipps'),
1226 'class' => 'vippspw vcs_porterbuddy vcs_depend',
1227 'type' => 'password',
1228 'description' => __('The public key provided to you by Porterbuddy','woo-vipps'),
1229 'default' => '',
1230 ),
1231 'vcs_porterbuddy_apiKey' => array(
1232 'title' => __('Porterbuddy API key', 'woo-vipps'),
1233 'class' => 'vippspw vcs_porterbuddy vcs_depend',
1234 'type' => 'password',
1235 'description' => __('The API key provided to you by Porterbuddy','woo-vipps'),
1236 'default' => '',
1237 ),
1238 'vcs_porterbuddy_phoneNumber' => array(
1239 'title' => __('Porterbuddy Phone Number', 'woo-vipps'),
1240 'class' => 'vcs_porterbuddy vcs_depend',
1241 'type' => 'text',
1242 'description' => __('Your phone number where Porterbuddy may send you important messages. Format must be MSISDN (including country code). Example: "4791234567"','woo-vipps'),
1243 'default' => '',
1244 ),
1245
1246 // Vipps checkout *shipping options* - extra shipping options that only work with Vipps Checkout
1247 'vcs_helthjem' => array(
1248 'title' => __('Helthjem', 'woo-vipps'),
1249 'label' => sprintf(__('Support Helthjem as a shipping method in %1$s', 'woo-vipps'), Vipps::CheckoutName()),
1250 'type' => 'checkbox',
1251 'class' => 'vcs_helthjem vcs_main',
1252 'custom_attributes' => array('data-vcs-show'=>'.vcs_depend.vcs_helthjem'),
1253 'description' => sprintf(__('Activate this for Helthjem as a %1$s Shipping method.' ,'woo-vipps'), Vipps::CheckoutName()),
1254 'default' => 'no'
1255 ),
1256
1257 'vcs_helthjem_shopId' => array(
1258 'title' => __('Helthjem Shop Id', 'woo-vipps'),
1259 'class' => 'vcs_helthjem vcs_depend',
1260 'type' => 'number',
1261 'custom_attributes' => array('pattern'=>'[0-9]'),
1262 'description' => __('The ShopId provided to you by Helthjem','woo-vipps'),
1263 'default' => '',
1264 ),
1265
1266 'vcs_helthjem_username' => array(
1267 'title' => __('Helthjem Username', 'woo-vipps'),
1268 'class' => 'vcs_helthjem vcs_depend',
1269 'type' => 'text',
1270 'description' => __('The Username provided to you by Helthjem','woo-vipps'),
1271 'default' => '',
1272 ),
1273 'vcs_helthjem_password' => array(
1274 'title' => __('Helthjem Password', 'woo-vipps'),
1275 'class' => 'vippspw vcs_helthjem vcs_depend',
1276 'type' => 'password',
1277 'description' => __('Password provided to you by Helthjem','woo-vipps'),
1278 'default' => '',
1279 ),
1280
1281 );
1282
1283 /* Support for *certain* external payment methods in Vipps Checkout. IOK 2024-05-27 */
1284 $externals = [];
1285 $external_payment_fields = [];
1286 $allow_external_payments = $this->allow_external_payments_in_checkout();
1287 if ($allow_external_payments) {
1288 if (in_array('KCO_Gateway', Vipps::$installed_gateways) || in_array('WC_Gateway_Klarna_Payments', Vipps::$installed_gateways)) {
1289 $externals['checkout_external_payments_klarna'] = array(
1290 'title' => __('Klarna', 'woo-vipps'),
1291 'label' => __('Klarna', 'woo-vipps'),
1292 'type' => 'checkbox',
1293 'class' => 'external_payments klarna',
1294 'description' => sprintf(__("Allow Klarna as an external payment method in %1\$s",'woo-vipps'), Vipps::CheckoutName()),
1295 'default' => 'no',
1296 );
1297 }
1298 if (!empty($externals)) {
1299 $external_payment_fields = [
1300 'checkout_external_payment_title' => array(
1301 'title' => sprintf(__('External Payment Methods', 'woo-vipps'), Vipps::CheckoutName()),
1302 'type' => 'title',
1303 'description' => sprintf(__("Allow certain external payment methods in %1\$s, returning control to WooCommerce for the order", 'woo-vipps'), Vipps::CheckoutName())
1304 ),
1305 ];
1306 foreach($externals as $k => $def) $external_payment_fields[$k] = $def;
1307 }
1308 }
1309
1310 $vipps_checkout_widgets_fields = [
1311 'checkout_widgets' => [
1312 'title' => sprintf(__('%1$s widgets', 'woo-vipps'), Vipps::CheckoutName()),
1313 'type' => 'title',
1314 'description' => sprintf(__('Widgets are elements shown above the %1$s frame with extra functionality.', 'woo-vipps'), Vipps::CheckoutName()),
1315 ],
1316 'checkout_widget_ordernotes' => [
1317 'title' => __('Order notes', 'woo-vipps'),
1318 'label' => __('Enable the order notes widget', 'woo-vipps'),
1319 'type' => 'checkbox',
1320 'description' => __('A widget to add customer notes with their order.', 'woo-vipps'),
1321 'default' => 'yes'
1322 ],
1323 ];
1324 /* This seems to have broken some sites with OOM during plugin activation. 2025-05-27 */
1325 // if (wc_coupons_enabled()) {
1326 $vipps_checkout_widgets_fields['checkout_widget_coupon'] = [
1327 'title' => __('Coupon code', 'woo-vipps'),
1328 'label' => __('Enable the coupon code widget', 'woo-vipps'),
1329 'type' => 'checkbox',
1330 'description' => __('A widget to activate coupon codes.', 'woo-vipps'),
1331 'default' => 'yes'
1332 ];
1333 // }
1334
1335 $mainfields = array(
1336 'main_options' => array(
1337 'title' => __('Main options', 'woo-vipps'),
1338 'type' => 'title',
1339 'class' => 'tab',
1340 ),
1341 'enabled' => array(
1342 'title' => __('Enable/Disable', 'woocommerce'),
1343 'label' => sprintf(__('Enable %1$s', 'woo-vipps'), Vipps::CompanyName()),
1344 'type' => 'checkbox',
1345 'description' => '',
1346 'default' => 'no',
1347 ),
1348 'country' => array(
1349 'title' => __('Country', 'woo-vipps'),
1350 'label' => __('Country', 'woo-vipps'),
1351 'type' => 'select',
1352 'options' => array(
1353 'NO' => __('Norway', 'woo-vipps'),
1354 'SE' => __('Sweden', 'woo-vipps'),
1355 'FI' => __('Finland', 'woo-vipps'),
1356 'DK' => __('Denmark', 'woo-vipps'),
1357 ),
1358 'description' => __('Select the country for this merchant serial number. This will determine the appropriate payment method (Vipps or MobilePay).', 'woo-vipps'),
1359 'default' => $country_code,
1360 ),
1361
1362 'payment_method_name' => array(
1363 'title' => __('Payment method', 'woo-vipps'),
1364 'label' => __('Choose which payment method should be displayed to users at checkout', 'woo-vipps'),
1365 'type' => 'select',
1366 'options' => array(
1367 'Vipps' => __('Vipps','woo-vipps'),
1368 'MobilePay' => __('MobilePay', 'woo-vipps'),
1369 ),
1370 'description' => __('Choose which payment method should be displayed to users at checkout', 'woo-vipps'),
1371 'default' => $payment_method_name,
1372 ),
1373
1374 'orderprefix' => array(
1375 'title' => __('Order-id Prefix', 'woo-vipps'),
1376 'label' => __('Order-id Prefix', 'woo-vipps'),
1377 'type' => 'string',
1378 'description' => __('An alphanumeric textstring to use as a prefix on orders from your shop, to avoid duplicate order-ids','woo-vipps'),
1379 'default' => $orderprefix
1380 ),
1381 'merchantSerialNumber' => array(
1382 'title' => __('Merchant Serial Number', 'woo-vipps'),
1383 'label' => __('Merchant Serial Number', 'woo-vipps'),
1384 'type' => 'number',
1385 'description' => __('Your "Merchant Serial Number" from the Developer tab on https://portal.vippsmobilepay.com','woo-vipps'),
1386 'default' => '',
1387 ),
1388 'clientId' => array(
1389 'title' => __('Client Id', 'woo-vipps'),
1390 'class' => 'vippspw',
1391 'label' => __('Client Id', 'woo-vipps'),
1392 'type' => 'password',
1393 'description' => __('Find your account under the "Developer" tab on https://portal.vippsmobilepay.com/ and choose "Show keys". Copy the value of "client_id"','woo-vipps'),
1394 'default' => '',
1395 ),
1396 'secret' => array(
1397 'title' => __('Client Secret', 'woo-vipps'),
1398 'label' => __('Client Secret', 'woo-vipps'),
1399 'class' => 'vippspw',
1400 'type' => 'password',
1401 'description' => __('Find your account under the "Developer" tab on https://portal.vippsmobilepay.com/ and choose "show keys". Copy the value of "client_secret"','woo-vipps'),
1402 'default' => '',
1403 ),
1404 'Ocp_Apim_Key_eCommerce' => array(
1405 'title' => __('Subscription Key', 'woo-vipps'),
1406 'label' => __('Subscription Key', 'woo-vipps'),
1407 'class' => 'vippspw',
1408 'type' => 'password',
1409 'description' => __('Find your account under the "Developer" tab on https://portal.vippsmobilepay.com/ and choose "show keys". Copy the value of "Vipps-Subscription-Key"','woo-vipps'),
1410 'default' => '',
1411 ),
1412
1413 'result_status' => array(
1414 'title' => sprintf(__('Order status on return from %1$s', 'woo-vipps'), Vipps::CompanyName()),
1415 'label' => __('Choose default order status for reserved (not captured) orders', 'woo-vipps'),
1416 'type' => 'select',
1417 'options' => array(
1418 'processing' => __('Processing', 'woo-vipps'),
1419 'on-hold' => __('On hold','woo-vipps'),
1420 ),
1421 'description' => __('By default, orders that are <b>reserved</b> but not <b>yet captured</b> will now have the order status \'Processing\'. You can capture the sum manually, or by changing the status to \'Complete\'. You should ensure that your workflow is such that the order is not shipped until after this capture.<br><br> The status \'On hold\' can be chosen instead for stores using a workflow where orders are shipped when the status is \'Processing\'. In this case, \'On hold\' will mean "order is reserved but not yet captured". This is a slightly safer solution, and ensures that the order status will reflect the payment status. <br><br>However, in many stores \'On hold\' has the additional meaning "there is a problem with the order"; and an email is often sent to the customer about this problem. The default is \'Processing\' because of this, and because many plugins and integrations expect orders to be \'Processing\' when the customer has completed payment.', 'woo-vipps'),
1422 'default' => 'processing',
1423 ),
1424
1425 'status_on_fail' => array(
1426 'title' => sprintf(__('Order status on failed payment (for restartable orders)', 'woo-vipps'), Vipps::CompanyName()),
1427 'label' => __('Choose default order status for failed payments', 'woo-vipps'),
1428 'type' => 'select',
1429 'options' => array(
1430 /* translators: woocommerce status name */
1431 'failed' => __('Failed', 'woo-vipps'),
1432 /* translators: woocommerce status name */
1433 'cancelled' => __('Cancelled','woo-vipps'),
1434 ),
1435 /* translators: company name. cancelled and failed are woocommerce status names! */
1436 'description' => sprintf(__('By default, orders where payment is started but not completed at %1$s will be set to failed if they can be restarted. This setting changes this behaviour, but does <strong>not</strong> affect orders that cannot be restarted as these will always be set to cancelled.<br><br>Cancelled orders will keep the customer\'s shopping cart intact.<br>Failed orders can be restarted, possibly with another payment method.', 'woo-vipps'), Vipps::CompanyName()),
1437 'default' => $default_status_on_fail,
1438 ),
1439
1440 /*
1441 'title' => array(
1442 'title' => __('Title', 'woocommerce'),
1443 'type' => 'text',
1444 'description' => __('This controls the title which the user sees during checkout.', 'woocommerce'),
1445 'default' => sprintf(__('%1$s','woo-vipps'), $payment_method_name),
1446 ),
1447 */
1448
1449 'description' => array(
1450 'title' => __('Description', 'woocommerce'),
1451 'type' => 'textarea',
1452 'description' => __('This controls the description which the user sees during checkout.', 'woocommerce'),
1453 'default' => __("Pay safely and easily. No fees, no matter the amount.", 'woo-vipps'),
1454 ),
1455
1456 'vippsdefault' => array(
1457 'title' => sprintf(__('Use %1$s as default payment method on checkout page', 'woo-vipps'), $payment_method_name),
1458 'label' => sprintf(__('%1$s is default payment method', 'woo-vipps'), $payment_method_name),
1459 'type' => 'checkbox',
1460 'description' => sprintf(__('Enable this to use %1$s as the default payment method on the checkout page, regardless of order.', 'woo-vipps'), $payment_method_name),
1461 'default' => 'yes',
1462 ),
1463
1464 'checkout_phone_transformation' => array(
1465 'title' => sprintf(__('Phone number transformation for %1$s and Express Checkout', 'woo-vipps'), 'Checkout'),
1466 'label' => sprintf(__('Choose a transformation to apply to phone numbers for %1$s and Express Checkout', 'woo-vipps'), 'Checkout'),
1467 'type' => 'select',
1468 'options' => array(
1469 'none' => __('None', 'woo-vipps'),
1470 'ensure_plus' => __('Prepend \'+\'','woo-vipps'),
1471 'strip_country_code' => __('Strip country code','woo-vipps'),
1472 ),
1473 'description' => __('Phone numbers from Express or Checkout are in the format 47xxxxxx without plus-sign in front. If you prefer, or if it is neccessary for your integrations, you can transform these numbers either by adding the plus sign or by stripping the country-code (45, 46, 47, 358).<br>NB: stripping country codes is at the moment only supported for Norwegian, Danish, Finnish and Swedish numbers.<br>Remember to explicitly test your use case before committing to any transformation on your live store.', 'woo-vipps'),
1474 'default' => 'none',
1475 ),
1476 );
1477
1478 $expressfields = array(
1479 'express_options' => array(
1480 'title' => sprintf(__('Express Checkout', 'woo-vipps')),
1481 'type' => 'title',
1482 'class' => 'tab',
1483 'description' => sprintf(__("%1\$s allows you to buy products by a single click from the cart, checkout, or directly from product or catalog pages. Product will get a 'buy now' button which will start the purchase process immediately.", 'woo-vipps'), Vipps::ExpressCheckoutName())
1484 ),
1485
1486 'cartexpress' => array(
1487 'title' => __('Enable Express Checkout in cart', 'woo-vipps'),
1488 'label' => __('Enable Express Checkout in cart', 'woo-vipps'),
1489 'type' => 'checkbox',
1490 'description' => sprintf(__('Enable this to allow customers to shop using %1$s directly from the cart with no login or address input needed', 'woo-vipps'), Vipps::ExpressCheckoutName()) . '.<br>' .
1491 sprintf(__('Please note that for Express Checkout, shipping must be calculated in a callback from the %1$s app, without any knowledge of the customer. This means that Express Checkout may not be compatible with all Shipping plugins or setup. You should test that your setup works if you intend to provide this feature.', 'woo-vipps'), Vipps::CompanyName()),
1492 'default' => 'yes',
1493 ),
1494
1495 'express_show_in_checkout' => array(
1496 'title' => __('Enable Express Checkout in checkout', 'woo-vipps'),
1497 'label' => __('Enable Express Checkout in checkout', 'woo-vipps'),
1498 'type' => 'checkbox',
1499 'description' => sprintf(__('Enable this to allow customers to shop using %1$s directly from the checkout page with no login or address input needed', 'woo-vipps'), Vipps::ExpressCheckoutName()) . '.<br>' .
1500 sprintf(__('Please note that for Express Checkout, shipping must be calculated in a callback from the %1$s app, without any knowledge of the customer. This means that Express Checkout may not be compatible with all Shipping plugins or setup. You should test that your setup works if you intend to provide this feature.', 'woo-vipps'), Vipps::CompanyName()),
1501 'default' => $default_express_show_in_checkout,
1502 ),
1503
1504 'singleproductexpress' => array(
1505 'title' => __('Enable Express Checkout for single products', 'woo-vipps'),
1506 'label' => __('Enable Express Checkout for single products', 'woo-vipps'),
1507 'type' => 'select',
1508 'options' => array(
1509 'none' => __('No products','woo-vipps'),
1510 'some' => __('Some products', 'woo-vipps'),
1511 'all' => __('All products','woo-vipps')
1512 ),
1513 'description' => sprintf(__('Enable this to allow customers to buy a product using %1$s directly from the product page. If you choose \'some\', you must enable this on the relevant products', 'woo-vipps'), Vipps::ExpressCheckoutName()),
1514 'default' => 'none',
1515 ),
1516 'singleproductexpressarchives' => array(
1517 'title' => __('Add \'Buy now\' button on catalog pages too', 'woo-vipps'),
1518 'label' => __('Add the button for all relevant products on catalog pages', 'woo-vipps'),
1519 'type' => 'checkbox',
1520 'description' => sprintf(__('If %1$s is enabled for a product, add the \'Buy now\' button to catalog pages too', 'woo-vipps'), Vipps::ExpressCheckoutName()),
1521 'default' => 'no',
1522 ),
1523 'expresscheckout_termscheckbox' => array(
1524 'title' => sprintf(__('Add terms and conditions checkbox on %1$s', 'woo-vipps'), Vipps::ExpressCheckoutName()),
1525 'label' => sprintf(__('Always ask for confirmation on %1$s', 'woo-vipps'), Vipps::ExpressCheckoutName()),
1526 'type' => 'checkbox',
1527 'description' => sprintf(__('When using %1$s, ask the user to confirm that they have read and accepted the stores terms and conditons before proceeding', 'woo-vipps'), Vipps::ExpressCheckoutName()),
1528 'default' => 'no',
1529 ),
1530
1531 'expresscheckout_always_address' => array(
1532 'title' => __('Always ask for address, even if products don\'t need shipping', 'woo-vipps'),
1533 'label' => __('Always ask the user for their address, even if you don\'t need it for shipping', 'woo-vipps'),
1534 'type' => 'checkbox',
1535 'description' => __('If the order contains only "virtual" products that do not need shipping, we do not normally ask the user for their address - but check this box to do so anyway.', 'woo-vipps'),
1536 'default' => $default_ask_address_for_express,
1537 ),
1538
1539 'enablestaticshipping' => array(
1540 'title' => __('Enable static shipping for Express Checkout', 'woo-vipps'),
1541 'label' => __('Enable static shipping', 'woo-vipps'),
1542 'type' => 'checkbox',
1543 'description' => __('If your shipping options do not depend on the customers address, you can enable \'Static shipping\', which will precompute the shipping options when using Express Checkout so that this will be much faster. If you do this and the customer isn\'t logged in, the base location of the store will be used to compute the shipping options for the order. You should only use this if your shipping is actually \'static\', that is, does not vary based on the customers address. So fixed price/free shipping will work. If the customer is logged in, their address as registered in the store will be used, so if your customers are always logged in, you may be able to use this too.', 'woo-vipps'),
1544 'default' => 'no',
1545 ),
1546
1547
1548 'expresscreateuser' => array (
1549 'title' => __('Create new customers on Express Checkout', 'woo-vipps'),
1550 'label' => __('Create new customers on Express Checkout', 'woo-vipps'),
1551 'type' => 'checkbox',
1552 'description' => sprintf(__('Enable this to create and login new customers when using express checkout. Otherwise these will all be guest checkouts. If you have "Login with Vipps" installed, this will be the default (unless you have turned off user creation in WooCommerce itself)', 'woo-vipps'), Vipps::CompanyName()),
1553 'default' => $expresscreateuserdefault,
1554 ),
1555 'singleproductbuynowcompatmode' => array(
1556 'title' => __('"Buy now" compatibility mode', 'woo-vipps'),
1557 'label' => __('Activate compatibility mode for all "Buy now" buttons', 'woo-vipps'),
1558 'type' => 'checkbox',
1559 'description' => __('Choosing this will use a different method of handling the "Buy now" button on a single product, which will work for more product types and more plugins - while being <i>slightly</i> less smooth. Use this if your product needs more configuration than simple or standard variable products', 'woo-vipps'),
1560 'default' => 'no',
1561 ),
1562
1563
1564 'deletefailedexpressorders' => array(
1565 'title' => __('Delete failed Express Checkout Orders', 'woo-vipps'),
1566 'label' => __('Delete failed Express Checkout Orders', 'woo-vipps'),
1567 'type' => 'checkbox',
1568 'description' => __('As Express Checkout orders are anonymous, failed orders will end up as "cancelled" orders with no information in them. Enable this to delete these automatically when cancelled - but test to make sure no other plugin needs them for anything.', 'woo-vipps'),
1569 'default' => 'no',
1570 )
1571 );
1572 // New shipping in express checkout is available, but merchant has overridden the old shipping callback. Ask what to do! IOK 2020-02-12
1573 if (has_action('woo_vipps_shipping_methods')) {
1574 $shippingoptions = array(
1575 'newshippingcallback' => array(
1576 'title' => __('Use old-style shipping callback for express checkout', 'woo-vipps'),
1577 'label' => __('Use your current shipping filters', 'woo-vipps'),
1578 'type' => 'select',
1579 'options' => array(
1580 'none' => __('Select one','woo-vipps'),
1581 'old' => __('Keep using old shipping callback with my custom filter', 'woo-vipps'),
1582 'new' => __('Use new shipping callback','woo-vipps')
1583 ),
1584 'description' => sprintf(__('Since version 1.4 this plugin uses a new method of providing shipping methods to %1$s when using Express Checkout. The new method supports metadata in the shipping options, which is neccessary for integration with Bring, Postnord etc. However, the new method is not compatible with the old <code>\'woo_vipps_shipping_methods\'</code> filter, which your site has overridden in a theme or plugin. If you want to, you can continue using this filter and the old method. If you want to disable your filters and use the new method, you can choose this here. ', 'woo-vipps'), Vipps::CompanyName()),
1585 'default' => 'none',
1586 )
1587 );
1588 $expressfields = array_merge(array_slice($expressfields ,0,1), $shippingoptions, array_slice($expressfields,1));
1589 }
1590
1591 $advancedfields = array(
1592 'advanced_options' => array(
1593 'title' => __('Advanced', 'woo-vipps'),
1594 'type' => 'title',
1595 'class' => 'tab',
1596 'description' => __("If you have issues with your theme, you might find a setting here that will help. Normally you do not need to change these.", 'woo-vipps')
1597 ),
1598
1599 'vippsorderattribution' => array(
1600 'title' => __( 'Support WooCommerces Order Attribution API for Checkout and Express Checkout', 'woo-vipps' ),
1601 'label' => __( 'Add support for Order Attribution', 'woo-vipps' ),
1602 'type' => 'checkbox',
1603 'default'=> 'no',
1604 'description' => __('Turn this on to add support for Woos Order Attribution API for Checkout and Express Checkout. Some stores have reported problems when using this API together with Vipps, so be sure to test this if you turn it on.', 'woo-vipps'),
1605 ),
1606
1607 'vippsspecialpagetemplate' => array(
1608 'title' => sprintf(__('Override page template used for the special %1$s pages', 'woo-vipps'), Vipps::CompanyName()),
1609 'label' => sprintf(__('Use specific template for %1$s', 'woo-vipps'), Vipps::CompanyName()),
1610 'type' => 'select',
1611 'options' => $page_templates,
1612 'description' => sprintf(__('Use this template from your theme or child-theme to display all the special %1$s pages. You will probably want a full-width template and it should call \'the_content()\' normally.', 'woo-vipps'), Vipps::CompanyName()),
1613 'default' => ''),
1614
1615 'vippsspecialpageid' => array(
1616 'title' => sprintf(__('Use a real page ID for the special %1$s pages - neccessary for some themes', 'woo-vipps'), Vipps::CompanyName()),
1617 'label' => __('Use a real page ID', 'woo-vipps'),
1618 'type' => 'select',
1619 'options' => $page_list,
1620 'description' => sprintf(__('Some very few themes do not work with the simulated pages used by this plugin, and needs a real page ID for this. Choose a blank page for this; the content will be replaced, but the template and other metadata will be present. You only need to use this if the plugin seems to break on the special %1$s pages.', 'woo-vipps'), Vipps::CompanyName()),
1621 'default'=>''),
1622
1623 'sendreceipts' => array(
1624 'title' => __("Send receipts and order confirmation info to the customers' app on completed purchases.", 'woo-vipps'),
1625 'label' => sprintf(__("Send receipts to the customers %1\$s app", 'woo-vipps'), Vipps::CompanyName()),
1626 'type' => 'checkbox',
1627 'description' => sprintf(__("If this is checked, a receipt will be sent to %1\$s which will be viewable in the users' app, specifying the order items, shipping et cetera", 'woo-vipps'), Vipps::CompanyName()),
1628 'default' => 'yes'
1629 ),
1630
1631 'receiptimage' => array (
1632 'title' => sprintf(__('Use this image for the order confirmation link uploaded to the customers\' %1$s app', 'woo-vipps'), Vipps::CompanyName()),
1633 'label' => sprintf(__('Profile image used in the %1$s App', 'woo-vipps'), Vipps::CompanyName()),
1634 'type' => 'woo_vipps_image',
1635 'description' => sprintf(__('If set, this image will be uploaded to %1$s and used to profile your store in the %1$s app for links to the order confirmation etc', 'woo-vipps'), Vipps::CompanyName()),
1636 'default' => 0,
1637 ),
1638
1639
1640 'use_flock' => array (
1641 'title' => __('Use flock() to lock orders for Express Checkout', 'woo-vipps'),
1642 'label' => __('Use flock() to lock orders for Express Checkout', 'woo-vipps'),
1643 'type' => 'checkbox',
1644 'description' => __('Use the flock() system call to ensure orders are only finalized once. You can use this for normal setups, but probably not on Windows with IIS, and possibly not on distributed filesystems like NFS. If you don\t know what it is, probably do not use it. If you get duplicated shipping lines on some express orders, you may try using this', 'woo-vipps'),
1645 'default' => 'no',
1646 ),
1647
1648 'delete_settings_on_deactivation' => array (
1649 'title' => __('Delete plugin settings on deactivation', 'woo-vipps'),
1650 'label' => __('Delete plugin settings on deactivation', 'woo-vipps'),
1651 'type' => 'checkbox',
1652 'description' => __('If set, all plugin settings will be deleted upon plugin deactivation. Warning: there is no recovery after deletion.', 'woo-vipps'),
1653 'default' => 'no',
1654 ),
1655
1656 'developermode' => array ( // DEVELOPERS! DEVELOPERS! DEVELOPERS! DEVE
1657 'title' => __('Enable developer mode', 'woo-vipps'),
1658 'label' => __('Enable developer mode', 'woo-vipps'),
1659 'type' => 'checkbox',
1660 'description' => __('Enable this to enter developer mode. This gives you access to the test-api and sometimes other tools not yet ready for general consumption', 'woo-vipps'),
1661 'default' => VIPPS_TEST_MODE ? 'yes' : 'no',
1662 )
1663
1664
1665 );
1666
1667 $developerfields = array(
1668 'developertitle' => array(
1669 'title' => __('Developer mode', 'woo-vipps'),
1670 'type' => 'title',
1671 'class' => 'tab',
1672 'description' => __('These are settings for developers that contain extra features that are normally not useful for regular users, or are not yet ready for primetime', 'woo-vipps'),
1673 ),
1674
1675 'testmode' => array(
1676 'title' => __('Test mode', 'woo-vipps'),
1677 'label' => __('Enable test mode', 'woo-vipps'),
1678 'type' => 'checkbox',
1679 'description' => sprintf(__('If you enable this, transactions will be made towards the %1$s Test API instead of the live one. No real transactions will be performed. You will need to fill out your test
1680 accounts keys below, and you will need to install a special test-mode app from Testflight on a device (which cannot run the regular %1$s app). Contact %1$s\'s technical support if you need this. If you turn this mode off, normal operation will resume. If you have the VIPPS_TEST_MODE defined in your wp-config file, this will override this value. ', 'woo-vipps'), Vipps::CompanyName()),
1681 'default' => VIPPS_TEST_MODE ? 'yes' : 'no',
1682 ),
1683 'merchantSerialNumber_test' => array(
1684 'title' => __('Merchant Serial Number', 'woo-vipps'),
1685 'class' => 'vippspw',
1686 'label' => __('Merchant Serial Number', 'woo-vipps'),
1687 'type' => 'number',
1688 'description' => __('Your test account "Merchant Serial Number" from the Developer tab on https://portal.vippsmobilepay.com','woo-vipps'),
1689 'default' => '',
1690 ),
1691 'clientId_test' => array(
1692 'title' => __('Client Id', 'woo-vipps'),
1693 'label' => __('Client Id', 'woo-vipps'),
1694 'type' => 'password',
1695 'class' => 'vippspw',
1696 'description' => __('Find your test account under the "Developer" tab on https://portal.vippsmobilepay.com/ and choose "Show keys". Copy the value of "client_id"','woo-vipps'),
1697 'default' => '',
1698 ),
1699 'secret_test' => array(
1700 'title' => __('Client Secret', 'woo-vipps'),
1701 'label' => __('Client Secret', 'woo-vipps'),
1702 'type' => 'password',
1703 'class' => 'vippspw',
1704 'description' => __('Find your test account under the "Developer" tab on https://portal.vippsmobilepay.com/ and choose "show keys". Copy the value of "client_secret"','woo-vipps'),
1705 'default' => '',
1706 ),
1707 'Ocp_Apim_Key_eCommerce_test' => array(
1708 'title' => __('Subscription Key', 'woo-vipps'),
1709 'label' => __('Subscription Key', 'woo-vipps'),
1710 'type' => 'password',
1711 'class' => 'vippspw',
1712 'description' => __('Find your test account under the "Developer" tab on https://portal.vippsmobilepay.com/ and choose "show keys". Copy the value of "Vipps-Subscription-Key"','woo-vipps'),
1713 'default' => '',
1714 ),
1715 );
1716
1717 // Add all the standard fields
1718 foreach($mainfields as $key=>$field) {
1719 $this->form_fields[$key] = $field;
1720 }
1721 foreach($expressfields as $key=>$field) {
1722 $this->form_fields[$key] = $field;
1723 }
1724 foreach($checkoutfields as $key=>$field) {
1725 $this->form_fields[$key] = $field;
1726 }
1727
1728
1729 foreach($external_payment_fields as $key=>$field) {
1730 $this->form_fields[$key] = $field;
1731 }
1732
1733 foreach($vipps_checkout_widgets_fields as $key=>$field) {
1734 $this->form_fields[$key] = $field;
1735 }
1736
1737 foreach($vipps_checkout_shipping_fields as $key=>$field) {
1738 $this->form_fields[$key] = $field;
1739 }
1740 foreach($advancedfields as $key=>$field) {
1741 $this->form_fields[$key] = $field;
1742 }
1743
1744 // The react UI decides whether or not to show the developer fields, however we always have to send this data to the client
1745 // because otherwise the react UI will not be able to show the correct translations, since they would be missing.
1746 foreach($developerfields as $key=>$field) {
1747 $this->form_fields[$key] = $field;
1748 }
1749 // Developer mode settings: Only shown when active. IOK 2019-08-30
1750 if ($this->get_option('developermode') == 'yes' || VIPPS_TEST_MODE) {
1751 if (VIPPS_TEST_MODE) {
1752 $this->form_fields['developermode']['description'] .= '<br><b>' . __('VIPPS_TEST_MODE is set to true in your configuration - dev mode is forced', 'woo-vipps') . "</b>";
1753 $this->form_fields['testmode']['description'] .= '<br><b>' . __('VIPPS_TEST_MODE is set to true in your configuration - test mode is forced', 'woo-vipps') . "</b>";
1754 }
1755 }
1756
1757
1758 }
1759
1760
1761 // IOK 2018-04-18 utilities for the 'admin notices' interface.
1762 private function adminwarn($what) {
1763 add_action('vipps_admin_notices',function() use ($what) {
1764 echo "<div class='notice notice-warning is-dismissible'><p>$what</p></div>";
1765 });
1766 }
1767 private function adminerr($what) {
1768 add_action('vipps_admin_notices',function() use ($what) {
1769 echo "<div class='notice notice-error is-dismissible'><p>$what</p></div>";
1770 });
1771 }
1772 private function adminnotify($what) {
1773 add_action('vipps_admin_notices',function() use ($what) {
1774 echo "<div class='notice notice-info is-dismissible'><p>$what</p></div>";
1775 });
1776 }
1777
1778 // Only be available if current currency is NOK IOK 2018-09-19
1779 // Only be available if current currency is supported NT 2023-12-04
1780 public function is_available() {
1781 // This is split into two functions to avoid triggering infinite recursion in filters that override this value below. IOK 2021-10-30
1782 $ok = $this->standard_is_available();
1783 $ok = apply_filters('woo_vipps_is_available', $ok, $this);
1784 return $ok;
1785 }
1786
1787 // True if the alternative Vipps Checkout screen is both available and activated. Returns the page id of the checkout
1788 // page for convenience. IOK 2021-10-01
1789 public function vipps_checkout_available () {
1790
1791 if ($this->get_option('vipps_checkout_enabled') != 'yes') return false;
1792 if (!$this->standard_is_available()) return false;
1793
1794 $checkoutid = wc_get_page_id('vipps_checkout');
1795 if (!$checkoutid) return false;
1796
1797 // Page doesn't exist anymore
1798 if (! get_post_status($checkoutid)) {
1799 delete_option('woocommerce_vipps_checkout_page_id');
1800 return false;
1801 }
1802
1803 // Restrictions on cart are similar to express checkout, but not exactly the same. IOK 2024-01-11
1804 if (!$this->cart_supports_checkout()) return false;
1805
1806 // Filter to false if you want to use the standard checkout for whatever reason
1807 return apply_filters('woo_vipps_checkout_available', $checkoutid, $this);
1808 }
1809
1810 // Get supported currencies for payment method NT 2023-12-04
1811 public function get_supported_currencies($payment_method) {
1812 switch ($payment_method) {
1813 case 'Vipps': return array('NOK', 'SEK');
1814 case 'MobilePay': return array('DKK', 'EUR');
1815 default: return array();
1816 }
1817 }
1818
1819 // Check if payment method supports currency. NT 2023-12-04
1820 public function payment_method_supports_currency($payment_method, $currency) {
1821 $ok = in_array($currency, $this->get_supported_currencies($payment_method));
1822 return $ok;
1823 }
1824
1825 // Basic unfiltered version of "can I use vipps" ? IOK 2021-10-01
1826 protected function standard_is_available () {
1827 if (!$this->can_be_activated()) return false;
1828 if (!parent::is_available()) return false;
1829 if (!$this->payment_method_supports_currency($this->get_payment_method_name(), get_woocommerce_currency())) return false;
1830 return true;
1831 }
1832
1833 // True if the express checkout feature should be available
1834 public function express_checkout_available() {
1835 if (! $this->is_available()) return false;
1836 $ok = true;
1837 $ok = apply_filters('woo_vipps_express_checkout_available', $ok, $this);
1838 return $ok;
1839 }
1840
1841 // IOK 2018-04-20 Initiate payment at Vipps and redirect to the Vipps payment terminal.
1842 public function process_payment ($order_id) {
1843 global $woocommerce, $Vipps;
1844 if (!$order_id) return [];
1845
1846 do_action('woo_vipps_before_process_payment',$order_id);
1847
1848 // Get current merchant serial
1849 $msn = $this->get_merchant_serial();
1850
1851 // Do a quick check for correct setup first - this is the most critical point IOK 2018-05-11
1852 try {
1853 $at = $this->api->get_access_token($msn);
1854 } catch (Exception $e) {
1855 $this->log(sprintf(__('Could not get access token when initiating %1$s payment for order id:','woo-vipps'), $this->get_payment_method_name()) . $order_id .":\n" . $e->getMessage(), 'error');
1856 wc_add_notice(sprintf(__('Unfortunately, the %1$s payment method is currently unavailable. Please choose another method.','woo-vipps'), $this->get_payment_method_name()),'error');
1857 return [];
1858 }
1859
1860
1861 // From the request, get either [billing_phone] => or [vipps phone]
1862 $phone = '';
1863 if (isset($_POST['vippsphone'])) {
1864 $phone = trim(sanitize_text_field($_POST['vippsphone']));
1865 }
1866 if (!$phone && isset($_POST['billing_phone'])) {
1867 $phone = trim(sanitize_text_field($_POST['billing_phone']));
1868 }
1869
1870 // This is for express checkout if we know the customers' phone.
1871 // thanks to sOndre @ github for reporting , https://github.com/vippsas/vipps-woocommerce/issues/22
1872 if (!$phone && WC()->customer) {
1873 $phone = WC()->customer->get_billing_phone();
1874 }
1875
1876 // No longer the case for V2 of the API
1877 if (false && !$phone) {
1878 wc_add_notice(sprintf(__('You need to enter your phone number to pay with %1$s','woo-vipps'), $this->get_payment_method_name()) ,'error');
1879 return [];
1880 }
1881
1882 $order = wc_get_order($order_id);
1883 $content = null;
1884
1885 // Should be impossible, but there we go IOK 2022-04-21
1886 if (! $order->has_status(['pending', 'failed'])) {
1887 $this->log(sprintf(__("Trying to start order %1\$s with status %2\$s - only 'pending' and 'failed' are allowed, so this will fail", 'woo-vipps'), $order_id, $order->get_status()));
1888 wc_add_notice(sprintf(__('This order cannot be paid with %1$s - please try another payment method or try again later', 'woo-vipps'), $this->get_payment_method_name()), 'error');
1889 return [];
1890 }
1891
1892 // If the Vipps order already has an init-timestamp, we should *not* call init_payment again,
1893 // in the *normal* case, this is a user who have lost their vipps session, so it suffices to
1894 // just return the stored vipps session URL (eg. the user used the Back button.) If abandoned, the
1895 // order will eventually be cancelled. Changes in the cart will result in a new order anyway.
1896 // Note: we now also support restarting the payment with a new retry session if there is no stored vipps session. LP 2026-03-12
1897 if ($order->get_meta('_vipps_init_timestamp')) {
1898 $oldurl = $order->get_meta('_vipps_orderurl');
1899
1900 // Poll status at VMP here to verify session is still open. LP 2026-02-27
1901 $vipps_status = 'unknown';
1902 $vipps_session_open = false;
1903 try {
1904 $vipps_status = $this->get_payment_details($order)['status'] ?? 'unknown';
1905 if ('unknown' !== $vipps_status) {
1906 $vipps_status = $this->interpret_vipps_order_status($vipps_status);
1907 $vipps_session_open = 'initiated' === $vipps_status;
1908 }
1909 } catch (Exception $e) {
1910 /* translators: company name, order id */
1911 $this->log(sprintf(__('Retry-branch: error getting payment details from %1$s for order id %2$s:','woo-vipps'), $this->get_payment_method_name(), $order->get_id()) . "\n" . $e->getMessage(), 'error');
1912 }
1913
1914 // Do we have an active session we can redirect to? LP 2026-02-27
1915 if ($vipps_session_open && $oldurl) {
1916 $order->add_order_note(sprintf(__('%1$s payment restarted','woo-vipps'), $this->get_payment_method_name()));
1917 return array('result'=>'success','redirect'=>$oldurl);
1918 }
1919
1920 // If not, then we need to create a new retry session with incrementing index. LP 2026-03-12
1921 $retry_count = intval($order->get_meta('_vipps_retry_count')) + 1;
1922 $enable_payment_retry = 'unknown' !== $vipps_status; // dont retry unknown statuses. LP 2026-03-18
1923 if (apply_filters('woo_vipps_enable_payment_retry', $enable_payment_retry, $order, $vipps_status, $retry_count)) {
1924 /* translators: number of attempts, order id. */
1925 $this->log(sprintf(__('Order %2$d session could not be restored, creating a new retry session (retry #%1$d).', 'woo-vipps'), $retry_count, $order_id), 'info');
1926 $order->update_meta_data('_vipps_retry_count', $retry_count);
1927 $order->save_meta_data();
1928 } else {
1929 // If restarting is disabled, then we have to cancel the order. LP 2026-03-12
1930 /* translators: order id. */
1931 $this->log(sprintf(__('Order %1$d session could not be restored, and payment retry is disabled. Cancelling the order!', 'woo-vipps'), $order_id), 'info');
1932 $order->update_status('cancelled', sprintf(__('Cannot restart order at %1$s', 'woo-vipps'), Vipps::CompanyName()));
1933 return [];
1934 }
1935 }
1936
1937 // This is needed to ensure that the callbacks from Vipps have access to the customers' session which is important for some plugins. IOK 2019-11-22
1938 $this->save_session_in_order($order);
1939
1940 // Vipps-terminal-page return url to poll/await return
1941 $returnurl= $Vipps->payment_return_url();
1942 // If we are using express checkout, use this to handle the address stuff
1943 // IOK 2018-11-19 also when *not* using express checkout. This allows us to pass the order-id in the return URL and use this as a password in case the sesson has been lost.
1944 $authtoken = $this->generate_authtoken();
1945
1946 // IOK 2019-11-19 We have to do this because even though we actually store the order ID in the session, we can a) be redirected to another browser than the one with
1947 // the session, and b) some plugins wipe the session for guest purchases.
1948 // So we might need to restore (enough of the) session to get to the than you page, even if the session is gone
1949 // or in another castle.
1950 // IOK 2023-01-23 store the limited session in the order instead and separeted it from the authtoken
1951 $limited_session = $this->generate_authtoken();
1952 $returnurl = add_query_arg('ls',$limited_session,$returnurl);
1953 $returnurl = add_query_arg('id', $order_id, $returnurl);
1954
1955
1956 try {
1957 // If the order was 'failed', it isnt any more! yet!
1958 if ($order->get_status() == 'failed') {
1959 $order->set_status('pending', __('Setting order status to pending to start payment', 'woo-vipps'));
1960 }
1961 // The requestid is actually for replaying the request, but I get 402 if I retry with the same Orderid.
1962 // Still, if we want to handle transient error conditions, then that needs to be extended here (timeouts, etc)
1963 // Update: replaced requestid with new idempotency key, moved this into epayment_initiate_payment. LP 2026-03-13
1964 $content = $this->api->epayment_initiate_payment($phone,$order,$returnurl,$authtoken);
1965 } catch (TemporaryVippsApiException $e) {
1966 $this->log(sprintf(__('Could not initiate %1$s payment','woo-vipps'), $this->get_payment_method_name()) . ' ' . $e->getMessage(), 'error');
1967 wc_add_notice(sprintf(__('Unfortunately, the %1$s payment method is temporarily unavailable. Please wait or choose another method.','woo-vipps'), $this->get_payment_method_name()),'error');
1968 return [];
1969 } catch (Exception $e) {
1970
1971 // Special case the "duplicate order id" thing to ensure it doesn't happen again, and if it does, at least
1972 // log some more info IOK 2022-11-02
1973 if (preg_match("/Duplicate Order Id/i", $e->getMessage())) {
1974 do_action('woo_vipps_duplicate_order_id', $order);
1975 $this->log(sprintf(__("Duplicate Order ID! Please report this to support@wp-hosting.no together with as much info about the order as possible. Express: %1\$s Status: %2\$s User agent: %3\$s", 'woo-vipps'), $order->get_meta('_vipps_express_checkout'), $order->get_status(), $order->get_customer_user_agent()), 'error');
1976 $order->update_status('cancelled', __('Cannot restart order with same order ID: Must cancel', 'woo-vipps'));
1977 }
1978
1979 $this->log(sprintf(__('Could not initiate %1$s payment','woo-vipps'), $this->get_payment_method_name()) . ' ' . $e->getMessage(), 'error');
1980 wc_add_notice(sprintf(__('Unfortunately, the %1$s payment method is currently unavailable. Please choose another method.','woo-vipps'), $this->get_payment_method_name()),'error');
1981 return [];
1982 }
1983
1984 $url = $content['url'];
1985 $vippstamp = time();
1986
1987 // Ensure we only check the status by ajax of our own orders. IOK 2018-05-03
1988 $sessionorders= WC()->session->get('_vipps_session_orders');
1989 $sessionorders[$order_id] = 1;
1990 WC()->session->set('_vipps_session_orders',$sessionorders);
1991 WC()->session->set('_vipps_pending_order',$order_id); // Send information to the 'please confirm' screen IOK 2018-04-24
1992
1993 $order = wc_get_order($order_id);
1994 if ($authtoken) {
1995 $order->update_meta_data('_vipps_authtoken',wp_hash_password($authtoken));
1996 }
1997 if ($limited_session) {
1998 $order->update_meta_data('_vipps_limited_session',wp_hash_password($limited_session));
1999 }
2000 // Store the "session URL" for restarts of the order in the same session context. IOK 2022-11-02
2001 $order->update_meta_data('_vipps_init_timestamp',$vippstamp);
2002 $order->update_meta_data('_vipps_orderurl', $url);
2003
2004 $order->update_meta_data('_vipps_status','INITIATE'); // INITIATE right now
2005 $order->add_order_note(sprintf(__('%1$s payment initiated','woo-vipps'), $this->get_payment_method_name()));
2006 $order->add_order_note(sprintf(__('Awaiting %1$s payment confirmation','woo-vipps'), $this->get_payment_method_name()));
2007 $order->save();
2008
2009 // Create a signal file that we can check without calling wordpress to see if our result is in IOK 2018-05-04
2010 try {
2011 $Vipps->createCallbackSignal($order);
2012 } catch (Exception $e) {
2013 // Could not create a signal file, but that's ok.
2014 }
2015
2016 do_action('woo_vipps_before_redirect_to_vipps',$order_id);
2017
2018 // This will send us to a receipt page where we will do the actual work. IOK 2018-04-20
2019 return array('result'=>'success','redirect'=>$url);
2020 }
2021
2022
2023 // This tries to capture a Vipps payment, and resets the status to 'on-hold' if it fails. IOK 2018-05-07
2024 public function maybe_capture_payment($orderid) {
2025 $order = wc_get_order($orderid);
2026 if (! Vipps::is_vipps_order($order)) return false;
2027 $ok = 0;
2028
2029 # Shortcut orders that have been directly captured
2030 $vippsstatus = $order->get_meta('_vipps_status');
2031 if ($vippsstatus == 'SALE') {
2032 return true;
2033 }
2034
2035 $remaining = intval($order->get_meta('_vipps_capture_remaining'));
2036
2037 // Somehow the order status in payment_complete has been set to the 'after order status' or 'complete' by a filter. If so, do not capture.
2038 // Capture will be done *before* payment_complete if appropriate IOK 2020-09-22
2039 if (did_action('woocommerce_pre_payment_complete')) {
2040 if (!$order->needs_processing()) return; // This is fine, we've captured.
2041 if ($remaining>0) {
2042 // Not everything has been captured, but we have reached a capturable status. Complain, do not capture. IOK 2020-09-22
2043 $this->log(sprintf(__("Filters are setting the payment_complete order status to '%1\$s' - will not capture", 'woo-vipps'), $order->get_status()),'debug');
2044 $order->add_order_note(sprintf(__('Payment complete set status to "%1$s" - will not capture payments automatically','woo-vipps'), $order->get_status()));
2045 return false;
2046 }
2047 }
2048
2049 // IOK 2019-10-03 it is now possible to do capture via other tools than Woo, so we must now first check to see if
2050 // the order is capturable by getting full payment details.
2051 try {
2052 $order = $this->update_vipps_payment_details($order);
2053 } catch (Exception $e) {
2054 //Do nothing with this for now
2055 $this->log(__("Error getting payment details before doing capture: ", 'woo-vipps') . $e->getMessage(), 'warning');
2056 }
2057
2058 try {
2059 $ok = $this->capture_payment($order);
2060 } catch (Exception $e) {
2061 // This is handled in sub-methods so we shouldn't actually hit this IOK 2018-05-07
2062 }
2063 if ($ok) {
2064 // Signal other hooked actions that this one actually did something. IOK 2025-02-04
2065 $order->update_meta_data('_vipps_capture_complete',true);
2066 $order->save();
2067 } else {
2068 $order->update_meta_data('_vipps_capture_complete',false);
2069 $msg = sprintf(__("Could not capture %1\$s payment for this order!", 'woo-vipps'), $this->get_payment_method_name());
2070 $order->add_order_note($msg);
2071 $order->save();
2072 if (apply_filters('woo_vipps_on_hold_on_failed_capture', true, $order)) {
2073 $msg = sprintf(__("Could not capture %1\$s payment - status set to", 'woo-vipps'), $this->get_payment_method_name()) . ' ' . __('on-hold','woocommerce');
2074 $order->set_status('on-hold',$msg);
2075 $order->save();
2076 global $Vipps;
2077 $this->adminerr($msg);
2078 $Vipps->store_admin_notices();
2079 return false;
2080 }
2081 }
2082 }
2083
2084
2085 // Capture (possibly partially) the order. Only full capture really supported by plugin at this point. IOK 2018-05-07
2086 // Except that we *do* note that money "refunded" through vipps before capture should be "uncapturable". IOK 2024-11-25
2087 public function capture_payment($order) {
2088 $pm = $order->get_payment_method();
2089 if (! Vipps::is_vipps_order($pm)) {
2090 $this->log(sprintf(__('Trying to capture payment on order not made by %1$s:','woo-vipps'), $this->get_payment_method_name()). ' ' . $order->get_id(), 'error');
2091 $this->adminerr(sprintf(__('Cannot capture payment on orders not made by %1$s','woo-vipps'), $this->get_payment_method_name()));
2092 return false;
2093 }
2094
2095 // Partial capture can happen if the order is edited IOK 2017-12-19
2096 $captured = intval($order->get_meta('_vipps_captured'));
2097 $vippsstatus = $order->get_meta('_vipps_status');
2098 $noncapturable = intval($order->get_meta('_vipps_noncapturable')); // This money has been marked as not-to-be-captured. It will be cancelled on complete.
2099
2100 // Ensure 'SALE' direct captured orders work
2101 if (!$captured && $vippsstatus == 'SALE') {
2102 $order = $this->update_vipps_payment_details($order);
2103 $captured = intval($order->get_meta('_vipps_captured'));
2104 }
2105
2106 $total = round(wc_format_decimal($order->get_total(),'')*100);
2107 $amount = $total-$captured-$noncapturable; // IOK subtract any amount not to be captured here
2108
2109 if ($amount<=0) {
2110 $order->add_order_note(__('Payment already captured','woo-vipps'));
2111 return true;
2112 }
2113
2114 // If we already have captured everything, then we are ok! IOK 2017-05-07
2115 if ($captured) {
2116 $remaining = intval($order->get_meta('_vipps_capture_remaining'));
2117 if (!$remaining) {
2118 $order->add_order_note(__('Payment already captured','woo-vipps'));
2119 return true;
2120 }
2121 }
2122
2123 // Each time we succeed, we'll increase the 'capture' transaction id so we don't just capture the same amount again and again. IOK 2018-05-07
2124 // (but on failre, we don't increase it - and also, we don't really support partial capture yet.) IOK 2018-05-07
2125 $requestidnr = intval($order->get_meta('_vipps_capture_transid'));
2126 // IOK 2023-03-13 keep track of failed captures; because some stores automate capturing without paying attention to the result.
2127 // some reservations are for only 7 days (or 30 days or 180 days) so some orders will be uncapturable. This will be reset by the
2128 // 'Show full transaction details' metabox.
2129 $failures = intval($order->get_meta('_vipps_capture_failures'));
2130 $failurelimit = 10;
2131 try {
2132
2133 // Assume we cannot capture if we have gotten errors 10 times from the API
2134 if ($failures >= $failurelimit) {
2135 throw new Exception(sprintf(__("More than %1\$d API exceptions trying to capture order - this order cannot be captured.", 'woo-vipps'), $failures));
2136 }
2137
2138 $requestid = $requestidnr . ":" . $order->get_order_key();
2139 $api = $order->get_meta('_vipps_api');
2140
2141
2142 if ($api == 'banktransfer') {
2143 // This is an error - we should not ever get to the 'capture' branch if we are a banktransfer payment.
2144 // IOK 2024-01-09
2145 $content = [];
2146 } elseif ($api == 'epayment') {
2147 $content = $this->api->epayment_capture_payment($order,$amount,$requestid);
2148 } else {
2149 $content = $this->api->capture_payment($order,$amount,$requestid);
2150 }
2151 } catch (TemporaryVippsApiException $e) {
2152 $this->log(sprintf(__('Could not capture %1$s payment for order id:', 'woo-vipps'), $this->get_payment_method_name()) . ' ' . $order->get_id() . "\n" .$e->getMessage(),'error');
2153 $this->adminerr(sprintf(__('%1$s is temporarily unavailable.','woo-vipps'), $this->get_payment_method_name()) . "\n" . $e->getMessage());
2154 return false;
2155 } catch (Exception $e) {
2156 // Keep track of API failures up to a point. IOK 2024-03-13
2157 if ($failures < $failurelimit) {
2158 $order->update_meta_data('_vipps_capture_failures', $failures + 1);
2159 $order->save();
2160 }
2161
2162 $msg = sprintf(__('Could not capture %1$s payment for order_id:','woo-vipps'), $this->get_payment_method_name()) . ' ' . $order->get_id() . "\n" . $e->getMessage();
2163 $this->log($msg,'error');
2164 $this->adminerr($msg);
2165 return false;
2166 }
2167
2168 $currency = $order->get_currency();
2169
2170 // Previously, we got this from the transactionInfo field of the Vipps data - this is no longer provided. IOK 2025-08-12
2171 // We simply have to keep track: There is no way of knowing what the correct values are here yet, as we only get these values async, after
2172 // the fact.
2173 $captured = $amount + intval($order->get_meta('_vipps_captured'));
2174 $remaining = intval($order->get_meta('_vipps_amount')) - $captured - intval($order->get_meta('_vipps_cancelled'));
2175 $refundable = $captured - intval($order->get_meta('_vipps_refunded'));
2176
2177 $order->update_meta_data('_vipps_captured', $captured);
2178 $order->update_meta_data('_vipps_capture_remaining', $remaining);
2179 $order->update_meta_data('_vipps_refund_remaining', $refundable);
2180 $order->update_meta_data('_vipps_capture_timestamp', time());
2181 $order->add_order_note(sprintf(__('%1$s Payment captured:','woo-vipps'), $this->get_payment_method_name()) . ' ' . sprintf("%0.2f",$captured/100) . ' ' . $currency);
2182
2183
2184 // Since we succeeded, the next time we'll start a new transaction.
2185 $order->update_meta_data('_vipps_capture_transid', $requestidnr+1);
2186 $order->save();
2187
2188 return true;
2189 }
2190
2191
2192 // Cancel (only completely) a reserved but not yet captured order IOK 2018-05-07
2193 public function cancel_payment($order) {
2194 $pm = $order->get_payment_method();
2195 if (! Vipps::is_vipps_order($pm)) {
2196 $this->log(sprintf(__('Trying to cancel payment on order not made by %1$s:','woo-vipps'), $this->get_payment_method_name()). ' ' .$order->get_id(), 'error');
2197 $this->adminerr(sprintf(__('Cannot cancel payment on orders not made by %1$s','woo-vipps'), $this->get_payment_method_name()));
2198 return false;
2199 }
2200 // We'll use the same transaction id for all cancel jobs, as we can only do it completely. IOK 2018-05-07
2201 // For epayment, partial cancellations will be possible. IOK 2022-11-12
2202 $api = $order->get_meta('_vipps_api');
2203 try {
2204 $requestid = "";
2205 if ($api == 'banktransfer') {
2206 // If we are here, and the order is somehow not captured, just do nothing. IOK 2024-01-09
2207 $content = [];
2208 } elseif ($api == 'epayment') {
2209 $requestid = 1;
2210 // This will cancel any remaining, not-captured amount IOK 2026-01-28
2211 $content = $this->api->epayment_cancel_payment($order,$requestid);
2212 } else {
2213 // If we have captured the order, we can't cancel it with the ecom API IOK 2018-05-07
2214 $captured = intval($order->get_meta('_vipps_captured'));
2215 if ($captured>0) {
2216 $msg = sprintf(__('Cannot cancel a captured %1$s transaction - use refund instead', 'woo-vipps'), "ECOM " . $this->get_payment_method_name());
2217 $this->adminerr($msg);
2218 return false;
2219 }
2220 $content = $this->api->cancel_payment($order,$requestid);
2221 }
2222 } catch (TemporaryVippsApiException $e) {
2223 $this->log(sprintf(__('Could not cancel %1$s payment for order_id:', 'woo-vipps'), $this->get_payment_method_name()) . ' ' . $order->get_id() . "\n" .$e->getMessage(),'error');
2224 $this->adminerr(sprintf(__('%1$s is temporarily unavailable.','woo-vipps'), $this->get_payment_method_name()) . ' ' . $e->getMessage());
2225 return false;
2226 } catch (Exception $e) {
2227 $msg = sprintf(__('Could not cancel %1$s payment for order id:','woo-vipps'), $this->get_payment_method_name()) . $order->get_id() . "\n" . $e->getMessage();
2228 $this->log($msg,'error');
2229 $this->adminerr($msg);
2230 return false;
2231 }
2232
2233 // the epay v2 API would return transactionInfo and Summary with the result, the new epayment api returns nothing.
2234 // Removed epay branch 2025-08-12 IOK
2235 $total = intval($order->get_meta('_vipps_amount'));
2236 $captured = intval($order->get_meta('_vipps_captured'));
2237 # $cancelled = $amount + intval($order->get_meta('_vipps_cancelled');
2238 $cancelled = $total;
2239 $remaining = $total - $captured - $cancelled;
2240
2241 // We need to assume it worked. Also, we can't do partial cancels yet, so just cancel everything.
2242 $order->update_meta_data('_vipps_cancel_timestamp',time());
2243 $order->update_meta_data('_vipps_cancelled', $cancelled);
2244 $order->update_meta_data('_vipps_cancel_remaining', $remaining);
2245
2246
2247 // Set status from Vipps, ignore errors, use statusdata if we have it.
2248 try {
2249 $status = $this->get_vipps_order_status($order);
2250 if ($status) $order->update_meta_data('_vipps_status',$status);
2251 $order->add_order_note(sprintf(__('%1$s Payment cancelled:','woo-vipps'), $this->get_payment_method_name()));
2252 $order->save();
2253 } catch (Exception $e) {
2254 }
2255 return true;
2256 }
2257
2258 // Refund (possibly partially) the captured order. IOK 2018-05-07
2259 // The caller must handle the errors.
2260 public function refund_payment($order,$amount=0,$cents=false) {
2261 $pm = $order->get_payment_method();
2262 if (! Vipps::is_vipps_order($pm)) {
2263 $msg = sprintf(__('Trying to refund payment on order not made by %1$s:','woo-vipps'), $this->get_payment_method_name()) . ' ' . $order->get_id();
2264 $this->log($msg,'error');
2265 throw new VippsAPIException($msg);
2266 }
2267
2268
2269 // If we haven't captured anything, we can't refund IOK 2017-05-07
2270 $captured = intval($order->get_meta('_vipps_captured'));
2271 if (!$captured) {
2272 $msg = sprintf(__('Trying to refund payment on %1$s payment not captured:','woo-vipps'), $this->get_payment_method_name()). ' ' .$order->get_id();
2273 $this->log($msg,'error');
2274 throw new VippsAPIException($msg);
2275 }
2276
2277 // Each time we succeed, we'll increase the 'refund' transaction id so we don't just refund the same amount again and again. IOK 2018-05-07
2278 // (but on failre, we don't increase it.) IOK 2018-05-07
2279 $requestidnr = intval($order->get_meta('_vipps_refund_transid'));
2280 $requestid = $requestidnr . ":" . $order->get_order_key();
2281
2282 $api = $order->get_meta('_vipps_api');
2283 if ($api == 'banktransfer') {
2284 $msg = sprintf(__("Cannot refund bank transfer order %1\$d", 'woo-vipps'), $order->get_id());
2285 $this->log($msg, 'error');
2286 throw new Exception($msg);
2287 } elseif ($api == 'epayment') {
2288 $content = $this->api->epayment_refund_payment($order,$requestid,$amount,$cents);
2289 } else {
2290 $content = $this->api->refund_payment($order,$requestid,$amount,$cents);
2291 }
2292
2293 $currency = $order->get_currency();
2294
2295 // Previously, we got updated transaction info in a transactionInfo field. this is no longer provided,
2296 // so we have to do dead reckoning. IOK 2025-08-12
2297 // We simply have to keep track: There is no way of knowing what the correct values are here yet, as we only get these values async, after
2298 // the fact.
2299 $captured = intval($order->get_meta('_vipps_captured'));
2300
2301 if (!$amount) {
2302 $amount = wc_format_decimal($order->get_total(),'');
2303 $cents = false;
2304 }
2305 if ($amount && !$cents) {
2306 $amount = round($amount * 100);
2307 }
2308
2309 $refunded_now = $amount;
2310 $refunded = intval($order->get_meta('_vipps_refunded')) + $amount;
2311 $remaining = $captured - $refunded;
2312
2313 $order->update_meta_data('_vipps_refunded', $refunded);
2314 $order->update_meta_data('_vipps_refund_remaining', $remaining);
2315 $order->update_meta_data('_vipps_refund_timestamp', time());
2316 $order->add_order_note(sprintf(__('%1$s Payment Refunded:','woo-vipps'), $this->get_payment_method_name()) . ' ' . sprintf("%0.2f",$refunded/100) . ' ' . $currency );
2317
2318 // Since we succeeded, the next time we'll start a new transaction.
2319 $order->update_meta_data('_vipps_refund_transid', $requestidnr+1);
2320 $order->save();
2321 return true;
2322 }
2323
2324 // Generate a one-time password for certain callbacks, with some backwards compatibility for PHP 5.6
2325 public function generate_authtoken($length=32) {
2326 $token="";
2327 if (function_exists('random_bytes')) {
2328 $token = bin2hex(random_bytes($length));
2329 } elseif (function_exists('openssl_random_pseudo_bytes')) {
2330 $token = bin2hex(openssl_random_pseudo_bytes($length));
2331 } elseif (function_exists('mcrypt_create_iv')) {
2332 // These aren't "secure" but they are probably ok for this purpose. IOK 2018-05-18
2333 $indirect = 'mcrypt_create_iv'; // grep-based 7.2 compatibility checkers need to be worked around IOK 2018-10-24
2334 $token = bin2hex($indirect($length));
2335 } else {
2336 // Final fallback
2337 $token = bin2hex(md5(microtime() . ":" . mt_rand()));
2338 }
2339
2340 return $token;
2341 }
2342
2343 // Collapse several statuses to a known list IOK 2019-01-23
2344 // Statuses still in use are annotated. IOK 2025-08-12
2345 public function interpret_vipps_order_status($status) {
2346 switch ($status) {
2347 case 'INITIATE': // legacy, used by us to indicate a fresh order
2348 case 'REGISTER':
2349 case 'REGISTERED':
2350 case 'CREATED': // Checkout, Epayment
2351 return 'initiated';
2352 break;
2353 case 'RESERVE':
2354 case 'RESERVED':
2355 case 'AUTHORISED':
2356 case 'AUTHORIZED': // Checkout, Epayment
2357 case 'CAPTURED': // Epayment
2358 case 'REFUNDED': // epayment - this is probably authorized, because it will have had that state *before* it was refuned. IOK 2025-08-12
2359 return 'authorized';
2360 break;
2361 case 'SALE':
2362 return 'complete';
2363 break;
2364 case 'CANCEL':
2365 case 'CANCELLED': // Epayment
2366 case 'VOID':
2367 case 'AUTOREVERSAL':
2368 case 'AUTOCANCEL':
2369 case 'AUTO_CANCEL':
2370 case 'RESERVE_FAILED':
2371 case 'FAILED':
2372 case 'REJECTED':
2373 case 'TERMINATED': // Checkout, Epayment
2374 case 'ABORTED': // Epayment
2375 case 'EXPIRED': // Epayment
2376 return 'cancelled';
2377 break;
2378 }
2379 // Default should never happen, but just to ensure we are in our enumeration
2380 return "initiated";
2381 }
2382
2383 // This does not normally call Vipps, so if you need to refresh status, please use callback_check_order_status first. IOK 2019-01-23
2384 public function check_payment_status($order) {
2385 if (!$order) return 'cancelled';
2386 $status = $this->interpret_vipps_order_status($order->get_meta('_vipps_status'));
2387 // This can happen if the vipps status is set from the back end for instance. IOK 2020-08-14
2388 if ($order->get_status() == 'pending' && $status != 'initiated') {
2389 $this->callback_check_order_status($order);
2390 $order = wc_get_order($order->get_id()); // refresh to get the new status IOK 2021-01-20
2391 $status = $this->interpret_vipps_order_status($order->get_meta('_vipps_status'));
2392 }
2393 return $status;
2394 }
2395
2396 // Called by callback_check_order_status and handle_callback to handle the situation where
2397 // the payment method has been set to something else *after* Vipps has gotten the order.
2398 // This happens very rarely for people who use Vipps as an external payment method in Klarna, so
2399 // we only do it for orders that match this. IOK 2023-02-03
2400 public function reset_erroneous_payment_method($order) {
2401 // This is only called by methods that are Vipps-specific, but still lets be careful not to touch other orders
2402
2403 // New 2026-01-05: we now check all other payment methods that aren't vipps, and reset it back to vipps.
2404 // The issue was using Klarna Payments and pressing 'back' in the browser, then completing the payment in vipps checkout
2405 // the order still had the payment method klarna_payments, since we previously only checked 'kco' = klarna/kustom checkout. LP 2026-01-05
2406 if (! Vipps::is_vipps_order($order) && $order->get_meta("_vipps_orderid")) {
2407 $order->set_payment_method('vipps');
2408 $express = $order->get_meta('_vipps_express_checkout');
2409 $checkout = $order->get_meta('_vipps_checkout');
2410 $order->set_payment_method_title('Vipps');
2411 if ($express) $order->set_payment_method_title('Vipps Express Checkout');
2412 if ($checkout) $order->set_payment_method_title('Vipps Checkout');
2413 // paypal gw resets payment gateway on order save because it has this meta, so delete it before save. LP 2026-06-23
2414 $order->delete_meta_data('_ppcp_paypal_order_id');
2415 $order->save();
2416
2417 $msg = sprintf(__("Payment method reset to %1\$s - it had been set to another payment method while completing the order for %2\$d", 'woo-vipps'), $this->get_payment_method_name(), $order->get_id());
2418 $this->log($msg, 'debug');
2419 $order->add_order_note($msg);
2420 }
2421 }
2422
2423 // Check status of order at Vipps, in case the callback has been delayed or failed.
2424 // Should only be called if in status 'pending'; it will modify the order when status changes.
2425 public function callback_check_order_status($order, $allow_retry = true) {
2426 global $Vipps;
2427 $orderid = $order->get_id();
2428
2429 clean_post_cache($order->get_id());
2430 $order = wc_get_order($orderid); // Ensure a fresh copy is read.
2431
2432 $oldstatus = $order->get_status();
2433 $newstatus = $oldstatus;
2434
2435 // Only do work when the orders woo status is pending
2436 if ($oldstatus != 'pending') return $oldstatus;
2437
2438 $oldvippsstatus = $this->interpret_vipps_order_status($order->get_meta('_vipps_status'));
2439 $vippsstatus = "";
2440
2441 /* Now read the payment details and update the order with the relevant values, finding the new Vipps status IOK 2021-01-20 */
2442 $paymentdetails = array();
2443 try {
2444 $paymentdetails = $this->get_payment_details($order);
2445 $newvippsstatus = $paymentdetails['status'];
2446 $vippsstatus = $this->interpret_vipps_order_status($newvippsstatus);
2447
2448 $ready = false; // True if money is authorized or complete
2449 if (in_array($vippsstatus, ['authorized', 'complete'])) {
2450 $ready = true;
2451 }
2452
2453 // No change == nothing to do. Ensure we don't modify the order at this point. IOK 2025-10-24
2454 if ($vippsstatus == $oldvippsstatus) {
2455 return $oldstatus;
2456 }
2457 // Something changed, so we are now going to sideeffect the order. IOK 2025-10-15
2458 $this->log(sprintf(__("%1\$s poll: Handling order: ", 'woo-vipps'), Vipps::CompanyName()) . " " . $orderid, 'debug');
2459
2460 // If we are in the process of getting a callback from vipps, don't update anything. Currently, Woo/WP has no locking mechanism,
2461 // and it isn't feasible to implement one portably. So this reduces somewhat the likelihood of races when this method is called
2462 // and callbacks happen at the same time.
2463 if (!$Vipps->lockOrder($order)) {
2464 return $oldstatus;
2465 }
2466
2467 // Failsafe for rare bug when using Klarna Checkout with Vipps as an external payment method
2468 // IOK 2024-01-09 ensure this is called only when order is complete/authorized
2469 if ($ready) {
2470 $this->reset_erroneous_payment_method($order);
2471 }
2472
2473 $order->update_meta_data('_vipps_status',$newvippsstatus);
2474
2475 // Extract order metadata from either Checkout or Epayment - set below IOK 2025-08-13
2476 if (!empty($paymentdetails)) {
2477
2478
2479 // checkout has a string, epayment has an array with upper case "type" and apparently, cardBin IOK 2025-08-12
2480 $paymentMethod = $paymentdetails['paymentMethod'] ?? "epayment";
2481 // After normalization, all APIs will have data here.
2482 $details = $paymentdetails['paymentDetails'];
2483 if (isset($details['paymentMethod'])) {
2484 $paymentMethod = $details['paymentMethod'];
2485 }
2486 if (!is_string($paymentMethod)) {
2487 // should be WALLET
2488 $paymentMethod = $paymentMethod['type'] ?? "epayment";
2489 }
2490 $transaction = array();
2491 $transaction['timeStamp'] = date('Y-m-d H:i:s', time());
2492 $transaction['amount'] = $details['amount']['value'];
2493 $transaction['currency'] = $details['amount']['currency'];
2494 $transaction['status'] = $details['state'];
2495 $transaction['paymentmethod'] = $paymentMethod;
2496 $this->order_set_transaction_metadata($order, $transaction);
2497 }
2498
2499 } catch (Exception $e) {
2500 $this->log(sprintf(__("Error getting payment details from %1\$s for order_id:",'woo-vipps'), $this->get_payment_method_name()) . $orderid . "\n" . $e->getMessage(), 'error');
2501 clean_post_cache($order->get_id());
2502 $Vipps->unlockOrder($order);
2503 return $oldstatus;
2504 }
2505 $order->save();
2506
2507 // We have a completed order, but the callback haven't given us the payment details yet - so handle it.
2508 if (($vippsstatus == 'authorized' || $vippsstatus=='complete') && $order->get_meta('_vipps_express_checkout')) {
2509
2510 do_action('woo_vipps_express_checkout_get_order_status', $paymentdetails);
2511 $address_set = $order->get_meta('_vipps_shipping_set');
2512
2513 if ($address_set) {
2514 // Callback has handled the situation, do nothing
2515 } elseif ($paymentdetails['shippingDetails'] ?? "") {
2516 // We need to set shipping details here
2517 $billing = isset($paymentdetails['billingDetails']) ? $paymentdetails['billingDetails'] : false;
2518 $this->set_order_shipping_details($order,$paymentdetails['shippingDetails'], $paymentdetails['userDetails'], $billing, $paymentdetails);
2519 } else {
2520 // IN THIS CASE we actually need to cancel the order as we have no way of determining whose order this is.
2521 // But first check to see if it has customer info!
2522 // Cancel any orders where the Checkout session is dead and there is no address info available
2523 if (!$order->has_shipping_address() && !$order->has_billing_address()) {
2524 $this->log(sprintf(__("No shipping details from %1\$s for express checkout for order id:",'woo-vipps'), $this->get_payment_method_name()) . ' ' . $orderid, 'error');
2525 $sessiontimeout = time() - (60*90);
2526 $then = intval($order->get_meta('_vipps_init_timestamp'));
2527 if ($then < $sessiontimeout) {
2528 $this->log(sprintf(__("Order %2\$d has no address info and any %1\$s session is dead - have to cancel.", 'woo-vipps'), Vipps::CheckoutName(), $order->get_id()));
2529 $order->update_status('cancelled', sprintf(__('Could not get address info for order from %1$s', 'woo-vipps'), Vipps::CompanyName()));
2530 $order->save();
2531 } else {
2532 // NOOP - the vipps checkout session can still be active, so we need to let it be
2533 $this->log(sprintf(__("No address information for order %2\$d, but there still might be an active %1\$s session for it, so do not cancel it.", 'woo-vipps'), Vipps::CheckoutName(), $order->get_id()));
2534 }
2535 }
2536 clean_post_cache($order->get_id());
2537 $Vipps->unlockOrder($order);
2538 return $oldstatus;
2539 }
2540 }
2541
2542 # Since the order is pending, and the vipps status has changed, switch to the correct vipps status in woo too IOK 2025-10-24
2543 switch ($vippsstatus) {
2544 case 'authorized':
2545 $this->payment_complete($order);
2546 break;
2547 case 'complete':
2548 $msg = sprintf(__('Payment captured directly at %1$s', 'woo-vipps'), $this->get_payment_method_name());
2549 $msg = $msg . __(" - order does not need processing", 'woo-vipps');
2550 $order->add_order_note($msg);
2551 $order = $this->update_vipps_payment_details($order, $paymentdetails);
2552 $order->payment_complete();
2553 break;
2554 case 'cancelled':
2555 $order_is_retryable = $allow_retry && Vipps::order_is_vipps_retryable($order->get_id());
2556 $status_on_fail = $this->get_option('status_on_fail');
2557 $cancel_on_fail = apply_filters('woo_vipps_cancel_failed_orders', false, $order, $vippsstatus);
2558 if ($cancel_on_fail || !$order_is_retryable) {
2559 $status_on_fail = 'cancelled';
2560 }
2561 if (!in_array($status_on_fail, ['cancelled', 'failed'])) {
2562 /* translators: order status name. Cancelled is woocommerce status name */
2563 $this->log(__('Unsupported status for payment failure of \'%1$s\', falling back to cancelled.', 'woo-vipps'), 'warning');
2564 $status_on_fail = 'cancelled';
2565 }
2566
2567 /* translators: company name */
2568 $order->update_status($status_on_fail, sprintf(__('Order failed or rejected at %1$s.', 'woo-vipps'), Vipps::CompanyName()));
2569 break;
2570 }
2571
2572 $order->save();
2573 clean_post_cache($order->get_id());
2574 $newstatus = $order->get_status();
2575 $Vipps->unlockOrder($order);
2576 return $newstatus;
2577 }
2578
2579 // IOK 2020-01-20 Previously was just a debugging tool, then was used to update postmeta values. Now is used as the main source of info
2580 // about the order from Vipps; the previous side-effecting is now done by update_vipps_payment_details.
2581 // IOK 2021-11-24 Because of this, we need to handle 402 and 404 errors differently here now - these *are* results, meaning there is
2582 // no payment details because the order doesn't exist.
2583 // IOK 2022-01-19 And now, with the epayment API in use by checkout, we also need to use the poll api because the epayment API does not return user- and shipping data. We do get an order status though.
2584 // IOK 2025-08-12 And now, with epayment used for Express Checkout also, there *is* user- and shipping-data when using Express Checkout, so we can simplify. We still need to transform the data
2585 // so old hooks and filters can get the input they expect.
2586 public function get_payment_details($order) {
2587 $result = array();
2588 $checkout_session = $order->get_meta('_vipps_checkout_session');
2589 $express = $order->get_meta('_vipps_express_checkout');
2590
2591 // IOK 2025-08-12: Three cases; either this is Checkout, in which case we need to get user/shipping-data from the checkout session,
2592 // or it is Express Checkout or normal payment, in which cases we just retrieve the payment from the epayment API - possibly containing user data
2593 if ($checkout_session) {
2594 try {
2595 $result = $this->api->checkout_get_session_info($order);
2596
2597 if ($result == 'EXPIRED') {
2598 $result = array('status'=>'CANCEL', 'state'=>'CANCEL');
2599 return $result;
2600 }
2601
2602 // For checkout, we are really handling *session states* which we map to *order states*, but sometimes
2603 // these indicate a failed order.
2604 // 'state' can be missing for Checkout, first case is if this is because the session is invalid.
2605 // The sesssion states are # "SessionCreated" "PaymentInitiated" "SessionExpired" "PaymentSuccessful" "PaymentTerminated"
2606 if (isset($result['sessionState']) && ($result['sessionState'] == 'SessionTerminated' || $result['sessionState'] == 'SessionExpired')) {
2607 $result['state'] = 'CANCEL';
2608 $result['status'] = 'CANCEL';
2609 $order->add_order_note(sprintf(__('%1$s Order with no order status, so session was never completed; setting status to cancelled', 'woo-vipps'), Vipps::CheckoutName()));
2610 return $result;
2611 }
2612
2613 // IOK 2023-12-14 at some point, apparently SessionStarted became SessionCreated
2614 if (isset($result['sessionState']) && ($result['sessionState'] == 'SessionStarted' || $result['sessionState'] == 'SessionCreated')) {
2615 // We have no order info, only the session data (this is a checkout order). Therefore, assume it has been started at least.
2616 $result['status'] = "INITIATE";
2617 $result['state'] = "INITIATE";
2618 $created = $order->get_date_created();
2619 $timestamp = 0;
2620 $now = time();
2621 try {
2622 $timestamp = $created->getTimestamp();
2623 } catch (Exception $e) {
2624 // PHP 8 gives ValueError for certain older versions of WooCommerce here.
2625 $timestamp = intval($created->format('U'));
2626 }
2627 $passed = $now - $timestamp;
2628 $minutes = ($passed / 60);
2629
2630 // Give up after 120 minutes. Actually, 60 minutes is probably enough: We expire live sessions after 50 mins.
2631 if ($minutes > 120) {
2632 $this->log(sprintf(__('Checkout order older than 120 minutes with no order status - cancelled as abandoned: %1$s', 'woo-vipps'), $order->get_id()), 'debug');
2633 $order->add_order_note(sprintf(__('%1$s Order with no order status, so session was never completed; setting status to cancelled', 'woo-vipps'), Vipps::CheckoutName()));
2634 $result['status'] = 'CANCEL';
2635 $result['state'] = 'CANCEL';
2636 }
2637 return $result;
2638 }
2639
2640
2641 } catch (VippsAPIException $e) {
2642 $resp = intval($e->responsecode);
2643 if ($resp == 402 || $resp == 404) {
2644 $result = array('status'=>'CANCEL', 'state'=>'CANCEL');
2645 return $result;
2646 } else {
2647 throw $e;
2648 }
2649 }
2650 } else {
2651 try {
2652 $result = $this->api->epayment_get_payment($order);
2653 } catch (VippsAPIException $e) {
2654 $resp = intval($e->responsecode);
2655 if ($resp == 402 || $resp == 404) {
2656 $result = array('status'=>'CANCEL', 'state'=>'CANCEL');
2657 return $result;
2658 } else {
2659 $this->log(sprintf(__("Could not get order status from %1\$s using epayment api: ", 'woo-vipps'), Vipps::CompanyName()) . $e->getMessage(), "error");
2660 throw $e;
2661 }
2662 }
2663 }
2664
2665 if (!$result || $result == "ERROR") {
2666 $this->log(sprintf(__("Could not get payment results for order %1\$s", 'woo-vipps'), $order->get_id()));
2667 wp_die(sprintf(__("Could not get payment results for order %1\$s - you may have the wrong MSN for the order. Please check logs for more information", 'woo-vipps'), $order->get_id()));
2668 }
2669
2670 // We now have a result which maybe will contain user and shipping data, which we will need to normalize because it is slightly different in the different
2671 // APIs, and we have provided filters/hooks that receive this information. IOK 2025-08-12
2672 // If we now have epayment data, we want to translate this to the ecom 'view' for now. Later, we will do the opposite.
2673 // We now only need to map Checkout and epayment to the same format, but we will try to keep the normalized result compatible with
2674 // ecom, in case consumers have created filters/hooks. IOK 2025-08-12
2675
2676 // if Checkout, the result will have a sessionState, reference etc, userInfo, shippingDetails, billingDetails and the payment details in a paymentDetails member.
2677 // if not, the result will *be* a paymentDetails field, but with user*Details* and shippingDetails added. No billingDetails.
2678 // The end result should have state/status (not neccessarily present with Checkout), userDetails, paymentDetails, shippingDetails and billingDetails, and a transactionSummary.
2679 // Because that's what the code depending on this has been expecting. IOK 2025-08-12
2680 if (!$checkout_session) {
2681 // This should be an ecom result, so move all data (for simplicitys sake) into paymentDetails
2682 $result['paymentDetails'] = $result;
2683 }
2684 // Ensure we get payment details with state + aggregate, which we do not if the payment method is bank transfer for checkout. IOK 2024-01-09
2685 // Also add keys and transform for backwards compatibility.
2686 $result = $this->normalizePaymentDetails($result);
2687 $newstatus = $this->interpret_vipps_order_status($result['status']);
2688 $ready = false;
2689 if (in_array($newstatus, ['authorized', 'complete'])) {
2690 $ready = true;
2691 }
2692
2693
2694 // if this is *express - not checkout * and there is no user information, this is probably because we only get that when adding the 'address' scope.
2695 // if we didn't want the address, we now need to ask for user details using the login get_userinfo api. IOK 2025-08-12
2696 // This is also the only way to get "email_verified", so we may want to add a setting that always calls this if neccessary. IOK 2025-08-13
2697 // Also we don't get this when the state is different from AUTHORIZED. Especially not ABORTED.
2698 // IOK 2025-09-29: This is *no longer the case* . We actually now get userDetails every time we add the relevant scopes,
2699 // so this is now probably dead code.
2700 if ($ready && $express && !$checkout_session && !isset($result['userDetails'])) {
2701
2702 $sub = isset($result['profile']) && isset($result['profile']['sub']) ? $result['profile']['sub'] : null;
2703 $userinfo = [];
2704 if (!$sub) {
2705 // This should never happen, but be prepared
2706 $message = sprintf(__("Could not get user info for order %1\$d using the userinfo API: %2\$s. Please use the 'get complete transaction details' on the button to try to recover this. ", 'woo-vipps'), $order->get_id(), "No 'sub' passed for user ID" );
2707 $order->add_order_note($message);
2708 $this->log($message , "error");
2709 } else {
2710 // If this happens, the merchant *may* be able to retrieve the information from Vipps so add a note for it.
2711 try {
2712 $userinfo = $this->api->get_userinfo($sub);
2713 } catch (Exception $e) {
2714 $message = sprintf(__("Could not get user info for order %1\$d using the userinfo API: %2\$s. Please use the 'get complete transaction details' on the button to try to recover this. ", 'woo-vipps'), $order->get_id(), $e->getMessage());
2715 $order->add_order_note($message);
2716 $this->log($message, 'woo-vipps', "error");
2717 }
2718 }
2719 if ($userinfo) {
2720 $userDetails = array(
2721 'email_verified' => $userinfo['email_verified'],
2722 'email' => $userinfo['email'],
2723 'firstName' => $userinfo['given_name'] ?? '',
2724 'lastName' => $userinfo['family_name'] ?? '',
2725 'mobileNumber' => $userinfo['phone_number'] ?? '',
2726 'phoneNumber' => $userinfo['phone_number'] ?? '',
2727 'userId' => $userinfo['phone_number'] ?? '',
2728 'sub' => $userinfo['sub']
2729 );
2730
2731 $result['userDetails'] = $userDetails;
2732
2733 // We may have asked for the address of the customer, so add that too, or a dummy.
2734 if (!isset($result['shippingDetails'])) {
2735 $countries=new WC_Countries();
2736 $address =[];
2737 $address['addressLine1'] = "";
2738 $address['addressLine2'] = "";
2739 $address['city'] ="";
2740 $address['postCode'] = "";
2741 $address['country'] = $countries->get_base_country();
2742
2743 // This uses other keys than both epayment and checkout, but we'll normalize it later. IOK 2025-08-13
2744 if (isset($userinfo['address'])) {
2745 $address['addressLine1'] = $userinfo['address']['street_address'];
2746 $address['city'] = $userinfo['address']['region'];
2747 $address['country'] = $userinfo['address']['country'];
2748 $address['postCode'] = $userinfo['address']['postal_code'];
2749 }
2750 $result['shippingDetails'] = ['address' => $address];
2751 }
2752 }
2753 }
2754
2755 if ($ready && ($express || $checkout_session)) {
2756 // For Vipps Checkout version 3 there are no more userDetails, so we will add it, including defaults for anonymous purchases IOK 2023-01-10
2757 // This will also normalize userDetails, adding 'sub' where required and fields for backwards compatibility. 2025-08-12
2758 $result = $this->ensure_userDetails($result, $order);
2759
2760 // After, we need to normalize shipping details or even add them if e.g. using Checkout without address or contact info IOK 2025-08-13
2761 // Epayment Express Checkout is of course also significantly different from both the old Express and from Checkout in the formatting here. IOK 2025-08-12
2762 $result = $this->normalizeShippingDetails($result, $order);
2763 }
2764
2765 return $result;
2766 }
2767
2768 // IOK 2025-08-12 Normalize the shippingDetails field for backwards compatibility, since this is different from old express, new express and checkout.
2769 function normalizeShippingDetails($result, $order) {
2770
2771 // We may actually get no shipping details eg. for Checkout when not asking for addresses etc.
2772 if (!isset($result['shippingDetails'])) {
2773 $result['shippingDetails'] = ['address' => [] ];
2774 }
2775 $details = $result['shippingDetails'];
2776
2777 $user = $result['userDetails']; // Normalized earlier
2778 $address = $details['address'] ?? [];
2779
2780 // No address, but we have a list of addresses in the userDetails field. This is ecom with the address scope added.
2781 // We will use the first one.
2782 if (empty($address) && isset($result['userDetails']) && isset($result['userDetails']['addresses']) && !empty($result['userDetails']['addresses'])) {
2783 $address = $result['userDetails']['addresses'][0];
2784 }
2785
2786 // Checkout has address info inside shippingDetails, whereas Express Checkout now has it in an address field IOK 2025-08-12
2787 if (empty($address)) {
2788 $address['firstName'] = $details['firstName'] ?? "";
2789 $address['lastName'] = $details['lastName'] ?? "";
2790 $address['email'] = $details['email'] ?? "";
2791 $address['mobileNumber'] = $details['phoneNumber'] ?? "";
2792 $address['addressLine1'] = $details['streetAddress'] ?? "";
2793 $address['addressLine2'] = "";
2794 $address['city'] = $details['city'] ?? "";
2795 $address['postCode'] = $details['postalCode'] ?? "";
2796 $address['country'] = $details['country'] ?? "";
2797 }
2798
2799 // Need at least a country for VAT so add our own.
2800 if (!$address['country']) {
2801 $countries=new WC_Countries();
2802 $address['country'] = $countries->get_base_country();
2803 }
2804
2805 // Normalize from user details when neccessary (mostly for new express)
2806 $address['firstName'] = ($address['firstName'] ?? "") ?: $user['firstName'];
2807 $address['lastName'] = ($address['lastName'] ?? "") ?: $user['lastName'];
2808 $address['email'] = ($address['email'] ?? "") ?: $user['email'];
2809 $address['mobileNumber'] = ($address['mobileNumber'] ?? "") ?: $user['mobileNumber'];
2810
2811 // phoneNumber is checkout, mobileNumber is epayment
2812 $address['phoneNumber'] = $address['mobileNumber'];
2813 // addressline1 and 2 are epayment, streetAddress is checkout
2814 $address['streetAddress'] = $address['addressLine1'];
2815 // postCode is epayment, postalCode is checkout
2816 $address['postalCode'] = $address['postCode'];
2817
2818
2819 // Ensure we have 'address' as in Express/epayment
2820 $details['address'] = $address;
2821
2822 // Name change from Checkout/Express to new Express from MethodId to OptionId IOK 2025-08-12
2823 $details['shippingMethodId'] = $details['shippingMethodId'] ?? ($details['shippingOptionId'] ?? "");
2824 $details['shippingOptionId'] = $details['shippingMethodId'];
2825
2826 $result['shippingDetails'] = $details;
2827 return $result;
2828 }
2829
2830
2831 // IOK 2024-01-09 If using Vipps Checkout with the BankTransfer method, which is eg. used in Finland,
2832 // we are (currently) not receiving any 'state' or 'aggregate', so add this iff the payment is successful.
2833 // The reason for this is that this payment type does not actually use the epayment API at all (!)
2834 // Also moved some other compatibility code here -
2835 // --- reference used to be orderId
2836 // --- state used to be status
2837 // --- there used to be a transactionSummary field
2838 // --- at one point there was a 'transactionAggregate' instead of an 'aggregate'
2839 private function normalizePaymentDetails($result) {
2840 // the 'reference' used to be an 'orderId', keep for compatibility.
2841 $result['orderId'] = $result['reference'];
2842 if (isset($result['sessionState']) && $result['sessionState'] == 'PaymentSuccessful' && $result['paymentMethod'] == 'BankTransfer') {
2843 $details = $result['paymentDetails'];
2844 $details['state'] = 'SALE'; // Payment is actually complete at this point
2845 $aggregate=[];
2846 $aggregate['capturedAmount'] = $details['amount'];
2847 $aggregate['authorizedAmount'] = $details['amount'];
2848 $aggregate['refundedAmount'] = ['value'=>0, 'currency'=>$details['amount']['currency']];
2849 $aggregate['cancelledAmount'] = ['value'=>0, 'currency'=>$details['amount']['currency']];
2850 $details['aggregate'] = $aggregate;
2851 $result['paymentDetails'] = $details;
2852 }
2853
2854 // Sometimes we get the state at top level, sometimes in paymentDetails.
2855 $state = $result['state'] ?? false;
2856
2857 // Now, if we don't have payment details, we should have a dead session or something like it. If we do, we can cretae
2858 // a normalized result. IOK 2023-12-13
2859 if (isset($result['paymentDetails'])) {
2860 $details = $result['paymentDetails'];
2861 $state = $state ?: $details['state'];
2862 $result['state'] = $state;
2863 $details['state'] = $state;
2864
2865 # IOK 2022-01-19 for this, the docs and experience does not agree, so check both
2866 $aggregate = (isset($details['transactionAggregate'])) ? $details['transactionAggregate'] : $details['aggregate'];
2867
2868 // if 'AUTHORISED' and directCapture is set and true, set to SALE which will set the order to complete
2869 // IOK 2025-08-12: This is never true anymore - directCapture is never set and the SALE state does not seem to exist.
2870 // this was an extra feature for merchants with special products however, so keep the logic just in case.
2871 if (($result['state'] == 'AUTHORISED' || $result['state'] == "AUTHORIZED") && isset($result['directCapture']) && $result['directCapture']) {
2872 $result['state'] = "SALE";
2873 }
2874
2875 # the transactionSummary used to contain the information now present in 'aggregate', so map it back for compatibility.
2876 $transactionSummary = array();
2877 // Always NOK at this point, but we also don't care because the order has the currency
2878 // IOK 2024-03-22 Now supports other currencies, but we still don't care.
2879 $transactionSummary['capturedAmount'] = isset($aggregate['capturedAmount']) ? $aggregate['capturedAmount']['value'] : 0;
2880 $transactionSummary['refundedAmount'] = isset($aggregate['refundedAmount']) ? $aggregate['refundedAmount']['value'] : 0;
2881 $transactionSummary['cancelledAmount'] =isset($aggregate['cancelledAmount']) ? $aggregate['cancelledAmount']['value'] : 0;
2882 $transactionSummary['authorizedAmount'] =isset($aggregate['authorizedAmount']) ? $aggregate['authorizedAmount']['value'] : 0;
2883 $transactionSummary['remainingAmountToCapture'] = $transactionSummary['authorizedAmount'] - $transactionSummary['cancelledAmount'] - $transactionSummary['capturedAmount'];
2884 $transactionSummary['remainingAmountToRefund'] = $transactionSummary['capturedAmount'] - $transactionSummary['refundedAmount'];
2885 // now also reducing remainingAmmountToCancel with cancelledAmount PMB 2024-11-21
2886 $transactionSummary['remainingAmountToCancel'] = $transactionSummary['authorizedAmount'] - $transactionSummary['capturedAmount'] - $transactionSummary['cancelledAmount'];
2887
2888 $result['transactionSummary'] = $transactionSummary;
2889 }
2890 // After this, the result will contain a 'state' which used to be a 'status' - map back for compatibility.
2891 // The reason for the method is that in ecom v2 we needed to calculate this from the transaction history. IOK 2025-08-12
2892 $result['status'] = $this->get_payment_status_from_payment_details($result);
2893
2894 // No longer used; was used in later versions of ecom to deduce order status. Added for typewise compatibility.
2895 $result['transactionLogHistory'] = array();
2896 // The corresponding epayment log. Filled on-demand by debugging code.
2897 $result['epaymentLog'] = null;
2898
2899 return $result;
2900 }
2901
2902 // Vipps Checkout v3 does *not* provide userDetails. Vipps Checkout v2 and epayment *does*. But Checkout additionally allows
2903 // for anonymous purchases, in which case there is *no* user details. In this case we provide an anonymous user so we can actually create an order.
2904 // To handle this, we provide this utility that ensures we have userDetails no matter the input. For this we use the anonymous filters and "billingDetails" if present
2905 // if not, we use shippingDetails. IOK 2023-01-10
2906 // Also, epayment uses mobileNumber and checkout uses phoneNumber, so normalize.
2907 public function ensure_userDetails($vippsdata, $order) {
2908 $userDetails = [];
2909
2910 // If we have userDetails, use it (ecom API with user data requested - Express Checkout
2911 if (isset($vippsdata['userDetails'])) {
2912 $userDetails = $vippsdata['userDetails'];
2913 // This is the verified user information from the app - this is always the customer for Express Checkout, but not for Checkout IOK 2025-08-12
2914 $sub = "";
2915 if (isset($vippsdata['profile']) && isset($vippsdata['profile']['sub'])) {
2916 $sub = $vippsdata['profile']['sub'];
2917 }
2918 $userDetails['sub'] = $sub;
2919
2920 } else if (isset($vippsdata['billingDetails'])) {
2921 // Otherwise this is now Checkout, and we want to get it from billingDetails preferrably
2922 $addr = $vippsdata['billingDetails'];
2923 $phone = $addr['phoneNumber'];
2924 $userDetails = array(
2925 'firstName' => $addr['firstName'],
2926 'lastName' => $addr['lastName'],
2927 'email' => $addr['email'],
2928 'phoneNumber' => $phone,
2929 // This is the verified user information from the app - this is always the customer for Express Checkout, but not for Checkout IOK 2025-08-12
2930 'sub' => ""
2931 );
2932
2933 // Or use shippingDetails - this is still Checkout
2934 } else if (isset($vippsdata['shippingDetails'])) {
2935 $addr = $vippsdata['shippingDetails'];
2936 $phone = $addr['phoneNumber'];
2937 $userDetails = array(
2938 'firstName' => $addr['firstName'],
2939 'lastName' => $addr['lastName'],
2940 'email' => $addr['email'],
2941 'phoneNumber' => $phone,
2942 // This is the verified user information from the app - this is always the customer for Express Checkout, but not for Checkout IOK 2025-08-12
2943 'sub' => ""
2944 );
2945
2946 // And it is possible to not require user details in Checkout at all (or if not using express)
2947 } else {
2948 $userDetails = array(
2949
2950 'firstName' => apply_filters('woo_vipps_anon_customer_first_name', __('Anonymous customer', 'woo-vipps'), $order),
2951 'lastName' => apply_filters('woo_vipps_anon_customer_last_name', "", $order),
2952 'email' => apply_filters('woo_vipps_anon_customer_email', '', $order),
2953 'phoneNumber' => apply_filters('woo_vipps_anon_customer_phone_number', '', $order),
2954 'sub' => ""
2955 );
2956 }
2957
2958 //Normalize the result
2959 $phone = $userDetails['phoneNumber'] ?? ($userDetails['mobileNumber'] ?? "");
2960 $userDetails['phoneNumber'] = $phone;
2961 $userDetails['mobileNumber'] = $phone;
2962
2963
2964 // No longer used, but try to provide it for backwards compatibility
2965 $userDetails['userId'] = $userDetails['phoneNumber'];
2966 // This is possible to get iff we have the 'sub', unfortunately it is not passed directly in several of the apis. IOK 2025-08-12
2967 $userDetails['email_verified'] = ($userDetails['email_verified'] ?? false);
2968
2969 $vippsdata['userDetails'] = $userDetails;
2970
2971 return $vippsdata;
2972 }
2973
2974 // Update the order with Vipps payment details, either passed or called using the API.
2975 public function update_vipps_payment_details ($order, $details = null) {
2976 if (!$details) {
2977 try {
2978 $details = $this->get_payment_details($order);
2979 } catch (Exception $e) {
2980 // We'll try but if we fail, that's too bad. IOK 2026-03-18. No recovery is really possible here.
2981 $this->log(sprintf(__("Could not get payment results for order %1\$s", 'woo-vipps'), $order->get_id()));
2982 $this->log($e->getMessage());
2983 }
2984 }
2985
2986 if ($details) {
2987 if (isset($details['transactionSummary'])) {
2988 $transactionSummary= $details['transactionSummary'];
2989 $order->update_meta_data('_vipps_status',$details['status']);
2990 $order->update_meta_data('_vipps_captured',$transactionSummary['capturedAmount']);
2991 $order->update_meta_data('_vipps_refunded',$transactionSummary['refundedAmount']);
2992 $order->update_meta_data('_vipps_capture_remaining',$transactionSummary['remainingAmountToCapture']);
2993 $order->update_meta_data('_vipps_refund_remaining',$transactionSummary['remainingAmountToRefund']);
2994 if (isset($details['transactionSummary']['cancelledAmount'])) {
2995 $order->update_meta_data('_vipps_cancelled',$transactionSummary['cancelledAmount']);
2996 $order->update_meta_data('_vipps_cancel_remaining',$transactionSummary['remainingAmountToCancel']);
2997 }
2998 }
2999 // This is the epayment API - IOK 2022-01-20
3000 if (isset($details['paymentDetails'])) {
3001 $d = $details['paymentDetails'];
3002 if (isset($d['amount'])) {
3003 $order->update_meta_data('_vipps_amount', $d['amount']['value']);
3004 }
3005 $aggregate = (isset($d['transactionAggregate'])) ? $d['transactionAggregate'] : $d['aggregate'];
3006 if ($aggregate) {
3007 // capturedAmount, refundedAmount, authorizedAmount, cancelledAmount
3008 if (isset($aggregate['authorizedAmount'])) {
3009 $order->update_meta_data('_vipps_amount', $aggregate['authorizedAmount']['value']);
3010 }
3011 }
3012 }
3013 // Modify payment method name if neccessary
3014 if (isset($details['paymentMethod']) && $details['paymentMethod'] == 'Card') {
3015 if ($order->get_meta('_vipps_checkout')) {
3016 $order->set_payment_method_title(sprintf(__('Credit Card / %1$s', 'woo-vipps'), Vipps::CheckoutName()));
3017 }
3018 }
3019 if (isset($details['paymentMethod']) && $details['paymentMethod'] == 'BankTransfer') {
3020 if ($order->get_meta('_vipps_checkout')) {
3021 $order->set_payment_method_title(sprintf(__('Bank Transfer/ %1$s', 'woo-vipps'), Vipps::CheckoutName()));
3022 $order->update_meta_data('_vipps_api', 'banktransfer');
3023 }
3024 }
3025 $order->save();
3026 }
3027 return $order;
3028 }
3029
3030 // IOK 2021-01-20 from March 2021 the order_status interface is removed; so we now need to interpret the payment history to find
3031 // out the order status.
3032 // IOK 2022-01-19 With the epayment API on the other hand, the payment status is back as 'state'.
3033 // IOK 2025-08-12 Except for certain payment methods in Checkout. So.
3034 // IOK 2025-08-12 Removing the ecom support now, so all code will use 'state', as normalized by normalizePaymentDetails
3035 public function get_payment_status_from_payment_details($details) {
3036 $status = $details['state'];
3037 return $status;
3038 }
3039
3040 // Get the order status as defined by Vipps; if you have the payment details already, pass them. Will modify the order. IOK 2021-01-20
3041 public function get_vipps_order_status($order, $statusdata=null) {
3042 $vippsorderid = $order->get_meta('_vipps_orderid');
3043 if (!$vippsorderid) {
3044 $msg = sprintf(__('Could not get %1$s order status - it has no %1$s Order Id. Must cancel.','woo-vipps'), $this->get_payment_method_name());
3045 $this->log($msg,'error');
3046 return 'CANCEL';
3047 }
3048 if (!$statusdata) {
3049 try {
3050 $statusdata = $this->get_payment_details($order);
3051 } catch (TemporaryVippsApiException $e) {
3052 $this->log(sprintf(__('Could not get %1$s order status for order id:', 'woo-vipps'), Vipps::CompanyName()) . ' ' . $order->get_id() . "\n" .$e->getMessage(),'error');
3053 return null;
3054 } catch (VippsAPIException $e) {
3055 $msg = sprintf(__('Could not get %1$s order status','woo-vipps'), $this->get_payment_method_name()) . ' ' . $e->getMessage();
3056 $this->log($msg,'error');
3057 if (intval($e->responsecode) == 402 || intval($e->responsecode) == 404) {
3058 $this->log(sprintf(__('Order does not exist at %1$s - cancelling','woo-vipps'), $this->get_payment_method_name()) . ' ' . $order->get_id(), 'warning');
3059 return 'CANCEL';
3060 }
3061 } catch (Exception $e) {
3062 $msg = sprintf(__('Could not get %1$s order status for order id:','woo-vipps'), $this->get_payment_method_name()) . ' ' . $order->get_id() . "\n" . $e->getMessage();
3063 $this->log($msg,'error');
3064 return null;
3065 }
3066 }
3067 if (!$statusdata) return null;
3068
3069 $vippsstatus = isset($statusdata['status']) ? $statusdata['status'] : "";
3070
3071 if (!$vippsstatus) {
3072 $this->log("Unknown Vipps Status: " . print_r($statusdata, true), 'debug');
3073 }
3074 return $vippsstatus;
3075 }
3076
3077 // The various Vipps APIs return address info with various keys and formats, so we need to translate all of them
3078 // to a canonical format.
3079 public function canonicalize_vipps_address($address, $user) {
3080 // eCom has user info only in the user struct
3081 $firstname = $user['firstName'];
3082 $lastname = $user['lastName'];
3083 $email = $user['email'];
3084
3085 // Get the passed phone number from checkout or express, which could be in any number of slots IOK 2025-
3086 $phone = isset($user['mobileNumber']) ? $user['mobileNumber'] : "";
3087 if (isset($user['phoneNumber'])) $phone = $user['phoneNumber'];
3088 if (!$phone && ($address['phoneNumber'] ?? "")) $phone = $address['phoneNumber'];
3089 if (!$phone && ($address['mobileNumber'] ?? "")) $phone = $address['mobileNumber'];
3090
3091 // Phone number transformations - the format Vipps Mobilepay uses is often not what merchants expect or need
3092 // NOTE: as of writing this, the checkout+expresscheckout expected format is '{countrycode}{phonenr}', so we assume this. LP 2025-12-29
3093 $phone_transformation = $this->get_option('checkout_phone_transformation');
3094 switch($phone_transformation) {
3095 case 'ensure_plus':
3096 $phone = "+$phone";
3097 break;
3098 case 'strip_country_code':
3099 // We only support norway,denmark,swedish,finnish country codes as of now. LP 2025-12-29
3100 // We can't do these replaces in sequence, because e.g. +47 46 12 34 56 would become 0 12 34 56 instead of the correct 46 12 34 56. LP 2026-02-19
3101 if (preg_match('!^(45|47)!', $phone)) { // NO, DK
3102 $phone = preg_replace('!^(45|47)!', '', $phone);
3103 } else if (preg_match('!^(46|358)!', $phone)) { // SE, FI: leading zero for area codes is not used with country code, so add it back here. LP 2026-02-09
3104 $phone = preg_replace('!^(46|358)!', '0', $phone);
3105 }
3106 break;
3107 }
3108 $phone = apply_filters('woo_vipps_canonicalize_checkout_phone', $phone, $address, $user);
3109
3110 if (!isset($address['firstName']) or !$address['firstName']) {
3111 $address['firstName'] = $firstname;
3112 }
3113 if (!isset($address['lastName']) or !$address['lastName']) {
3114 $address['lastName'] = $lastname;
3115 }
3116 // checkout uses phonenumber
3117 if (!isset($address['phoneNumber']) or !$address['phoneNumber']) {
3118 $address['phoneNumber'] = $phone;
3119 }
3120 // epayment uses mobileNumber
3121 if (!isset($address['mobileNumber']) or !$address['mobileNumber']) {
3122 $address['mobileNumber'] = $phone;
3123 }
3124 if (!isset($address['email']) or !$address['email']) {
3125 $address['email'] = $email;
3126 }
3127
3128 // epayment
3129 $addressline1 = isset($address['addressLine1']) ? $address['addressLine1'] : "";
3130 $addressline2 = isset($address['addressLine2']) ? $address['addressLine2'] : "";
3131 // checkout
3132 if (isset($address['streetAddress'])) {
3133 $addressline1 = $address['streetAddress'];
3134 }
3135 if (isset($address['street_address'])) { // From the userinfo api
3136 $addressline1 = $address['street_address'];
3137 }
3138 if ($addressline1 == $addressline2) $addressline2 = '';
3139 $address['addressLine1'] = $addressline1; // epayment
3140 $address['addressline2'] = $addressline2;
3141 $address['streetAddress'] = $addressline1; // Checkout
3142
3143 $city = "";
3144 if (isset($address['city'])) { // checkout and epayment
3145 $city = $address['city'];
3146 } elseif (isset($address['region'])) { // ecom
3147 $city = $address['region'];
3148 }
3149 $address['city'] = $city;
3150 $address['region'] = $city;
3151
3152 $postcode= "";
3153 if (isset($address['postCode'])) {
3154 $postcode= $address['postCode']; // epayment
3155 } elseif (isset($address['postalCode'])){
3156 $postcode= $address['postalCode']; // checkout
3157 } elseif (isset($address['postal_code'])) {
3158 $postcode= $address['postal_code']; // userinfo
3159 }
3160 $address['postCode'] = $postcode; // epayment
3161 $address['zipCode'] = $postcode; // ecom
3162 $address['postalCode'] = $postcode; // checkout
3163
3164 // Allow users to modify the address to e.g. handle phone numbers differently IOK 2025-01-20
3165 // note: added separate filter for phone number 'woo_vipps_canonicalize_checkout_phone' because of the different uses, keys etc. LP 2025-12-29
3166 return apply_filters('woo_vipps_canonicalize_checkout_address', $address, $user);
3167 }
3168
3169 public function set_order_shipping_details($order,$shipping, $user, $billing=false, $alldata=null, $assigncustomer=true) {
3170 global $Vipps;
3171 $done = $order->get_meta('_vipps_shipping_set');
3172 if ($done) return true;
3173 $order->update_meta_data('_vipps_shipping_set', true);
3174 $order->save(); // Limit the window for double shipping as much as possible.
3175
3176 // This is for handling a custom consent checkbox for mailing lists etc. IOK 2023-02-09
3177 if ($alldata && isset($alldata['customConsentProvided'])) {
3178 $order->update_meta_data('_vipps_custom_consent_provided', intval($alldata['customConsentProvided']));
3179 }
3180
3181
3182 // We get different values from the normal callback and the Checkout callback, so be prepared for several results. IOK 2021-09-02
3183 // IOK VERIFY this should be normalized now or soon at any rate
3184 $address = isset($shipping['address']) ? $shipping['address'] : $shipping;;
3185
3186 // Sometimes we get an empty shipping address! In this case, fill the details with the billing address.
3187 // This only happens with ecommerce though, so we need to check before canonicalizing. IOK 2022-03-21
3188 // billing is only present in Checkout, which uses phoneNumber, streetAddress, postalCode etc.
3189 $shipping_empty = true;
3190 if ($billing && array_key_exists('streetAddress', $address)) {
3191 $keys = ['firstName', 'lastName', 'email', 'phoneNumber', 'streetAddress', 'postalCode', 'city', 'country'];
3192 foreach ($keys as $key) {
3193 if (isset($address[$key]) && $address[$key]) {
3194 $shipping_empty = false; break;
3195 }
3196 }
3197 if ($shipping_empty) {
3198 foreach ($keys as $key) $address[$key] = $billing[$key];
3199 }
3200 }
3201
3202 if (!$billing) $billing = $address;
3203 $address = $this->canonicalize_vipps_address($address, $user);
3204 $billing = $this->canonicalize_vipps_address($billing, $user);
3205
3206 # Billing.
3207 $order->set_billing_email($billing['email']);
3208 $order->set_billing_phone($billing['mobileNumber']);
3209 $order->set_billing_first_name($billing['firstName']);
3210 $order->set_billing_last_name($billing['lastName']);
3211 $order->set_billing_address_1($billing['addressLine1']);
3212 if ($billing['addressLine2'] ?? false) $order->set_billing_address_2($billing['addressLine2']);
3213 $order->set_billing_city($billing['city'] ?? "");
3214 $order->set_billing_postcode($billing['postCode'] ?? "");
3215 $order->set_billing_country($billing['country'] ?? "");
3216
3217 # Shipping.
3218 $order->set_shipping_first_name($address['firstName']);
3219 $order->set_shipping_last_name($address['lastName']);
3220 if (version_compare(WC_VERSION, '5.6.0', '>=')) {
3221 $order->set_shipping_phone($address['mobileNumber']);
3222 }
3223 $order->set_shipping_address_1($address['addressLine1']);
3224 if ($address['addressLine2'] ?? "") $order->set_shipping_address_2($address['addressLine2']);
3225 $order->set_shipping_city($address['city']);
3226 $order->set_shipping_postcode($address['postCode']);
3227 $order->set_shipping_country($address['country']);
3228
3229 $order->save();
3230
3231 // This is *essential* to get VAT calculated correctly. That calculation uses the customer, which uses the session, which we will have restored at this point.IOK 2019-10-25
3232 if (WC()->customer) {
3233 WC()->customer->set_billing_email($billing['email']);
3234 WC()->customer->set_email($billing['email']);
3235
3236 $country = $billing['country'] ?? ($address['country'] ?? "");
3237 WC()->customer->set_billing_location($country,'',$billing['postalCode'],$billing['region']);
3238 WC()->customer->set_shipping_location($address['country'],'',$address['postalCode'],$address['region']);
3239 }
3240
3241 // We may need the order total early on, so start with that
3242 $ordertotal = $order->get_total() ?: 0;
3243
3244 $vipps_reserved = $alldata['paymentDetails']['amount']['value'] ?? null;
3245 // i dont expect order total to ever be greater than vipps reserved total here, so i dont use abs(). LP 2026-01-28
3246 $diff_reserved_ordertotal = is_numeric($vipps_reserved) ? ($vipps_reserved / 100 - $ordertotal) : 0;
3247
3248 // Now do shipping, if it exists IOK 2021-09-02
3249 $method = isset($shipping['shippingMethodId']) ? $shipping['shippingMethodId'] : false;
3250
3251 // We will add a shipping rate either if there has been passed a shipping method; or if this
3252 // is an order that needs shipping and the amount reserved at vipps is greater than the order total
3253 // (with a bit of tolerance for rounding errors). If we *don't* have a shipping method but we know
3254 // we need a shipping rate; this is an error condition that the merchant needs to resolve. We'll add a fake
3255 // 'Unknown' rate to ensure we capture the right amount and add this fact to the order log. Code by LP, comment by IOK 2026-01-28
3256 $needs_shipping = $method || $order->get_meta('_vipps_needs_shipping');
3257 $tol = 0.01;
3258 $has_shipping = $method || $diff_reserved_ordertotal > $tol;
3259
3260 if ($needs_shipping && $has_shipping) {
3261 $shipping_rate=null;
3262 $option_table = [];
3263
3264 // Try to find the shipping rate. LP 2026-01-28
3265 if ($method) {
3266 if (substr($method,0,1) != '$') {
3267 // This is the old way of adding shipping. We should probably deprecate this sometime soon. IOK 2026-01-28
3268 $shipping_rate = $this->get_legacy_express_checkout_shipping_rate($shipping);
3269 } else {
3270 // Strip suffixes if we have several Express rates mapping to the same Woo rate (eg. for Posten). IOK 2025-05-04
3271 $matches = [];
3272 preg_match("!^(?P<key>[^:]+):?(?P<option_index>.+)?$!", $method, $matches);
3273 $key = $matches['key'] ?? "";
3274 $option_index = intval(trim($matches['option_index'] ?? "")); // 0 is never an index
3275 $shipping_table = $order->get_meta('_vipps_express_checkout_shipping_method_table');
3276 $is_base64 = $shipping_table ? ( $shipping_table['_is_base64'] ?? false) : false;
3277
3278 if (is_array($shipping_table) && isset($shipping_table[$key])) {
3279 $decoded = $is_base64 ? @base64_decode($shipping_table[$key]) : $shipping_table[$key];
3280 $shipping_rate = $decoded ? @unserialize($decoded) : null;
3281 if (!$shipping_rate) {
3282 $this->log(sprintf(__("%1\$s: Could not deserialize the chosen shipping method %2\$s for order %3\$d", 'woo-vipps'), Vipps::ExpressCheckoutName(), $method, $order->get_id()), 'error');
3283 $this->log(sprintf(__("Serialized data was %1\$s", 'woo-vipps'), $decoded), 'error');
3284 } else {
3285 // Special-case the Woo pickup location methods. IOK 2026-01-28
3286 if ($option_index) {
3287 $meta = $shipping_rate->get_meta_data();
3288 $option_table = $meta['_vipps_pickupPoints'] ?? [];
3289 // force string table IOK 2025-08-15
3290 $point = $option_table["i".$option_index] ?? "";
3291 if ($point) {
3292 $shipping['pickupPoint'] = $point;
3293 }
3294 $shipping_rate->add_meta_data('_vipps_pickupPoints', null);
3295 }
3296 // Empty this when done, but not if there was an error - let the merchant be able to debug. IOK 2020-02-14
3297 $order->update_meta_data('_vipps_express_checkout_shipping_method_table', null);
3298 }
3299 }
3300 }
3301
3302 // Possible extra metadata from Vipps Checkout IOK 2023-01-17
3303 // Store in the order, but also in the shipping rate so it will be visible in the order screen
3304 // along with the shipping ragte
3305 if (isset($shipping['pickupPoint'])) {
3306 $order->update_meta_data('vipps_checkout_pickupPoint', $shipping['pickupPoint']);
3307 if ($shipping_rate) {
3308 $pp = $shipping['pickupPoint'];
3309 $addr = [];
3310 foreach(['address', 'postalCode', 'city', 'country'] as $key) {
3311 $v = trim($pp[$key]);
3312 if (!empty($v)) $addr[] = trim($pp[$key]);
3313 }
3314
3315 $shipping_rate->add_meta_data('pickup_location', $pp['name']);
3316 $shipping_rate->add_meta_data('pickup_address', join(", ", $addr));
3317 $shipping_rate->add_meta_data('pickup_details', ""); // Not supported by the API unfortunately. IOK 2025-06-07
3318 }
3319 }
3320 if (isset($shipping['timeslot'])) {
3321 $order->update_meta_data('vipps_checkout_timeslot', $shipping['timeslot']);
3322 if ($shipping_rate) {
3323 $pp = $shipping['timeslot'];
3324 $slot = "";
3325 $slot .= sprintf(__("Date: %s", 'woo-vipps'), ($pp['date'] ?? ""));
3326 $slot .= " " . sprintf(__("Start: %s", 'woo-vipps'), ($pp['start'] ?? ""));
3327 $slot .= " " . sprintf(__("End: %s", 'woo-vipps'), ($pp['end'] ?? ""));
3328 $shipping_rate->add_meta_data('vipps_delivery_timeslot', $slot);
3329 $shipping_rate->add_meta_data('vipps_delivery_timeslot_id', $pp['id']);
3330 }
3331 }
3332 }
3333
3334 // We know we need a shipping rate, and what its price has to be, so ensure we have one by making one up if missing. LP 2026-01-28
3335 if (!$shipping_rate) {
3336 $shipping_rate = new WC_Shipping_Rate(
3337 'UNKNOWN',
3338 sprintf(__('Unknown shipping: please check the shipping details at %1$s', 'woo-vipps'), Vipps::CompanyName()),
3339 $diff_reserved_ordertotal,
3340 [],
3341 'UNKNOWN',
3342 0,
3343 );
3344 $shipping_rate = apply_filters('woo_vipps_unknown_shipping_rate_dummy', $shipping_rate, $order);
3345
3346 // Add an error log for the merchants to quote to us.
3347 $msg = sprintf(__("%1\$s Could not retrieve any shipping rate for this order, with method %2\$s",'woo-vipps'), $this->get_payment_method_name(), $method) . " " . $order->get_id();
3348 $order->add_order_note($msg);
3349 $this->log($msg, 'warning');
3350 }
3351
3352 $shipping_rate = apply_filters('woo_vipps_express_checkout_final_shipping_rate', $shipping_rate, $order, $shipping);
3353
3354 $total_shipping = 0;
3355 $total_shipping_tax = 0;
3356 $it = null;
3357
3358 // Recover the Shipping Method class
3359 $methods_classes = WC()->shipping->get_shipping_method_class_names();
3360 $methodclass = $methods_classes[$shipping_rate->get_method_id()] ?? null;
3361 $shipping_method = $methodclass ? new $methodclass($shipping_rate->get_instance_id()) : null;
3362 $is_vipps_checkout_shipping = $shipping_method && is_a($shipping_method, 'VippsCheckout_Shipping_Method');
3363
3364 // Some Vipps Checkout-specific shipping methods calculate the cost in the Vipps window.
3365 if ($is_vipps_checkout_shipping && $shipping_method->dynamic_cost) {
3366 $vippsamount = intval($order->get_meta('_vipps_amount'));
3367 $shipping_tax_rate = floatval($order->get_meta('_vipps_shipping_tax_rates'));
3368 $compareamount = $ordertotal * 100;
3369 $amountdiff = $vippsamount-$compareamount; // this is the *actual* shipping cost at this point
3370 $diffnotax = ($amountdiff / (100 + $shipping_tax_rate)); // Adjusted to correct values actually
3371 $difftax = WC_Tax::round($amountdiff/100 - $diffnotax);
3372 $actual = $amountdiff/100 - $difftax;
3373
3374 $shipping_rate->set_cost($actual);
3375 $shipping_rate->set_taxes( [ 1 => $difftax] );
3376 }
3377
3378 $it = new WC_Order_Item_Shipping();
3379 $it->set_shipping_rate($shipping_rate);
3380 $it->set_order_id( $order->get_id() );
3381 // This should actually have been done by the "set_shipping_rate" call above, but as of 3.9.2 at least, this does not work.
3382 // Therefore, do it manually/forcefully IOK 2020-02-17
3383 foreach($shipping_rate->get_meta_data() as $key => $value) {
3384 $it->add_meta_data($key,$value,true);
3385 }
3386 $it->save();
3387
3388 $order->add_item($it);
3389
3390 $total_shipping = $it->get_total() ?: 0;
3391 $total_shipping_tax = $it->get_total_tax() ?: 0;
3392
3393 // Try to avoid calculate_totals, because this will recalculate shipping _without checking if the rate
3394 // in question actually should use tax_. Therefore we will just add the pre-calculated values, so that the
3395 // value reserved at Vipps and the order total is the same. IOK 2022-10-03
3396 $order->set_shipping_total($total_shipping);
3397 $order->set_shipping_tax($total_shipping_tax);
3398
3399 $order->set_total($ordertotal + $total_shipping + $total_shipping_tax);
3400 $order->update_taxes(); // Necessary for the admin view only; does not recalculate order.
3401
3402 // Add an early hook for Vipps Checkout orders with special shipping methods
3403 $metadata = $shipping_rate->get_meta_data();
3404 if (isset($metadata['type'])) {
3405 do_action('woo_vipps_checkout_special_shipping_method', $order, $shipping_rate, $metadata['type']);
3406 }
3407
3408 $order->save();
3409 // NB: WE DO NOT CALL CALCULATE TOTALS!
3410 // THIS WILL CALCULATE SHIPPING FOR TAX IF THERE IS A TAX RATE FOR THE GIVEN AREA WITH THE 'shipping' PROPERTY CHECKED - EVEN IF THE SHIPPING RATE IT SELF IS NOT THUS CONFIGURED.
3411 // Same thing happens when using the "recalculate" button in the backend
3412 // This will *only* affect users that choose "No tax" for the shipping rates themselves, which is mostly just wrong, but we want to ensure consistency here since this is hard
3413 // to debug.
3414 // $order->calculate_totals(true);
3415 }
3416
3417
3418 // If we have the 'expresscreateuser' thing set to true, we will create or assign the order here, as it is the first-ish place where we can.
3419 // If possible and safe, user will be logged in before being sent to the thankyou screen. IOK 2020-10-09
3420 // Same thing for Vipps Checkout, mutatis mutandis. The function below returns false if no customer exists or gets created.
3421 $customer = false;
3422 if ($assigncustomer) {
3423 $customer = Vipps::instance()->express_checkout_get_vipps_customer($order);
3424 }
3425 if ($customer) {
3426 // This would have been used to ensure that we 'enroll' the users the same way as in the Login plugin. Unfortunately, the userId from express checkout isn't
3427 // the same as the 'sub' we get in Login so that must be a future feature. IOK 2020-10-09
3428 // IOK 2025-08-13 we do get the 'sub' now, at least for express checkout. For Checkout, we would have to compare the email of the user with the verified email
3429 // after calling get_userinfo, so we'll leave that be.
3430 if (class_exists('VippsWooLogin') && $customer && !is_wp_error($customer) && !get_user_meta($customer->get_id(), '_vipps_phone',true)) {
3431 update_user_meta($customer->get_id(), '_vipps_phone', $billing['phoneNumber']);
3432 if (isset($user['sub'])) {
3433 $userid = $customer->get_id();
3434 update_user_meta($userid, '_vipps_id', $user['sub']);
3435 update_user_meta($userid, '_vipps_just_connected', 1);
3436 }
3437 }
3438
3439 // Ensure we get any changes made to the order, as it will be re-saved later
3440 $order = wc_get_order($order->get_id());
3441 }
3442
3443 do_action('woo_vipps_set_order_shipping_details', $order, $shipping, $user);
3444 $order->save(); // I'm not sure why this is neccessary - but be sure.
3445
3446 }
3447
3448 // Previously, shipping rates were added by creating them here with metadata packed into the shippingMethodId. This is from 1.4.0 only
3449 // used when the woo_vipps_shipping_methods filter has been overriden by the merchant. IOK 2020-02-14
3450 private function get_legacy_express_checkout_shipping_rate($shipping) {
3451 $method = $shipping['shippingMethodId'];
3452 list ($rate,$tax) = explode(";",$method);
3453 // The method ID is encoded in the rate ID but we apparently must still send it to the WC_Shipping_Rate constructor. IOK 2018-06-01
3454 // Unfortunately, Vipps won't accept long enought 'shipingMethodId' for us to actually stash all the information we need. IOK 2018-06-01
3455 list ($method,$product) = explode(":",$rate);
3456 $tax = wc_format_decimal($tax,'');
3457 $label = $shipping['shippingMethod'];
3458 $cost = wc_format_decimal($shipping['shippingCost'],''); // This is inclusive of tax
3459 $costExTax= wc_format_decimal($cost-$tax,'');
3460 $shipping_rate = new WC_Shipping_Rate($rate,$label,$costExTax,array(array('total'=>$tax)), $method, $product);
3461 $shipping_rate = apply_filters('woo_vipps_express_checkout_shipping_rate',$shipping_rate,$costExTax,$tax,$method,$product);
3462 return $shipping_rate;
3463 }
3464
3465 // Used by both callback_check_order_status and handle_callback - sets the neccessary order metadata after a successful (or not vipps transaction). IOK 2025-08-13
3466 public function order_set_transaction_metadata($order, $transaction) {
3467 // Set Vipps metadata as early as possible
3468 $vippsstamp = strtotime($transaction['timeStamp']);
3469 $vippsamount = $transaction['amount'] ?? '';
3470 $vippscurrency= $transaction['currency'] ?? '';
3471 $vippsstatus = $transaction['status'];
3472
3473 $order->update_meta_data('_vipps_callback_timestamp',$vippsstamp);
3474 $order->update_meta_data('_vipps_amount',$vippsamount);
3475 $order->update_meta_data('_vipps_currency',$vippscurrency);
3476 $order->update_meta_data('_vipps_status',$vippsstatus);
3477
3478 // Checkout only, modify payment method name if neccessary
3479 if ($transaction['paymentmethod'] == 'Card') {
3480 if ($order->get_meta('_vipps_checkout')) {
3481 $order->set_payment_method_title(sprintf(__('Credit Card / %1$s', 'woo-vipps'), Vipps::CheckoutName()));
3482 }
3483 }
3484 // Checkout only, banktransfers are handled specially so note that
3485 if ($transaction['paymentmethod'] == 'BankTransfer') {
3486 $order->set_payment_method_title(sprintf(__('Bank Transfer/ %1$s', 'woo-vipps'), Vipps::CheckoutName()));
3487 $order->update_meta_data('_vipps_api', 'banktransfer');
3488 }
3489 }
3490
3491 // Handle the callback from Vipps ePayment
3492 public function handle_callback($result, $order, $ischeckout=false, $iswebhook=false) {
3493 global $Vipps;
3494
3495 $vippsorderid = $result['orderId'];
3496 $merchant= $result['merchantSerialNumber'];
3497
3498 $keyset = $this->get_keyset();
3499 $me = array_keys($keyset);
3500
3501 // Validate the callback first
3502 if (!in_array($merchant, $me)) {
3503 $this->log(sprintf(__("%1\$s callback with wrong merchantSerialNumber - might be forged",'woo-vipps'), $this->get_payment_method_name()) . " " . $order->get_id(), 'warning');
3504 return false;
3505 }
3506 if (!$order) {
3507 $this->log(sprintf(__("%1\$s callback for unknown order",'woo-vipps'), $this->get_payment_method_name()) . " " . $order->get_id(), 'warning');
3508 return false;
3509 }
3510 $order_id = $order->get_id();
3511 if ($vippsorderid != $order->get_meta('_vipps_orderid')) {
3512 $this->log(sprintf(__('Wrong %1$s Orderid - possibly an attempt to fake a callback ', 'woo-vipps'), Vipps::CompanyName()), 'warning');
3513 clean_post_cache($order_id);
3514 exit();
3515 }
3516
3517 // Note any errors in the callback early
3518 $errorInfo = $result['errorInfo'] ?? '';
3519 if ($errorInfo) {
3520 /* translators: payment method name, order id */
3521 $this->log(sprintf(__('Message in callback from %1$s for order %2$s: ','woo-vipps'), $this->get_payment_method_name(), $order_id), $errorInfo['errorMessage'], 'error');
3522 /* translators: payment method name, message */
3523 $order->add_order_note(sprintf(__('Message from %1$s: %2$s','woo-vipps'), $this->get_payment_method_name(), $errorInfo['errorMessage']));
3524 }
3525
3526 // Create a signal file (if possible) so the confirm screen knows to check status IOK 2018-05-04
3527 try {
3528 $Vipps->createCallbackSignal($order,'ok');
3529 } catch (Exception $e) {
3530 // Could not create a signal file, but that's ok.
3531 }
3532
3533 // New callback handling: schedule an Action Scheduler job to process it. The purpose of processing callback
3534 // is to set finalize the order (set order status, set shipping for express) in the case when customer does
3535 // not return to the store, because then poll does not run. LP 2026-03-27
3536
3537 // Below is separate from '_vipps_callback_timestamp' which is when callback is sent,
3538 // but also that meta won't be stored until callback is actually processed. LP 2026-03-30
3539 $order->update_meta_data('_vipps_callback_received_at', time());
3540 // Store the callback data in the order. We'll do a cleanup of this when the scheduled job runs. IOK 2026-04-21
3541 $order->update_meta_data('_vipps_callback_data', $result);
3542 $order->save_meta_data();
3543
3544 // Run callback actions for callback received as soon as it is actually received.
3545 $transaction = []; // No longer provided. IOK 2026-05-06
3546 do_action('woo_vipps_callback_received', $order, $result, $transaction);
3547
3548 $action_args = [
3549 'order_id' => $order->get_id(),
3550 'is_checkout' => $ischeckout,
3551 'is_webhook' => $iswebhook,
3552 ];
3553 // We'll check the status of this order in a minute. At that time, the customer should have been able to return to the store
3554 // and have the order finalized the 'normal' way, but if they don't, we'll handle it async. 2026-04-21
3555 $scheduled_at = time() + 60;
3556 $action_id = as_schedule_single_action($scheduled_at, 'woo_vipps_action_process_callback', $action_args, 'woo-vipps', false);
3557 if ($action_id) {
3558 /* translators: order id, scheduled time */
3559 $this->log(sprintf(__('Callback action scheduled at %2$s for order %1$s', 'woo-vipps'), $order->get_id(), $scheduled_at), 'info');
3560 } else {
3561 // The action scheduler error is not returned, only sent to error_log (https://github.com/woocommerce/action-scheduler/blob/25c982c3d0f8134389d5b5884082403c4806322f/classes/ActionScheduler_ActionFactory.php#L268). LP 2026-04-23
3562 /* translators: order id */
3563 $this->log(sprintf(__('Failed to schedule callback process action for order %1$s, check the php error log', 'woo-vipps'), $order->get_id()), 'error');
3564 /* We will not delete the callback data here, to facilitate debugging. But return false to indicate that callback handling will fail. */
3565 /* NB: The order will still be processed with the periodic job, at a later stage. IOK 2026-05-06 */
3566 return false;
3567 }
3568
3569 // Signal that we in fact handled the order.
3570 return true;
3571 }
3572
3573 /** Runs in action scheduler: sync woo status from Vipps callback data. Handle shipping etc. for Express. LP 2026-03-31 */
3574 public function action_process_callback($order_id, $is_checkout, $is_webhook) {
3575 $order = wc_get_order($order_id);
3576 if (!is_a($order, 'WC_Order')) {
3577 /* translators: order id */
3578 $this->log(sprintf(__('Callback process action failed, could not find order %1$s','woo-vipps'), $order_id), 'error');
3579 return false;
3580 }
3581
3582 $oldstatus = $order->get_status();
3583 if ($oldstatus != 'pending') {
3584 // Actually, we are ok with this order, abort the callback handler. IOK 2018-05-30
3585 $order->delete_meta_data('_vipps_callback_data');
3586 clean_post_cache($order->get_id());
3587 return false;
3588 }
3589 $data = $order->get_meta('_vipps_callback_data');
3590
3591 /* translators: order id */
3592 $this->log(sprintf(__('Callback process action running for order %1$s.', 'woo-vipps'), $order_id));
3593
3594 // The payment details field is passed in Checkout, not in Express, but none of them are complete, so we fill out the values
3595 // depending on which one we are IOK 2025-08-13
3596 $details = [];
3597 // Checkout has this as a field, containing *some* of the neccessary data
3598 if (isset($data['paymentDetails'])) {
3599 // Checkout. The sesssion states are # "SessionCreated" "PaymentInitiated" "SessionExpired" "PaymentSuccessful" "PaymentTerminated"
3600 // -- we should only get callbacks for successful sessions actually.
3601
3602 $details = $data['paymentDetails'];
3603 $data['state'] = $data['sessionState'] == 'PaymentSuccessful' ? 'AUTHORIZED' : ($data['sessionState'] == 'PaymentTerminated' ? 'TERMINATED' : 'CREATED');
3604 $details['state'] = $data['state'];
3605 $details['paymentMethod'] = $data['paymentMethod'];
3606 } else {
3607 // This should be an epayment webhook callback; which we need to add a lot of data for to get a valid "paymentDetails".
3608 $details = [];
3609 $data['state'] = $data['name']; // The name of the callback - which should be AUTHORIZED, TERMINATED etc
3610 $details['state'] = $data['name'];
3611 $details['amount'] = $data['amount']; // currency, value
3612 $details['paymentMethod'] = 'epayment';
3613 }
3614
3615 // For both callbacks, set 'aggregate'
3616 $currency = $details['amount']['currency'];
3617 $nothing = [ 'currency' => $currency, 'value' => 0];
3618 $aggregate = ['authorizedAmount' => $nothing, 'cancelledAmount' => $nothing, 'capturedAmount' => $nothing, 'refundedAmount' => $nothing];
3619 if ($details['state'] == 'AUTHORIZED') {
3620 $aggregate['authorizedAmount'] = $details['amount'];
3621 }
3622 $details['aggregate'] = $aggregate;
3623 $data['paymentDetails'] = $details;
3624
3625 // Do the actual work with a function shared with the periodic job.
3626 $this->set_order_status_by_payment_details($order,$data);
3627
3628 /* translators: payment method name */
3629 $order->add_order_note(sprintf(__('%1$s callback processed','woo-vipps'), $this->get_payment_method_name()));
3630
3631 // We're done, so delete the callback data. IOK 2026-04-22
3632 $order->delete_meta_data('_vipps_callback_data');
3633 }
3634
3635
3636 // Called either by periodic job or by action_process_callback with the callback data *or* with payment details fetched with poll.
3637 // sets order status if neccessary, and will finalize the order for Express via HTTP call if necessary. IOK 2026-05-06
3638 public function set_order_status_by_payment_details($order, $data, $allow_retry=true) {
3639 $data = $this->normalizePaymentDetails($data);
3640 $details = $data['paymentDetails'];
3641 $order_id = $order->get_id();
3642
3643 $vippsstatus = $data['status']; // Will exist now, because of the normalization IOK 2025-08-13
3644 $newstatus = $this->interpret_vipps_order_status($vippsstatus);
3645
3646 // Extract order metadata from either Checkout or Epayment - set below IOK 2025-08-13
3647 $transaction = array();
3648 $stamp = ($data['timestamp'] ?? false) ? strtotime($data['timestamp']) : time();
3649 $transaction['timeStamp'] = date('Y-m-d H:i:s', $stamp);
3650 $transaction['amount'] = $details['amount']['value'];
3651 $transaction['currency'] = $details['amount']['currency'];
3652 $transaction['status'] = ($data['state'] ?? $details['state']);
3653 $transaction['paymentmethod'] = $details['paymentMethod'] ?? "";
3654 $this->order_set_transaction_metadata($order, $transaction);
3655
3656 // This order is ready to set order shipping details etc for IOK 2025-09-19
3657 $ready = false;
3658 if (in_array($newstatus, ['authorized', 'complete'])) {
3659 $ready = true;
3660 }
3661 if ($ready) {
3662 // Failsafe for rare bug when using Klarna Checkout with Vipps as an external payment method
3663 // IOK 2024-01-09 ensure this is called only when order is complete/authorized
3664 $this->reset_erroneous_payment_method($order);
3665 }
3666
3667 $is_express_or_checkout = $order->get_meta('_vipps_express_checkout');
3668
3669 // Handle session and shipping through http, because we dont want to mess with session here in wp cron (action scheduler). LP 2026-03-30
3670 // NB: This is and must be a *synchronous call*. When done, the order will have shipping, addresses etc. IOK 2026-05-06.
3671 $shipping_set = $order->get_meta('_vipps_shipping_set');
3672 if ($ready && $is_express_or_checkout && !$shipping_set) {
3673 $token = $order->get_meta('_vipps_authtoken');
3674 $args = [
3675 'body' => [
3676 'order_id' => $order_id,
3677 'vipps_order_data' => $data,
3678 ],
3679 'headers' => [
3680 'X-WooVipps-Token' => $token,
3681 ],
3682 ];
3683 $url = Vipps::get_rest_url('v1', '/order-set-shipping');
3684 $response = wp_remote_post($url, $args);
3685 if (is_wp_error($response)) {
3686 /* translators: order id, error message */
3687 $error_msg = $response->get_error_message();
3688 $this->log(sprintf(__('Process callback action failed to finalize shipping through http rest endpoint for order %1$s: %2$s', 'woo-vipps'), $order->get_id(), $error_msg), 'error');
3689 } else if (200 != ($response['response']['code'] ?? -1)) {
3690 /* translators: order id */
3691 $response_msg = print_r($response['body'] ?? ['Missing response body'], true);
3692 $this->log(sprintf(__('Process callback action failed to finalize shipping through http rest endpoint for order %1$s: %2$s', 'woo-vipps'), $order->get_id(), $response_msg), 'error');
3693 }
3694 }
3695
3696 // This must happen *after* finalization for Express, as above. IOK 2026-05-06
3697 // the only status we now care about is AUTHORIZED. Previously we had AUTHORISED and RESERVED and RESERVE as well. And SALE.
3698 if ($vippsstatus == 'AUTHORIZED') {
3699 $this->payment_complete($order);
3700 } else if ($vippsstatus == 'SALE') {
3701 // Direct capture needs special handling because most of the meta values we use are missing IOK 2019-02-26
3702 // Actually not supported anymore, but keep logic. IOK 2025-08-13
3703 // Still supported for finnish direct bank transfer. IOK 2026-04-22
3704 $order->add_order_note(sprintf(__('Payment captured directly at %1$s', 'woo-vipps'), $this->get_payment_method_name()));
3705 $order->payment_complete();
3706 $this->update_vipps_payment_details($order);
3707 } else {
3708 // Not ok status; set to failed/cancelled
3709 $order_is_retryable = $allow_retry && Vipps::order_is_vipps_retryable($order->get_id());
3710 $status_on_fail = $this->get_option('status_on_fail');
3711 $cancel_on_fail = apply_filters('woo_vipps_cancel_failed_orders', false, $order, $vippsstatus);
3712 if ($cancel_on_fail || !$order_is_retryable) {
3713 $status_on_fail = 'cancelled';
3714 }
3715 if (!in_array($status_on_fail, ['cancelled', 'failed'])) {
3716 /* translators: %1 = order status parameter. 'cancelled' is woocommerce order status name */
3717 $this->log(__('Unsupported status for payment failure of \'%1$s\', falling back to cancelled.', 'woo-vipps'), 'warning');
3718 $status_on_fail = 'cancelled';
3719 }
3720
3721 /* translators: company name */
3722 $order->update_status($status_on_fail, sprintf(__('Callback: Payment cancelled at %1$s.', 'woo-vipps'), Vipps::CompanyName()));
3723 }
3724
3725 $order->save();
3726 clean_post_cache($order_id);
3727 }
3728
3729 /* finalize shipping for express/checkout order. LP 2026-03-30 */
3730 public function rest_order_set_shipping($request) {
3731 $order_id = $request->get_param('order_id');
3732 $data = $request->get_param('vipps_order_data');
3733
3734 $order = wc_get_order($order_id);
3735 if (!is_a($order, 'WC_Order')) {
3736 return new WP_Error('order_not_found', __('Order not found', 'woo-vipps'), ['status' => 404]);
3737 }
3738
3739 $is_express_or_checkout = $order->get_meta('_vipps_express_checkout');
3740 $shipping_set = $order->get_meta('_vipps_shipping_set');
3741 if (!$is_express_or_checkout || $shipping_set) {
3742 return new WP_Error('order_is_finalized', __('Order does not need to set shipping', 'woo-vipps'), ['status' => 409]);
3743 }
3744
3745 // Ensure we use the same session as for the original order from here on. IOK 2019-10-21
3746 // IOK 2023-07-18 but because of the race condition issue, we cannot guarantee that any changes
3747 // made to the session here will be saved. Sorry.
3748 // UPDATE: Should be no more race condition since we moved callback into the action scheduler, and this shipping finalization into this rest endpoint. LP 2026-03-30
3749 Vipps::instance()->callback_restore_session($order_id);
3750
3751 // For Vipps Checkout version 3 there are no more userDetails, so we will add it, including defaults for anonymous purchases IOK 2023-01-10
3752 // This will also normalize userDetails, adding 'sub' where required and fields for backwards compatibility. 2025-08-12
3753 $data = $this->ensure_userDetails($data, $order);
3754
3755 // Some Express Checkout orders aren't really express checkout orders, but normal orders to which we have
3756 // added scope name, email, phoneNumber. The reason is that we don't care about the address. But then
3757 // we also get no user data in the callback, so we must replace the callback with a user info call. IOK 2023-03-10
3758 // IOK 2025-09-29: This is probably *no longer true* - we now almost certainly *always* get a userDetails field if
3759 // we have added a scope of any kind. This is therefore probably dead code.
3760 // This being dead code, we'll not try to handle errors gracefully here. IOK 2026-03-18
3761 if (!isset($data['userDetails'])) {
3762 // This also calls ensure_userDetails and normalizeShippingDetails - but NB: it could fail, so call only when neccessary.
3763 try {
3764 $details = $this->get_payment_details($order);
3765 $data = $details;
3766 } catch (Exception $e) {
3767 $this->log(sprintf(__("Could not get payment results for order %1\$s", 'woo-vipps'), $order->get_id()));
3768 $this->log($e->getMessage());
3769 }
3770 }
3771
3772 // Epayment Express Checkout is of course also significantly different from both the old Express and from Checkout in the formatting here. IOK 2025-08-12
3773 $data = $this->normalizeShippingDetails($data, $order);
3774
3775 // We should now always have shipping details.
3776 if (isset($data['shippingDetails'])) {
3777 $billing = isset($data['billingDetails']) ? $data['billingDetails'] : false;
3778 $this->set_order_shipping_details($order,$data['shippingDetails'], $data['userDetails'], $billing, $data);
3779 }
3780 }
3781
3782 // Do the 'payment_complete' logic for non-SALE orders IOK 2020-09-22
3783 public function payment_complete($order,$transactionid='') {
3784 // Orders not needing processing can be autocaptured, so try to do so now.
3785 $autocapture = $this->maybe_complete_payment($order);
3786 if (!$autocapture) {
3787 add_filter('woocommerce_payment_complete_order_status',
3788 function ($status, $orderid, $order) {
3789 return $this->after_vipps_order_status($order);
3790 }, 99, 3);
3791 $order->add_order_note(sprintf(__('Payment authorized at %1$s', 'woo-vipps'), $this->get_payment_method_name()));
3792 }
3793 $order->payment_complete();
3794 }
3795
3796 // Hook run by Woo after order is complete (authorized or sale). We'll add receipt info etc here.
3797 public function order_payment_complete ($orderid) {
3798 $order = wc_get_order($orderid);
3799 if (!is_a($order, 'WC_Order')) return false;
3800 if (! Vipps::is_vipps_order($order)) return false;
3801
3802 $do_order_management = apply_filters('woo_vipps_order_management_on_payment_complete', true, $orderid);
3803 if (!$do_order_management) return;
3804
3805 // We do the actual order management call in a separate request which we call non-blocking to avoid it locking
3806 // up the users' session on return from the store. This won't work if your Wordpress doesn't support non-blocking calls,
3807 // so in this case, allow the user to set a longer timeout (5 seconds should be plenty.) IOK 2022-07-01
3808 // Yes, it will block until timeout even if non-blocking is set. IOK 2022-07-01
3809 $timeout = apply_filters('woo_vipps_asynch_timeout', 0.5);
3810 $data = [ 'action'=> 'woo_vipps_order_management','orderid'=>$orderid, 'orderkey' => $order->get_order_key() ];
3811 $args = array( "method" => "POST", "body"=>$data, "timeout"=>$timeout, "blocking" => false);
3812 $url = admin_url('admin-post.php');
3813 $asynch = wp_remote_request($url,$args);
3814 if (is_wp_error($asynch)) {
3815 $this->log(__("Error calling the Order Management API: %1\$s ", 'woo-vipps'), $asynch->get_error_message());
3816 }
3817 }
3818
3819 // The below actions *may* be long-running, and we can't be sure
3820 // they will happen at callback-time. Some user may be affected, even if using wp-cron.
3821 // We therefore set them up to be run at shutdown, as soon as payment complete is done
3822 public function payment_complete_at_shutdown ($orderid, $orderkey) {
3823 // Ensure consistent environment here
3824 global $Vipps;
3825 if (!$Vipps) $Vipps = Vipps::instance();
3826 $order = wc_get_order($orderid);
3827 if (!is_a($order, 'WC_Order')) {
3828 return false;
3829 }
3830 if (! Vipps::is_vipps_order($order)) return false;
3831 if ($order->get_order_key() != wc_clean($orderkey)) {
3832 return false;
3833 }
3834 try {
3835
3836 $sendreceipt = apply_filters('woo_vipps_send_receipt', ($this->get_option('sendreceipts') == 'yes'), $order);
3837 if ($sendreceipt) {
3838 $this->api->add_receipt($order);
3839 $this->order_add_vipps_categories($order);
3840 }
3841 do_action('woo_vipps_payment_complete_at_shutdown', $order, $this);
3842 } catch (Exception $e) {
3843 // This is/should be non-critical so just log it.
3844 $this->log(sprintf(__("Could not do all payment-complete actions on %1\$s order %2\$d: %3\$s ", 'woo-vipps'), Vipps::CompanyName(), $orderid, $e->etMessage()), "error");
3845 }
3846 }
3847
3848 // This is run on payment complete. Per default will it only add a link to the order confirmation page, but
3849 // the hook added should be used if selling tickets, bookings etc to add these to the Vipps app receipt; with images if desired (eg. QR images).
3850 public function order_add_vipps_categories ($order) {
3851 if (!is_a($order, 'WC_Order')) return;
3852
3853 $none = ['link'=>null, 'image'=>null, 'imagesize'=>null];
3854 $orderconfirmation = ['link' => $this->get_return_url($order), 'image' => null, 'imagesize'=>null];
3855
3856 $receipt_image = $this->get_option('receiptimage');
3857 if ($receipt_image) {
3858 $orderconfirmation['image'] = intval($receipt_image);
3859 $orderconfirmation['imagesize'] = 'full';
3860 }
3861
3862 // Do these in this order, in case we get terminated at some point during processing
3863 $default = ['TICKET'=>$none,'ORDER_CONFIRMATION' => $orderconfirmation, 'RECEIPT' => $none,"BOOKING" => $none, "DELIVERY" => $none, "GENERAL" => $none];
3864 $categories = apply_filters('woo_vipps_add_order_categories', $default, $order, $this);
3865
3866 foreach ($categories as $category=>$data) {
3867 if ($data['link']) {
3868 $this->order_add_vipps_category($category, $order, $data['link'], $data['image'], $data['imagesize']);
3869 }
3870 // Let people handle this in other ways if not using filter above IOK 2022-07-01
3871 do_action('woo_vipps_add_order_category', $category, $order, $this);
3872
3873 }
3874 }
3875
3876 // Use the Order Management API to add a link with a category name and an optional image, which is viewable in the order.
3877 public function order_add_vipps_category($categoryname, $order, $link, $image=null, $imagesize='medium') {
3878 $imageid = $image ? $this->add_vipps_image($image, $imagesize) : null;
3879 return $this->api->add_category($order, $link, $imageid, $categoryname);
3880 }
3881
3882 // Use the Order Management API to upload an image that can be attached to the order.
3883 public function add_vipps_image ($imagespec, $size = 'medium') {
3884 // Imagespec is an attachmend id (of an image) or a filename (to an image), and a size if using an attachment id.
3885 $filename = null;
3886 $imageid = 0;
3887 $imagefile = "";
3888 $mime = "";
3889 $accepted_types = ["image/jpeg", "image/png", "image/jpg"]; // Only accepted types at Vipps
3890 $vippsid = null;
3891 $uploads = wp_get_upload_dir();
3892
3893 if (is_numeric($imagespec)) {
3894 // Don't send same image twice if we have an id
3895 $stored = get_post_meta($imagespec, '_vipps_imageid', true);
3896 if ($stored && !$this->is_test_mode()) {
3897 return $stored;
3898 }
3899 $imageid = intval($imagespec);
3900 $imagefile = get_attached_file($imageid);
3901 $mime = get_post_mime_type($imageid);
3902 }
3903
3904 if (!is_file($imagefile) || !in_array($mime, $accepted_types)) {
3905 $this->log(sprintf(__('%1$s is not an image that can be uploaded to %2$s', 'woo-vipps'), $imagefile, Vipps::CompanyName()), 'error');
3906 $this->log(sprintf(__('File type was %1$s; supported types are %2$s', 'woo-vipps'), $mime, join(", ", $accepted_types)), 'error');
3907 return null;
3908 }
3909
3910 if ($imageid) {
3911 $intermediate = image_get_intermediate_size($imageid, $size);
3912 if ($intermediate && isset($intermediate['path'])) {
3913 $imagefile = join(DIRECTORY_SEPARATOR, [$uploads['basedir'] , $intermediate['path']]);
3914 }
3915 }
3916
3917 if ($imagefile) {
3918 // Check image dimensions before uploading
3919 $dimensions = getimagesize($imagefile);
3920 if ($dimensions && $dimensions[1] < 167) { // [1] is height
3921 $this->log(sprintf(__('Image %1$s is too small - height %2$dpx (minimum 167px required)', 'woo-vipps'),
3922 $imagefile, $dimensions[1]), 'error');
3923 return null;
3924 }
3925
3926 $vippsid = $this->api->add_image($imagefile);
3927 if ($vippsid) {
3928 update_post_meta($imageid, '_vipps_imageid', $vippsid);
3929 }
3930 }
3931 return $vippsid;
3932 }
3933
3934 // For the express checkout mechanism, create a partial order without shipping details by simulating checkout->create_order();
3935 // IOK 2018-05-25
3936 public function create_partial_order($ischeckout=false) {
3937 // This is neccessary for some plugins, like Yith Dynamic Pricing, that adds filters to get_price depending on whether or not ischeckout is true.
3938 // so basically, since we are impersonating WC_Checkout here, we should define this constant too. IOK 2020-07-03
3939 wc_maybe_define_constant('WOOCOMMERCE_CHECKOUT', true );
3940
3941 // In *some* cases you may need to actually load classes and reload the cart, because some plugins do not load when DOING_AJAX.
3942 do_action('woo_vipps_express_checkout_before_calculate_totals');
3943 WC()->cart->calculate_fees();
3944 WC()->cart->calculate_totals();
3945 do_action('woo_vipps_before_create_express_checkout_order', WC()->cart);
3946
3947 // We store this in the order so we don't have to access the cart when initiating payment. This allows us to restart orders etc.
3948 $needs_shipping = WC()->cart->needs_shipping();
3949
3950 $contents = WC()->cart->get_cart_contents();
3951 $contents = apply_filters('woo_vipps_create_express_checkout_cart_contents',$contents);
3952 try {
3953 $cart_hash = md5(json_encode(wc_clean($contents)) . WC()->cart->total);
3954 $order = new WC_Order();
3955 $order->set_status('pending');
3956 $order->set_payment_method($this);
3957 if ($ischeckout) {
3958 $order->update_meta_data('_vipps_api', 'epayment');
3959 $order->set_payment_method_title('Vipps Checkout');
3960 } else {
3961 $order->set_payment_method_title('Vipps Express Checkout');
3962 }
3963 // We use 'checkout' as the created_via key as per requests, but allow merchants to use their own. IOK 2022-09-15
3964 $created_via = apply_filters('woo_vipps_express_checkout_created_via', 'checkout', $order, $ischeckout);
3965 $order->set_created_via($created_via);
3966
3967 $dummy = sprintf(__('Vipps Express Checkout', 'woo-vipps')); // this is so gettext will find this string.
3968 $dummy = sprintf(__('Vipps Checkout', 'woo-vipps')); // this is so gettext will find this string.
3969
3970 $order->update_meta_data('_vipps_express_checkout',1);
3971
3972 # To help with address fields, scope etc in inititate payment
3973 $order->update_meta_data('_vipps_needs_shipping', $needs_shipping);
3974
3975 $order->set_customer_id( apply_filters('woocommerce_checkout_customer_id', get_current_user_id() ) );
3976 $order->set_currency( get_woocommerce_currency() );
3977 $order->set_prices_include_tax('yes' === get_option('woocommerce_prices_include_tax') );
3978 $order->set_customer_ip_address( WC_Geolocation::get_ip_address() );
3979 $order->set_customer_user_agent( wc_get_user_agent() );
3980 $order->set_discount_total( WC()->cart->get_discount_total());
3981 $order->set_discount_tax( WC()->cart->get_discount_tax() );
3982 $order->set_cart_tax( WC()->cart->get_cart_contents_tax() + WC()->cart->get_fee_tax() );
3983
3984 // Use these methods directly - they should be safe.
3985 WC()->checkout->create_order_line_items( $order, WC()->cart);
3986 WC()->checkout->create_order_fee_lines( $order, WC()->cart);
3987 WC()->checkout->create_order_tax_lines( $order, WC()->cart);
3988 WC()->checkout->create_order_coupon_lines( $order, WC()->cart);
3989 do_action('woo_vipps_before_calculate_totals_partial_order', $order);
3990 $order->calculate_totals(true);
3991
3992 // Added to support third-party plugins that wants to do stuff with the order before it is saved. IOK 2020-07-03
3993 do_action('woocommerce_checkout_create_order', $order, array());
3994
3995 $orderid = $order->save();
3996
3997 do_action('woo_vipps_express_checkout_order_created', $orderid);
3998
3999 // Normally done by the WC_Checkout::create_order method, so call it here too. IOK 2018-11-19
4000 do_action('woocommerce_checkout_update_order_meta', $orderid, array());
4001
4002 // It isn't possible to remove the javascript or 'after order notice' actions, because these are added as closures
4003 // before anything else is run. But we can disable the hook that saves data. IOK 2024-01-18
4004 if (WC_Gateway_Vipps::instance()->get_option('vippsorderattribution') != 'yes') {
4005 remove_all_filters( 'woocommerce_order_save_attribution_data');
4006 }
4007
4008 // And another one. IOK 2021-11-24
4009 do_action('woocommerce_checkout_order_created', $order );
4010 } catch ( Exception $e ) {
4011 if ( $order && $order instanceof WC_Order ) {
4012 $order->get_data_store()->release_held_coupons( $order );
4013 do_action('woocommerce_checkout_order_exception', $order );
4014 }
4015 // Any errors gets passed upstream IOK 2021-11-24
4016 throw $e;
4017 }
4018 return $orderid;
4019 }
4020
4021 // The order attribution subsystem of Woo requires extra work for our partial orders. IOK 2024-01-09
4022 // The attribution data is added to the order forms with prefixes (after 'order note') and we need to strip the prefix.
4023 public function get_order_attribution_data($input_data) {
4024 $prefix = (string) apply_filters( 'wc_order_attribution_tracking_field_prefix', 'wc_order_attribution_');
4025 $prefix = trim( $prefix, '_' ) . "_";
4026 $len = strlen($prefix);
4027 $params = [];
4028 foreach($input_data as $key=>$val) {
4029 $found = strpos($key, $prefix);
4030 if ($found === 0) {
4031 $paramkey = substr($key, $len);
4032 $params[$paramkey] = $val;
4033 }
4034 }
4035 return $params;
4036 }
4037
4038 public function save_session_in_order($order) {
4039 // The callbacks from Vipps carry no session cookie, so we must store this in the order and use a special session handler when in a callback.
4040 // The Vipps class will restore the session from this on callbacks.
4041 // IOK 2019-10-21
4042 $sessioncookie = array();
4043 $sessionhandler = WC()->session;
4044 if ($sessionhandler && is_a($sessionhandler, 'WC_Session_Handler')) {
4045 // If customer is actually logged in, take note IOK 2019-10-25
4046 WC()->session->set('express_customer_id',get_current_user_id());
4047 WC()->session->save_data();
4048 $sessioncookie=$sessionhandler->get_session_cookie();
4049 } else {
4050 // This actually can't happen. IOK 2020-04-08. Branch added for debugging only.
4051 }
4052
4053 if (!empty($sessioncookie)) {
4054 // Customer id, session expiration, session-epiring and cookie-hash is the contents. IOK 2019-10-21
4055 $order->update_meta_data('_vipps_sessiondata',json_encode($sessioncookie));
4056 $order->save();
4057 }
4058
4059 }
4060
4061 // Using this internally to allow the 'enable' button or not. Checks SSL in addition to currency,
4062 // is valid_for_use can in principle run on a http version of the page; we only need to have https accessible for callbacks,
4063 // but if so, admin should definitely be HTTPS so we just check that. IOK 2018-06-06
4064 public function can_be_activated () {
4065 if (!is_ssl() && !preg_match("!^https!i",home_url())) return false;
4066 return true;
4067 }
4068
4069 // Used by the ajax thing that 'sets activated' - checks that it can be activated and that all keys are present. IOK 2018-06-06
4070 function needs_setup() {
4071 if (!$this->can_be_activated()) return true;
4072 $required = array('merchantSerialNumber','clientId', 'secret', 'Ocp_Apim_Key_eCommerce');
4073 foreach ($required as $key) {
4074 if (!$this->get_option($key)) return true;
4075 }
4076 return false;
4077 }
4078
4079 // Not present in WooCommerce until 3.4.0. Should be deleted when required versions are incremented. IOK 2018-10-26
4080 public function update_option( $key, $value = '') {
4081 if ( empty( $this->settings ) ) {
4082 $this->init_settings();
4083 }
4084 $this->settings[ $key ] = $value;
4085 return update_option( $this->get_option_key(), apply_filters('woocommerce_settings_api_sanitized_fields_' . $this->id, $this->settings ), 'yes');
4086 }
4087
4088
4089 public function admin_options() {
4090 $currency = get_woocommerce_currency();
4091 $payment_method = $this->get_payment_method_name();
4092
4093 if (!$this->can_be_activated()) {
4094 $this->update_option('enabled', 'no');
4095 }
4096
4097 if ($payment_method != "Vipps"): ?>
4098 <style>
4099 #woocommerce_vipps_express_options, #woocommerce_vipps_express_options-table {
4100 display: none;
4101 }
4102 </style>
4103 <?php endif; ?>
4104
4105 <h2 id='vipps-settings-page'><?php echo __(Vipps::CompanyName(),'woo-vipps'); ?> <img style="float:right;max-height:40px;margin-top:-15px" alt="<?php _e($this->title,'woo-vipps'); ?>" src="<?php echo $this->icon; ?>"></h2>
4106 <?php $this->display_errors(); ?>
4107
4108 <?php
4109
4110
4111 if (!$this->payment_method_supports_currency($payment_method, $currency)):
4112 ?>
4113 <div class="inline error">
4114 <p><strong><?php echo sprintf(__('%1$s does not support your currency.', 'woo-vipps'), $payment_method); ?></strong>
4115 <br>
4116 <?php echo sprintf(__('%1$s supported currencies: %2$s', 'woo-vipps'), $payment_method, implode(", ", $this->get_supported_currencies($payment_method))); ?>
4117 </p>
4118 </div>
4119 <?php endif; ?>
4120
4121 <?php if (!is_ssl() && !preg_match("!^https!i",home_url())): ?>
4122 <div class="inline error">
4123 <p><strong><?php _e('Gateway disabled', 'woocommerce'); ?></strong>:
4124 <?php echo sprintf(__('%1$s requires that your site uses HTTPS.', 'woo-vipps'), $payment_method); ?>
4125 </p>
4126 </div>
4127 <?php endif; ?>
4128
4129 <?php // We will only show the Vipps Checkout options if the user has activated the feature (thus creating the pages involved etc). IOK 2021-10-01
4130 $vipps_checkout_activated = get_option('woo_vipps_checkout_activated', false);
4131 ?>
4132
4133 <?php /* We will *not* allow vipps checkout to be activated at this point, since the product is no longer sold. IOK 2026-04-30 */ ?>
4134 <?php if (!$vipps_checkout_activated): ?>
4135
4136 <?php endif; ?>
4137 <table class="form-table">
4138 <?php $this->generate_settings_html(); ?>
4139 </table> <?php
4140 }
4141
4142 // Validate/mangle input fields
4143 function validate_text_field ($key, $value) {
4144 if ($key != 'orderprefix') return parent::validate_text_field($key,$value);
4145 $value = preg_replace('![^a-zA-Z0-9]!','',$value);
4146 return $value;
4147 }
4148 function validate_checkbox_field($key,$value) {
4149 if ($key == 'testmode' && VIPPS_TEST_MODE) {
4150 return "yes";
4151 } else if ($key == 'developermode' && VIPPS_TEST_MODE) {
4152 return "yes";
4153 } else if ($key == 'enabled') {
4154 if ($value && $this->can_be_activated()) return 'yes';
4155 return "no";
4156 }
4157 return parent::validate_checkbox_field($key,$value);
4158 }
4159
4160 function process_admin_options () {
4161 // Handle options updates
4162 $saved = parent::process_admin_options();
4163 // We may have changed the number of form fields at this point if dev mode was changed
4164 // from off to on,so re-initialize the form fields here. IOK 2019-09-03
4165 $this->init_form_fields();
4166
4167 // Reinitialize keysets in case user added/changed these
4168 $this->keyset = null;
4169 delete_transient('_vipps_keyset');
4170 $keyset = $this->get_keyset();
4171
4172 // IOK FIXME check if we are called using ajax for this; and if so add the notifications to a list of notifications
4173 // instead of doing the adminerr/adminnotify thing. IOK 2024-01-03
4174
4175 list($ok,$msg) = $this->check_connection();
4176 if ($ok) {
4177 $this->adminnotify(sprintf(__("Connection to %1\$s is OK", 'woo-vipps'), Vipps::CompanyName()));
4178 } else {
4179 $this->adminerr(sprintf(__("Could not connect to %1\$s", 'woo-vipps'), Vipps::CompanyName()) . ": $msg");
4180 }
4181
4182 if ($ok) {
4183 $this->check_webhooks();
4184 // Try to ensure we have webhooks defined for the epayment-api IOK 2023-12-19
4185 $hooks = $this->initialize_webhooks();
4186 }
4187
4188 // If enabling this, ensure the page in question exists
4189 if ($this->get_option('vipps_checkout_enabled') == 'yes') {
4190 update_option('woo_vipps_checkout_activated', true, true); // This must be true here, but still, make sure
4191 Vipps::instance()->maybe_create_vipps_pages();
4192 }
4193
4194 return $saved;
4195 }
4196
4197 // Check our stored webhooks for consistency, which means the callback URLs should point to *this* site. If they don't,
4198 // delete all the ones pointing wrong. If this returns false, you should reinitialize the webhooks. IOK 2023-12-20
4199 public function check_webhooks () {
4200 $local_hooks = get_option('_woo_vipps_webhooks');
4201 if (!$local_hooks) return false;
4202
4203 $callback = $this->webhook_callback_url();
4204 $callback_compare = strtok($callback, '?');
4205 $problems = false;
4206
4207 // We are going to re-initialize our webhooks after this, but just to ensure we're not keeping any 'stale' hooks,
4208 // we'll update the local hooks too. IOK 2025-02-13
4209 $change = false;
4210 $msns = array_keys($local_hooks);
4211 foreach($msns as $msn) {
4212 $hooks = $local_hooks[$msn];
4213 $ids = array_keys($hooks);
4214 foreach ($ids as $id) {
4215 $hook = $hooks[$id];
4216 $noargs = strtok($hook['url'], '?');
4217 if ($noargs == $callback_compare) continue; // This hook is good, probably, unless somebody has deleted it
4218 try {
4219 $this->log(sprintf(__("For msn %s we have a webhook %s %s which is pointed the wrong way (%s) for this website", 'woo-vipps'), $msn, $hook['id'], $hook['url'], $callback_compare));
4220 $this->api->delete_webhook($msn, $hook['id']); // This isn't - it's pointed the wrong way, which means we have changed name of the site or something
4221 } catch (Exception $e) {
4222 $this->log(sprintf(__("Could not delete webhook for this site with url '%2\$s' : %1\$s", 'woo-vipps'), $e->getMessage(), $noargs), 'error');
4223 }
4224 unset($hooks[$id]);
4225 $change = true;
4226 $problems = true;
4227 }
4228
4229 if ($change) {
4230 if (empty($hooks)) {
4231 unset($local_hooks[$msn]);
4232 } else {
4233 $local_hooks[$msn] = $hooks;
4234 }
4235 }
4236 }
4237
4238 if ($change) {
4239 update_option('_woo_vipps_webhooks', $local_hooks, true);
4240 }
4241
4242 if ($problems) return false;
4243 return true;
4244 }
4245
4246 // Returns the local webhooks for the given msn. If the url has changed, it will return nothing. IOK 2023-12-19
4247 public function get_local_webhook($msn) {
4248 $local_hooks = get_option('_woo_vipps_webhooks');
4249 $hooks = $local_hooks[$msn] ?? [];
4250 $callback = $this->webhook_callback_url();
4251 $callback_compare = strtok($callback, '?');
4252
4253 foreach ($hooks as $id=>$hook) {
4254 $noargs = strtok($hook['url'], '?');
4255 if ($noargs == $callback_compare) {
4256 return $hook;
4257 } else {
4258 // May want to log this somehow
4259 }
4260 }
4261 return null;
4262 }
4263
4264
4265 // This is to be used in deactivate/uninstall - it deletes all webhooks for all MSNs for this instance
4266 // Unfortunatetly, we can't delete other msn's webhooks or webhooks pointing to other URLs. IOK 2023-12-20
4267 public function delete_all_webhooks() {
4268 delete_option('_woo_vipps_webhooks');
4269 $callback = $this->webhook_callback_url();
4270 $comparandum = strtok($callback, '?');
4271 $all_hooks = $this->get_webhooks_from_vipps();
4272 foreach($all_hooks as $msn => $data) {
4273 $hooks = $data['webhooks'] ?? [];
4274 foreach ($hooks as $hook) {
4275 $id = $hook['id'];
4276 $url = $hook['url'];
4277 $noargs = strtok($url, '?');
4278 if ($noargs != $comparandum) continue; // Some other shops hook, we will ignore it
4279 $ok = $this->api->delete_webhook($msn,$id);
4280 }
4281 }
4282 }
4283
4284 // This will initalize the webhooks for this instance, for all MSNs that are configured.
4285 // Hooks that point to us that we *do not* know the secret for, have to be deleted.
4286 public function initialize_webhooks() {
4287 // IOK 2023-12-20 for the epayment api, we need to re-initialize webhooks at this point.
4288 try {
4289 return $this->initialize_webhooks_internal();
4290 } catch (Exception $e) {
4291 $this->log(sprintf(__("Could not initialize webhooks for this site: %1\$s", 'woo-vipps'), $e->getMessage()), 'error');
4292 return [];
4293 }
4294 }
4295
4296 private function initialize_webhooks_internal () {
4297 $local_hooks = get_option('_woo_vipps_webhooks');
4298 $all_hooks = $this->get_webhooks_from_vipps();
4299 $ourselves = $this->webhook_callback_url();
4300 $keysets = $this->get_keyset();
4301
4302 // Ignore any extra arguments
4303 $comparandum = strtok($ourselves, '?');
4304
4305 $change = false;
4306
4307 // We may need to delete webhooks that have been orphaned. There should be exactly one
4308 // for this sites' callback, and we need to know its secret. All others should be deleted.
4309 $delenda = [];
4310
4311
4312 foreach($all_hooks as $msn => $data) {
4313 $hooks = $data['webhooks'] ?? [];
4314 $gotit = false;
4315 $locals = $local_hooks[$msn] ?? [];
4316
4317 foreach ($hooks as $hook) {
4318 $id = $hook['id'];
4319 $url = $hook['url'];
4320 $noargs = strtok($url, '?');
4321 if ($noargs != $comparandum) {
4322 continue; // Some other shops hook, we will ignore it
4323 }
4324 $local = $locals[$id] ?? false;
4325
4326 // If we haven't gotten our hook yet, but we have a local hook now that we know a secret for, note it and continue
4327 if (!$gotit && $local && isset($local['secret'])) {
4328 $gotit = $local;
4329 continue;
4330 }
4331 // Now we have a hook for our own msn and url, but either we don't know the secret or it is a duplicate. It should be deleted.
4332 $delenda[] = $id;
4333 }
4334
4335 // Delete all the webhooks for this msn that we don't want
4336 foreach ($delenda as $wrong) {
4337 $change = true;
4338 $this->api->delete_webhook($msn,$wrong);
4339 }
4340
4341 if ($gotit) {
4342 // Now if we got a hook, then we should *just* remember that for this msn.
4343 $local_hooks[$msn] = array($gotit['id'] => $gotit);
4344 } else {
4345 // If not, we don't have a hook for this msn and site, so we need to (try to) create one
4346 // but only if the MSN is registered for the payment gateway "vipps" ! IOK 2024-12-03
4347 $keys = $keysets[$msn] ?? [];
4348 $gateway = $keys['gw'] ?? 'vipps';
4349
4350 if ($gateway == 'vipps') {
4351 $change = true;
4352 $result = $this->api->register_webhook($msn, $ourselves);
4353 if ($result) {
4354 $local_hooks[$msn] = [$result['id'] => ['id'=>$result['id'], 'url' => $ourselves, 'secret' => $result['secret']]];
4355 }
4356 }
4357 }
4358 }
4359 update_option('_woo_vipps_webhooks', $local_hooks, true);
4360
4361
4362 if ($change) $all_hooks = $this->get_webhooks_from_vipps();
4363
4364 return $all_hooks;
4365 }
4366
4367
4368 // Checks connection of the 'main' MSN IOK 2023-12-19
4369 public function check_connection ($msn = null) {
4370 if (!$msn) {
4371 $msn = $this->get_merchant_serial();
4372 }
4373 $at = $this->get_key($msn);
4374 $s = $this->get_secret($msn);
4375 $c = $this->get_clientid($msn);
4376 if ($at && $s && $c) {
4377
4378
4379
4380 try {
4381 // First, test the client id / client secret which will give us an access token
4382 $token = $this->api->get_access_token($msn,'force');
4383 if ($token) {
4384 // Then, call the webhooks api to check if the msn/sub key is ok
4385 try {
4386 $this->api->get_webhooks_raw($msn);
4387 update_option('woo-vipps-configured', 1, true);
4388 return array(true,'');
4389 } catch (Exception $e) {
4390 $msg = $e->getMessage();
4391 if ($msg == "403 Forbidden") {
4392 $msg= __("MSN or subscription key (or both) seem to be wrong: ", 'woo-vipps') . $msg;
4393 }
4394 update_option('woo-vipps-configured', 0, true);
4395 return array(false, $msg);
4396 }
4397 }
4398
4399 } catch (Exception $e) {
4400 $msg = __("Your client key or secret is wrong.", 'woo-vipps');
4401 update_option('woo-vipps-configured', 0, true);
4402 return array(false, $msg);
4403 }
4404 }
4405 return array(false, ''); // No configuration
4406 }
4407
4408 public function log ($what,$type='info') {
4409 $logger = function_exists('wc_get_logger') ? wc_get_logger() : false;
4410 if ($logger) {
4411 $context = array('source'=>'woo-vipps');
4412 $logger->log($type,$what,$context);
4413 } else {
4414 error_log("woo-vipps ($type): $what");
4415 }
4416 }
4417
4418 // Ensure chosen name gets used in the checkout page IOK 2018-09-12
4419 public function get_title() {
4420 return apply_filters('woo_vipps_payment_method_title', $this->get_payment_method_name());
4421 }
4422
4423 public function get_payment_method_name() {
4424 return $this->get_option('payment_method_name');
4425 }
4426
4427 public function payment_fields() {
4428 // Use Billing Phone if it is required, otherwise ask for a phone IOK 2018-04-24
4429 // For v2 of the api, just let Vipps ask for then umber
4430 // IOK 2019-09-12 removed dead code only used for v1 of api
4431 // This just prints a description of the payment method.
4432 print $this->get_option('description');
4433 return;
4434 }
4435 public function validate_fields() {
4436 return true;
4437 }
4438
4439
4440 }
4441
4442