PluginProbe
Pay with Vipps and MobilePay for WooCommerce / 6.1.9
Pay with Vipps and MobilePay for WooCommerce v6.1.9
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 trunk All 183 releases
woo-vipps / payment / WC_Gateway_Vipps.class.php

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

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