diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6bff56eb..1caf5c69 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [2.6.0] - 2026-01-28
+### Added
+- Added support for manual activation of invoices for payments made with Walley and Klarna invoice methods.
+### Fixed
+- Fixed compatibility issue with Visma Pay.
+
## [2.5.3] - 2025-07-02
### Added
- Added missing accessibility features
diff --git a/package-lock.json b/package-lock.json
index 2532214e..40aee09b 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "paytrail-for-woocommerce",
- "version": "2.5.2",
+ "version": "2.6.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "paytrail-for-woocommerce",
- "version": "2.5.2",
+ "version": "2.6.0",
"license": "MIT",
"dependencies": {
"babel-runtime": "^6.23.0",
diff --git a/package.json b/package.json
index 7e3c47a0..941a9a1e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "paytrail-for-woocommerce",
- "version": "2.5.3",
+ "version": "2.6.0",
"description": "Paytrail is a payment gateway that offers 20+ payment methods for Finnish customers.",
"private": true,
"dependencies": {
diff --git a/plugin.php b/plugin.php
index e5d90161..9599b4ba 100644
--- a/plugin.php
+++ b/plugin.php
@@ -3,13 +3,13 @@
* Plugin Name: Paytrail for WooCommerce
* Plugin URI: https://github.com/paytrail/paytrail-for-woocommerce
* Description: Paytrail is a payment gateway that offers 20+ payment methods for Finnish customers.
- * Version: 2.5.3
+ * Version: 2.6.0
* Requires at least: 4.9
* Requires Plugins: woocommerce
- * Tested up to: 6.8
+ * Tested up to: 6.9
* Requires PHP: 7.3
* WC requires at least: 3.5
- * WC tested up to: 9.9
+ * WC tested up to: 10.4.3
* Author: Paytrail
* Author URI: https://www.paytrail.com/
* Text Domain: paytrail-for-woocommerce
@@ -23,7 +23,7 @@
// Ensure that the file is being run within the WordPress context.
if ( ! defined( 'ABSPATH' ) ) {
- die;
+ die;
}
/**
@@ -31,414 +31,460 @@
*/
final class Plugin {
- /**
- * WooCommerce payment gateway ID.
- */
- public const GATEWAY_ID = 'paytrail';
-
- /**
- * Merchant ID for the test mode.
- */
- public const TEST_MERCHANT_ID = 375917;
-
- /**
- * Secret key for the test mode.
- */
- public const TEST_SECRET_KEY = 'SAIPPUAKAUPPIAS';
-
- public const PAYMENT_METHOD_IMG_URL = 'https://static.paytrail.com/static/img/payment-methods';
-
- public const BASE_URL = 'paytrail/';
-
- public const ADD_CARD_REDIRECT_SUCCESS_URL = 'card-success';
-
- public const ADD_CARD_REDIRECT_CANCEL_URL = 'card-cancel';
-
- public const ADD_CARD_CONTEXT_MY_ACCOUNT = 'my_account';
-
- public const ADD_CARD_CONTEXT_CHECKOUT= 'checkout';
-
- public const ADD_CARD_CONTEXT_CHANGE_PAYMENT_METHOD = 'change_payment_method';
-
- public const CARD_ENDPOINT = 'card';
-
- public const CALLBACK_URL = 'callback';
-
- /**
- * Singleton instance.
- *
- * @var Plugin
- */
- private static $instance;
-
- /**
- * Plugin version.
- *
- * @var string
- */
- public static $version;
-
- /**
- * Plugin directory.
- *
- * @var string
- */
- protected $plugin_dir;
-
- /**
- * Plugin directory URL.
- *
- * @var string
- */
- protected $plugin_dir_url;
-
- /**
- * Container array for possible initialization errors.
- *
- * @var array
- */
- protected $errors = [];
-
- /**
- * Plugin info
- *
- * @var array
- */
- protected $plugin_info = [
- 'Plugin Name',
- 'Plugin URI',
- 'Description',
- 'Version',
- 'Author',
- 'Author URI',
- 'Text Domain',
- 'Domain Path',
- ];
- public function enqueue_jquery() {
- // Enqueue jQuery script
- wp_enqueue_script('jquery');
- }
-
- /**
- * Constructor function
- */
- protected function __construct() {
- $this->plugin_dir = __DIR__;
- $this->plugin_dir_url = plugin_dir_url( __FILE__ );
- $this->plugin_info = array_combine( $this->plugin_info, get_file_data( __FILE__, $this->plugin_info ) );
-
- self::$version = $this->plugin_info['Version'];
-
- // Load the plugin textdomain.
- load_plugin_textdomain( 'paytrail-for-woocommerce', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
-
- // Register customizations
- add_action( 'customize_register', [ $this, 'checkout_customizations' ] );
- // Add custom styles
- add_action( 'wp_head', [ $this, 'paytrail_checkout_customize_css' ] );
- // Enable WP Dashicons on frontend
- add_action( 'wp_enqueue_scripts', function() {
- wp_enqueue_style( 'dashicons' );
- } );
-
- add_action( 'before_woocommerce_init', function() {
- if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
- \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
- \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks',__FILE__, true );
- }
- } );
-
- // Blocks compatibility
- add_action( 'woocommerce_blocks_loaded', [__CLASS__,'register_blocks_support'] );
-
- // Enqueue jQuery
- add_action('admin_enqueue_scripts', array($this, 'enqueue_jquery'));
- add_action('admin_enqueue_scripts', array($this, 'enque_jquery_scripts'));
-
- //Add OP Lasku calculator to the product and cart page
- add_action('woocommerce_init', array($this, 'op_lasku_init'));
- }
-
- /**
- * Register intro scripts
- */
- public static function register_intro_scripts() {
- // Get plugin directory URL
- $plugin_instance = Plugin::instance();
- $plugin_dir_url = $plugin_instance->get_plugin_dir_url();
- $plugin_version = $plugin_instance->get_plugin_info()['Version'];
-
- // Register the custom script
- wp_register_script(
- 'introScripts',
- $plugin_dir_url . 'dist/assets/frontend/intro-scripts.js',
- ['jquery'], // Dependency on jQuery
- $plugin_version,
- true // Enqueue in the footer
- );
-
- // Enqueue the custom script
- wp_enqueue_script('introScripts');
- }
-
- /**
- * Enqueue jQuery UI from WordPress core
- */
- public function enque_jquery_scripts($hook) {
- if ($hook == 'woocommerce_page_wc-settings' && isset($_GET['tab']) && $_GET['tab'] == 'checkout' && isset($_GET['section']) && $_GET['section'] == 'paytrail') {
-
- wp_enqueue_script('jquery');
- // Enqueue jQuery UI Core
- wp_enqueue_script('jquery-ui-core');
- // Enqueue jQuery UI Dialog
- wp_enqueue_script('jquery-ui-dialog');
- // Add jQuery UI styles
- wp_enqueue_style('jquery-ui-css', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css');
- // Enqueue intro scripts
- self::register_intro_scripts();
-
- }
- }
-
- /**
- * Print custom styles
- */
- public function paytrail_checkout_customize_css() {
- ?>
-
- add_setting( 'paytrail_group_background' , array(
- 'default' => '#ebebeb',
- 'transport' => 'refresh',
- ) );
- $wp_customize->add_setting( 'paytrail_group_text' , array(
- 'default' => '#515151',
- 'transport' => 'refresh',
- ) );
- $wp_customize->add_setting( 'paytrail_group_highlighted_background' , array(
- 'default' => '#33798d',
- 'transport' => 'refresh',
- ) );
- $wp_customize->add_setting( 'paytrail_group_highlighted_text' , array(
- 'default' => '#ffffff',
- 'transport' => 'refresh',
- ) );
- $wp_customize->add_setting( 'paytrail_group_hover_background' , array(
- 'default' => '#d0d0d0',
- 'transport' => 'refresh',
- ) );
- $wp_customize->add_setting( 'paytrail_group_hover_text' , array(
- 'default' => '#313131',
- 'transport' => 'refresh',
- ) );
- $wp_customize->add_setting( 'paytrail_method_highlighted' , array(
- 'default' => '#33798d',
- 'transport' => 'refresh',
- ) );
- $wp_customize->add_setting( 'paytrail_method_hover' , array(
- 'default' => '#5399ad',
- 'transport' => 'refresh',
- ) );
- // Section
- $wp_customize->add_section( 'paytrail_checkout_customize_section' , array(
- 'title' => __( 'Payment page personalization', 'paytrail-for-woocommerce' ),
- 'priority' => 30,
- ) );
- // Controls
- $wp_customize->add_control( new \WP_Customize_Color_Control( $wp_customize, 'paytrail_bgcolor', array(
- 'label' => __( 'Payment method group background', 'paytrail-for-woocommerce' ),
- 'section' => 'paytrail_checkout_customize_section',
- 'settings' => 'paytrail_group_background',
- ) ) );
- $wp_customize->add_control( new \WP_Customize_Color_Control( $wp_customize, 'paytrail_fgcolor', array(
- 'label' => __( 'Payment method group text', 'paytrail-for-woocommerce' ),
- 'section' => 'paytrail_checkout_customize_section',
- 'settings' => 'paytrail_group_text',
- ) ) );
- $wp_customize->add_control( new \WP_Customize_Color_Control( $wp_customize, 'paytrail_bgcolor_selected', array(
- 'label' => __( 'Selected payment method group background', 'paytrail-for-woocommerce' ),
- 'section' => 'paytrail_checkout_customize_section',
- 'settings' => 'paytrail_group_highlighted_background',
- ) ) );
- $wp_customize->add_control( new \WP_Customize_Color_Control( $wp_customize, 'paytrail_fgcolor_selected', array(
- 'label' => __( 'Selected payment method group text', 'paytrail-for-woocommerce' ),
- 'section' => 'paytrail_checkout_customize_section',
- 'settings' => 'paytrail_group_highlighted_text',
- ) ) );
- $wp_customize->add_control( new \WP_Customize_Color_Control( $wp_customize, 'paytrail_bgcolor_hover', array(
- 'label' => __( 'Payment method group background hover', 'paytrail-for-woocommerce' ),
- 'section' => 'paytrail_checkout_customize_section',
- 'settings' => 'paytrail_group_hover_background',
- ) ) );
- $wp_customize->add_control( new \WP_Customize_Color_Control( $wp_customize, 'paytrail_fgcolor_hover', array(
- 'label' => __( 'Payment method group text hover', 'paytrail-for-woocommerce' ),
- 'section' => 'paytrail_checkout_customize_section',
- 'settings' => 'paytrail_group_hover_text',
- ) ) );
- $wp_customize->add_control( new \WP_Customize_Color_Control( $wp_customize, 'paytrail_bordercolor_selected', array(
- 'label' => __( 'Selected payment method', 'paytrail-for-woocommerce' ),
- 'section' => 'paytrail_checkout_customize_section',
- 'settings' => 'paytrail_method_highlighted',
- ) ) );
- $wp_customize->add_control( new \WP_Customize_Color_Control( $wp_customize, 'paytrail_bordercolor_hover', array(
- 'label' => __( 'Payment method hover', 'paytrail-for-woocommerce' ),
- 'section' => 'paytrail_checkout_customize_section',
- 'settings' => 'paytrail_method_hover',
- ) ) );
- }
-
- /**
- * Singleton instance getter function
- *
- * @return Plugin
- */
- public static function instance() {
- if ( is_null( self::$instance ) ) {
- // Construct the object.
- self::$instance = new self();
-
- // Run initialization checks. If any of the checks
- // fails, interrupt the execution.
- if ( ! self::$instance->initialization_checks() ) {
- return;
- }
-
- // Check if Composer has been initialized in this directory.
- // Otherwise we just use global composer autoloading.
- if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
- require_once __DIR__ . '/vendor/autoload.php';
- }
-
- // Create new instance of Router class
- new Router();
-
- // Add the gateway class to WooCommerce.
- add_filter( 'woocommerce_payment_gateways', function( $gateways ) {
- $gateways[] = Gateway::CLASS;
-
- return $gateways;
- });
-
- }
-
- return self::$instance;
- }
-
- /**
- * Run checks for plugin requirements.
- *
- * Returns false if checks failed.
- *
- * @return bool
- */
- protected function initialization_checks() {
- $errors = [];
-
- $errors[] = self::check_php_version();
- $errors[] = self::check_woocommerce_active_status();
- $errors[] = self::check_woocommerce_version();
-
- $errors = array_filter( $errors );
-
- if ( ! empty( $errors ) ) {
- add_action( 'admin_notices', function() use ( $errors ) {
- echo '
';
- array_walk( $errors, 'esc_html_e' );
- echo '
';
- });
-
- return false;
- }
- else {
- return true;
- }
- }
-
- /**
- * Checks to run on plugin activation
- *
- * @return void
- */
- public static function activation_check() {
- $checks = [
- 'check_php_version',
- 'check_woocommerce_active_status',
- 'check_woocommerce_version',
- ];
-
- array_walk( $checks, function( $check ) {
- $error = call_user_func( __CLASS__ . '::' . $check );
-
- if ( $error ) {
- wp_die( esc_html( $error ) );
- }
- });
- }
-
- /**
- * Ensure that the PHP version is at least 7.3.
- *
- * @return string|null
- */
- public static function check_php_version() : ?string {
- if ( ! version_compare( PHP_VERSION, '7.3.0', '>=' ) ) {
- return sprintf(
- // translators: The placeholder contains the current PHP version.
- esc_html__( 'Paytrail payment gateway plugin requires a PHP version of at least 7.3. You are currently running version %1$s.', 'paytrail-for-woocommerce' ),
- esc_html( PHP_VERSION )
- );
- }
-
- return null;
- }
-
- /**
- * Ensure that the WooCommerce plugin is active.
- *
- * @return string|null
- */
- public static function check_woocommerce_active_status() : ?string {
- if ( ! class_exists( '\WC_Payment_Gateway' ) ) {
- return esc_html__( 'Paytrail payment gateway plugin requires WooCommerce to be activated.', 'paytrail-for-woocommerce' );
- }
-
- return null;
- }
-
- /**
+ /**
+ * WooCommerce payment gateway ID.
+ */
+ public const GATEWAY_ID = 'paytrail';
+
+ /**
+ * Merchant ID for the test mode.
+ */
+ public const TEST_MERCHANT_ID = 375917;
+
+ /**
+ * Secret key for the test mode.
+ */
+ public const TEST_SECRET_KEY = 'SAIPPUAKAUPPIAS';
+
+ public const PAYMENT_METHOD_IMG_URL = 'https://static.paytrail.com/static/img/payment-methods';
+
+ public const BASE_URL = 'paytrail/';
+
+ public const ADD_CARD_REDIRECT_SUCCESS_URL = 'card-success';
+
+ public const ADD_CARD_REDIRECT_CANCEL_URL = 'card-cancel';
+
+ public const ADD_CARD_CONTEXT_MY_ACCOUNT = 'my_account';
+
+ public const ADD_CARD_CONTEXT_CHECKOUT = 'checkout';
+
+ public const ADD_CARD_CONTEXT_CHANGE_PAYMENT_METHOD = 'change_payment_method';
+
+ public const CARD_ENDPOINT = 'card';
+
+ public const CALLBACK_URL = 'callback';
+
+ /**
+ * Singleton instance.
+ *
+ * @var Plugin
+ */
+ private static $instance;
+
+ /**
+ * Plugin version.
+ *
+ * @var string
+ */
+ public static $version;
+
+ /**
+ * Plugin directory.
+ *
+ * @var string
+ */
+ protected $plugin_dir;
+
+ /**
+ * Plugin directory URL.
+ *
+ * @var string
+ */
+ protected $plugin_dir_url;
+
+ /**
+ * Container array for possible initialization errors.
+ *
+ * @var array
+ */
+ protected $errors = array();
+
+ /**
+ * Plugin info
+ *
+ * @var array
+ */
+ protected $plugin_info = array(
+ 'Plugin Name',
+ 'Plugin URI',
+ 'Description',
+ 'Version',
+ 'Author',
+ 'Author URI',
+ 'Text Domain',
+ 'Domain Path',
+ );
+
+ /**
+ * Gateway instance
+ *
+ * @var Gateway
+ */
+ protected $gateway;
+
+ /**
+ * Enqueue jQuery script
+ */
+ public function enqueue_jquery() {
+ // Enqueue jQuery script
+ wp_enqueue_script( 'jquery' );
+ }
+
+ /**
+ * Constructor function
+ */
+ protected function __construct() {
+ $this->plugin_dir = __DIR__;
+ $this->plugin_dir_url = plugin_dir_url( __FILE__ );
+ $this->plugin_info = array_combine( $this->plugin_info, get_file_data( __FILE__, $this->plugin_info ) );
+
+ self::$version = $this->plugin_info['Version'];
+
+ // Load the plugin textdomain.
+ load_plugin_textdomain( 'paytrail-for-woocommerce', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
+
+ // Register customizations.
+ add_action( 'customize_register', array( $this, 'checkout_customizations' ) );
+ // Add custom styles.
+ add_action( 'wp_head', array( $this, 'paytrail_checkout_customize_css' ) );
+ // Enable WP Dashicons on frontend.
+ add_action(
+ 'wp_enqueue_scripts',
+ function () {
+ wp_enqueue_style( 'dashicons' );
+ }
+ );
+
+ add_action(
+ 'before_woocommerce_init',
+ function () {
+ if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
+ \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
+ \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', __FILE__, true );
+ }
+ }
+ );
+
+ // Blocks compatibility.
+ add_action( 'woocommerce_blocks_loaded', array( __CLASS__, 'register_blocks_support' ) );
+
+ // Enqueue jQuery.
+ add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_jquery' ) );
+ add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_jquery_scripts' ) );
+
+ // Add OP Lasku calculator to the product and cart page.
+ add_action( 'woocommerce_init', array( $this, 'op_lasku_init' ) );
+
+ add_action( 'init', array( $this, 'initialize_gateway' ) );
+ }
+
+ /**
+ * Initialize the gateway
+ */
+ public function initialize_gateway() {
+ $this->gateway();
+
+ add_filter(
+ 'woocommerce_payment_gateways',
+ function ( $gateways ) {
+ $gateways[] = $this->gateway();
+ add_action( 'template_redirect', array( $this->gateway, 'on_redirect_to_thankyou_page' ) );
+
+ return $gateways;
+ }
+ );
+ }
+
+ /**
+ * Register intro scripts
+ */
+ public static function register_intro_scripts() {
+ // Get plugin directory URL
+ $plugin_instance = self::instance();
+ $plugin_dir_url = $plugin_instance->get_plugin_dir_url();
+ $plugin_version = $plugin_instance->get_plugin_info()['Version'];
+
+ // Register the custom script
+ wp_register_script(
+ 'introScripts',
+ $plugin_dir_url . 'dist/assets/frontend/intro-scripts.js',
+ array( 'jquery' ), // Dependency on jQuery
+ $plugin_version,
+ true // Enqueue in the footer
+ );
+
+ // Enqueue the custom script
+ wp_enqueue_script( 'introScripts' );
+ }
+
+ /**
+ * Enqueue jQuery UI from WordPress core
+ */
+ public function enqueue_jquery_scripts( $hook ) {
+ if ( $hook == 'woocommerce_page_wc-settings' && isset( $_GET['tab'] ) && $_GET['tab'] == 'checkout' && isset( $_GET['section'] ) && $_GET['section'] == 'paytrail' ) {
+
+ wp_enqueue_script( 'jquery' );
+ // Enqueue jQuery UI Core
+ wp_enqueue_script( 'jquery-ui-core' );
+ // Enqueue jQuery UI Dialog
+ wp_enqueue_script( 'jquery-ui-dialog' );
+ // Add jQuery UI styles
+ wp_enqueue_style( 'jquery-ui-css', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );
+ // Enqueue intro scripts
+ self::register_intro_scripts();
+
+ }
+ }
+
+ /**
+ * Print custom styles
+ */
+ public function paytrail_checkout_customize_css() {
+ ?>
+
+ add_setting(
+ 'paytrail_group_background',
+ array(
+ 'default' => '#ebebeb',
+ 'transport' => 'refresh',
+ )
+ );
+ $wp_customize->add_setting(
+ 'paytrail_group_text',
+ array(
+ 'default' => '#515151',
+ 'transport' => 'refresh',
+ )
+ );
+ $wp_customize->add_setting(
+ 'paytrail_group_highlighted_background',
+ array(
+ 'default' => '#33798d',
+ 'transport' => 'refresh',
+ )
+ );
+ $wp_customize->add_setting(
+ 'paytrail_group_highlighted_text',
+ array(
+ 'default' => '#ffffff',
+ 'transport' => 'refresh',
+ )
+ );
+ $wp_customize->add_setting(
+ 'paytrail_group_hover_background',
+ array(
+ 'default' => '#d0d0d0',
+ 'transport' => 'refresh',
+ )
+ );
+ $wp_customize->add_setting(
+ 'paytrail_group_hover_text',
+ array(
+ 'default' => '#313131',
+ 'transport' => 'refresh',
+ )
+ );
+ $wp_customize->add_setting(
+ 'paytrail_method_highlighted',
+ array(
+ 'default' => '#33798d',
+ 'transport' => 'refresh',
+ )
+ );
+ $wp_customize->add_setting(
+ 'paytrail_method_hover',
+ array(
+ 'default' => '#5399ad',
+ 'transport' => 'refresh',
+ )
+ );
+ // Section
+ $wp_customize->add_section(
+ 'paytrail_checkout_customize_section',
+ array(
+ 'title' => __( 'Payment page personalization', 'paytrail-for-woocommerce' ),
+ 'priority' => 30,
+ )
+ );
+ // Controls
+ $wp_customize->add_control(
+ new \WP_Customize_Color_Control(
+ $wp_customize,
+ 'paytrail_bgcolor',
+ array(
+ 'label' => __( 'Payment method group background', 'paytrail-for-woocommerce' ),
+ 'section' => 'paytrail_checkout_customize_section',
+ 'settings' => 'paytrail_group_background',
+ )
+ )
+ );
+ $wp_customize->add_control(
+ new \WP_Customize_Color_Control(
+ $wp_customize,
+ 'paytrail_fgcolor',
+ array(
+ 'label' => __( 'Payment method group text', 'paytrail-for-woocommerce' ),
+ 'section' => 'paytrail_checkout_customize_section',
+ 'settings' => 'paytrail_group_text',
+ )
+ )
+ );
+ $wp_customize->add_control(
+ new \WP_Customize_Color_Control(
+ $wp_customize,
+ 'paytrail_bgcolor_selected',
+ array(
+ 'label' => __( 'Selected payment method group background', 'paytrail-for-woocommerce' ),
+ 'section' => 'paytrail_checkout_customize_section',
+ 'settings' => 'paytrail_group_highlighted_background',
+ )
+ )
+ );
+ $wp_customize->add_control(
+ new \WP_Customize_Color_Control(
+ $wp_customize,
+ 'paytrail_fgcolor_selected',
+ array(
+ 'label' => __( 'Selected payment method group text', 'paytrail-for-woocommerce' ),
+ 'section' => 'paytrail_checkout_customize_section',
+ 'settings' => 'paytrail_group_highlighted_text',
+ )
+ )
+ );
+ $wp_customize->add_control(
+ new \WP_Customize_Color_Control(
+ $wp_customize,
+ 'paytrail_bgcolor_hover',
+ array(
+ 'label' => __( 'Payment method group background hover', 'paytrail-for-woocommerce' ),
+ 'section' => 'paytrail_checkout_customize_section',
+ 'settings' => 'paytrail_group_hover_background',
+ )
+ )
+ );
+ $wp_customize->add_control(
+ new \WP_Customize_Color_Control(
+ $wp_customize,
+ 'paytrail_fgcolor_hover',
+ array(
+ 'label' => __( 'Payment method group text hover', 'paytrail-for-woocommerce' ),
+ 'section' => 'paytrail_checkout_customize_section',
+ 'settings' => 'paytrail_group_hover_text',
+ )
+ )
+ );
+ $wp_customize->add_control(
+ new \WP_Customize_Color_Control(
+ $wp_customize,
+ 'paytrail_bordercolor_selected',
+ array(
+ 'label' => __( 'Selected payment method', 'paytrail-for-woocommerce' ),
+ 'section' => 'paytrail_checkout_customize_section',
+ 'settings' => 'paytrail_method_highlighted',
+ )
+ )
+ );
+ $wp_customize->add_control(
+ new \WP_Customize_Color_Control(
+ $wp_customize,
+ 'paytrail_bordercolor_hover',
+ array(
+ 'label' => __( 'Payment method hover', 'paytrail-for-woocommerce' ),
+ 'section' => 'paytrail_checkout_customize_section',
+ 'settings' => 'paytrail_method_hover',
+ )
+ )
+ );
+ }
+
+ /**
+ * Singleton instance getter function
+ *
+ * @return Plugin
+ */
+ public static function instance() {
+ if ( is_null( self::$instance ) ) {
+ // Check if Composer has been initialized in this directory.
+ // Otherwise we just use global composer autoloading.
+ if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
+ require_once __DIR__ . '/vendor/autoload.php';
+ }
+
+ // Construct the object.
+ self::$instance = new self();
+
+ // Create new instance of Router class.
+ new Router();
+ }
+
+ return self::$instance;
+ }
+
+ /**
+ * Ensure that the PHP version is at least 7.3.
+ *
+ * @return string|null
+ */
+ public static function check_php_version(): ?string {
+ if ( ! version_compare( PHP_VERSION, '7.3.0', '>=' ) ) {
+ return sprintf(
+ // translators: The placeholder contains the current PHP version.
+ esc_html__( 'Paytrail payment gateway plugin requires a PHP version of at least 7.3. You are currently running version %1$s.', 'paytrail-for-woocommerce' ),
+ esc_html( PHP_VERSION )
+ );
+ }
+
+ return null;
+ }
+
+ /**
+ * Ensure that the WooCommerce plugin is active.
+ *
+ * @return string|null
+ */
+ public static function check_woocommerce_active_status(): ?string {
+ if ( ! class_exists( '\WC_Payment_Gateway' ) ) {
+ return esc_html__( 'Paytrail payment gateway plugin requires WooCommerce to be activated.', 'paytrail-for-woocommerce' );
+ }
+
+ return null;
+ }
+
+ /**
* Register blocks support
*/
public static function register_blocks_support() {
@@ -447,57 +493,57 @@ public static function register_blocks_support() {
add_action(
'woocommerce_blocks_payment_method_type_registration',
- function( \Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
- $payment_method_registry->register( new Paytrail_Blocks_Support() );
+ function ( \Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
+ $payment_method_registry->register( new Paytrail_Blocks_Support() );
}
);
}
}
- /**
- * Ensure that we have at least version 3.5 of the WooCommerce plugin.
- *
- * @return string|null
- */
- public static function check_woocommerce_version() : ?string {
- if (
- defined( 'WOO_COMMERCE_VERSION' ) &&
- version_compare( WOO_COMMERCE_VERSION, '3.5' ) === -1
- ) {
- return esc_html__( 'Paytrail gateway plugin requires WooCommerce version of 3.5 or greater.', 'paytrail-for-woocommerce' );
- }
-
- return null;
- }
-
- /**
- * Get plugin directory.
- *
- * @return string
- */
- public function get_plugin_dir() : string {
- return $this->plugin_dir;
- }
-
- /**
- * Get plugin directory URL.
- *
- * @return string
- */
- public function get_plugin_dir_url() : string {
- return $this->plugin_dir_url;
- }
-
- /**
- * Get plugin info.
- *
- * @return array
- */
- public function get_plugin_info() : array {
- return $this->plugin_info;
- }
-
- /**
+ /**
+ * Ensure that we have at least version 3.5 of the WooCommerce plugin.
+ *
+ * @return string|null
+ */
+ public static function check_woocommerce_version(): ?string {
+ if (
+ defined( 'WOO_COMMERCE_VERSION' ) &&
+ version_compare( WOO_COMMERCE_VERSION, '3.5' ) === -1
+ ) {
+ return esc_html__( 'Paytrail gateway plugin requires WooCommerce version of 3.5 or greater.', 'paytrail-for-woocommerce' );
+ }
+
+ return null;
+ }
+
+ /**
+ * Get plugin directory.
+ *
+ * @return string
+ */
+ public function get_plugin_dir(): string {
+ return $this->plugin_dir;
+ }
+
+ /**
+ * Get plugin directory URL.
+ *
+ * @return string
+ */
+ public function get_plugin_dir_url(): string {
+ return $this->plugin_dir_url;
+ }
+
+ /**
+ * Get plugin info.
+ *
+ * @return array
+ */
+ public function get_plugin_info(): array {
+ return $this->plugin_info;
+ }
+
+ /**
* Plugin url.
*
* @return string
@@ -515,21 +561,31 @@ public static function plugin_abspath() {
return trailingslashit( plugin_dir_path( __FILE__ ) );
}
- /**
- * Initialize OP Lasku calculator for product and cart page
- */
- public function op_lasku_init() {
- $settings = get_option('woocommerce_paytrail_settings');
-
- if(isset($settings['op_lasku_calculator']) && 'yes' === $settings['op_lasku_calculator']) {
- new \Paytrail\WooCommercePaymentGateway\Providers\OPLasku();
- }
- }
-}
+ /**
+ * Initialize OP Lasku calculator for product and cart page
+ */
+ public function op_lasku_init() {
+ $settings = get_option( 'woocommerce_paytrail_settings' );
+
+ if ( isset( $settings['op_lasku_calculator'] ) && 'yes' === $settings['op_lasku_calculator'] ) {
+ new \Paytrail\WooCommercePaymentGateway\Providers\OPLasku();
+ }
+ }
-add_action( 'plugins_loaded', function() {
- Plugin::instance();
-});
+ /**
+ * Get the Gateway class instance.
+ *
+ * @return Gateway
+ */
+ public function gateway(): Gateway {
+ // If the gateway is not initialized, initialize it.
+ if ( ! isset( $this->gateway ) ) {
+ $this->gateway = new Gateway();
+ }
+
+ return $this->gateway;
+ }
+}
-register_activation_hook( __FILE__, __NAMESPACE__ . '\\Plugin::activation_check' );
+$paytrail = Plugin::instance();
diff --git a/readme.txt b/readme.txt
index 82549c6c..4cd9f0d4 100644
--- a/readme.txt
+++ b/readme.txt
@@ -3,8 +3,8 @@ Contributors: loueranta, kotivuori
Donate link: https://www.paytrail.com/
Tags: woocommerce
Requires at least: 4.9
-Tested up to: 6.8
-Stable tag: 2.5.3
+Tested up to: 6.9
+Stable tag: 2.6.0
Requires PHP: 7.3
License: MIT
License URI: https://opensource.org/licenses/MIT
@@ -55,6 +55,9 @@ Test credentials:
With test credentials, you can test most of the payment methods included in Paytrail’s payment service. You can find the payment method specific credentials needed for testing in Paytrail’s [documentation](https://docs.paytrail.com/#/payment-method-providers).
== Changelog ==
+= 2.6.0 =
+- Added support for manual activation of invoices for payments made with Walley and Klarna invoice methods.
+- Fixed compatibility issue with Visma Pay.
= 2.5.3 =
- Added missing accessibility features
diff --git a/src/Controllers/AbstractController.php b/src/Controllers/AbstractController.php
index b9741599..b516f90a 100644
--- a/src/Controllers/AbstractController.php
+++ b/src/Controllers/AbstractController.php
@@ -7,11 +7,11 @@
abstract class AbstractController {
- public function execute( $action = null) {
- if (method_exists($this, $action)) {
+ public function execute( $action = null ) {
+ if ( method_exists( $this, $action ) ) {
$this->$action();
} else {
- echo esc_html('Not found');
+ echo esc_html( 'Not found' );
return;
}
}
diff --git a/src/Controllers/Callback.php b/src/Controllers/Callback.php
index 90712e75..c5f85c90 100644
--- a/src/Controllers/Callback.php
+++ b/src/Controllers/Callback.php
@@ -5,11 +5,15 @@
namespace Paytrail\WooCommercePaymentGateway\Controllers;
-use Paytrail\WooCommercePaymentGateway\Gateway;
+use Paytrail\WooCommercePaymentGateway\Plugin;
class Callback extends AbstractController {
+ /**
+ * Index method for the Callback controller
+ */
protected function index() {
- new Gateway(['callbackMode' => true]);
+ Plugin::instance()->gateway()->set_callback_mode( true );
+ Plugin::instance()->gateway()->check_paytrail_response(); // Trigger the response check to process any potential payment response.
}
}
diff --git a/src/Controllers/Card.php b/src/Controllers/Card.php
index c0fb53da..9f3fc2ed 100644
--- a/src/Controllers/Card.php
+++ b/src/Controllers/Card.php
@@ -5,9 +5,8 @@
namespace Paytrail\WooCommercePaymentGateway\Controllers;
-use Paytrail\WooCommercePaymentGateway\Gateway;
use Paytrail\WooCommercePaymentGateway\Plugin;
-//use Paytrail\WooCommercePaymentGateway\Exception;
+// use Paytrail\WooCommercePaymentGateway\Exception;
use WC_Payment_Tokens;
use WP_Error;
use WP_HTTP_Response;
@@ -15,10 +14,11 @@
class Card extends AbstractController {
protected function add() {
- $gateway = new Gateway();
+ $gateway = Plugin::instance()->gateway();
+
try {
$gateway->add_card_form();
- } catch (\Exception $e) {
+ } catch ( \Exception $e ) {
return null;
}
}
@@ -32,17 +32,17 @@ protected function add() {
protected function delete() {
try {
$this->validate_request();
- } catch (\Exception $e) {
- wc_add_notice(__('Card could not be deleted', 'paytrail-for-woocommerce'), 'error');
+ } catch ( \Exception $e ) {
+ wc_add_notice( __( 'Card could not be deleted', 'paytrail-for-woocommerce' ), 'error' );
wp_send_json_error();
- return new WP_Error('invalid-request', $e->getMessage(), array('status' => 400));
+ return new WP_Error( 'invalid-request', $e->getMessage(), array( 'status' => 400 ) );
}
- $body = file_get_contents('php://input');
- $data = json_decode($body, true);
+ $body = file_get_contents( 'php://input' );
+ $data = json_decode( $body, true );
- if (!is_array($data)) {
- throw new \Exception('Failed to decode JSON object');
+ if ( ! is_array( $data ) ) {
+ throw new \Exception( 'Failed to decode JSON object' );
}
// @var \WP_User $current_user
@@ -50,44 +50,44 @@ protected function delete() {
$token_id = $data['token_id'];
- if (!$current_user->ID || !$token_id) {
- return new WP_Error('cant-delete', __('message', 'text-domain'), array('status' => 500));
+ if ( ! $current_user->ID || ! $token_id ) {
+ return new WP_Error( 'cant-delete', __( 'message', 'text-domain' ), array( 'status' => 500 ) );
}
- $customer_tokens = WC_Payment_Tokens::get_customer_tokens($current_user->ID, Plugin::GATEWAY_ID);
- $customer_token_ids = array_keys($customer_tokens);
+ $customer_tokens = WC_Payment_Tokens::get_customer_tokens( $current_user->ID, Plugin::GATEWAY_ID );
+ $customer_token_ids = array_keys( $customer_tokens );
- if (!in_array($token_id, $customer_token_ids)) {
- return new WP_Error('cant-delete', __('message', 'text-domain'), array('status' => 500));
+ if ( ! in_array( $token_id, $customer_token_ids ) ) {
+ return new WP_Error( 'cant-delete', __( 'message', 'text-domain' ), array( 'status' => 500 ) );
}
try {
- WC_Payment_Tokens::delete($token_id);
- wc_add_notice(__('Card was deleted successfully', 'paytrail-for-woocommerce'), 'success');
- wp_send_json_success($data);
- return new WP_HTTP_Response(['type' => 'success'], 200);
- } catch (\Exception $e) {
- wc_add_notice(__('Card could not be deleted', 'paytrail-for-woocommerce'), 'error');
+ WC_Payment_Tokens::delete( $token_id );
+ wc_add_notice( __( 'Card was deleted successfully', 'paytrail-for-woocommerce' ), 'success' );
+ wp_send_json_success( $data );
+ return new WP_HTTP_Response( array( 'type' => 'success' ), 200 );
+ } catch ( \Exception $e ) {
+ wc_add_notice( __( 'Card could not be deleted', 'paytrail-for-woocommerce' ), 'error' );
wp_send_json_error();
- return new WP_Error('cant-delete', __('message', 'text-domain'), array('status' => 500));
+ return new WP_Error( 'cant-delete', __( 'message', 'text-domain' ), array( 'status' => 500 ) );
}
}
private function validate_request() {
- $request_method = isset($_SERVER['REQUEST_METHOD']) ? sanitize_text_field($_SERVER['REQUEST_METHOD']) : '';
+ $request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( $_SERVER['REQUEST_METHOD'] ) : '';
- if (empty($request_method)) {
+ if ( empty( $request_method ) ) {
return;
}
- if ('POST' !== $request_method) {
- throw new \Exception('Only POST requests are allowed');
+ if ( 'POST' !== $request_method ) {
+ throw new \Exception( 'Only POST requests are allowed' );
}
- $content_type = isset($_SERVER['CONTENT_TYPE']) ? sanitize_text_field($_SERVER['CONTENT_TYPE']) : '';
+ $content_type = isset( $_SERVER['CONTENT_TYPE'] ) ? sanitize_text_field( $_SERVER['CONTENT_TYPE'] ) : '';
- if (stripos($content_type, 'application/json') === false) {
- throw new \Exception('Content-Type must be application/json');
+ if ( stripos( $content_type, 'application/json' ) === false ) {
+ throw new \Exception( 'Content-Type must be application/json' );
}
}
}
diff --git a/src/Controllers/CardCancel.php b/src/Controllers/CardCancel.php
index eb1077fe..87c885d4 100644
--- a/src/Controllers/CardCancel.php
+++ b/src/Controllers/CardCancel.php
@@ -8,20 +8,20 @@
class CardCancel extends AbstractController {
protected function checkout() {
- wc_add_notice(__('Could not add card details', 'paytrail-for-woocommerce'), 'error');
- wp_safe_redirect(wc_get_checkout_url());
+ wc_add_notice( __( 'Could not add card details', 'paytrail-for-woocommerce' ), 'error' );
+ wp_safe_redirect( wc_get_checkout_url() );
exit;
}
protected function my_account() {
- wc_add_notice(__('Could not add card details', 'paytrail-for-woocommerce'), 'error');
- wp_safe_redirect(wc_get_account_endpoint_url('payment-methods'));
+ wc_add_notice( __( 'Could not add card details', 'paytrail-for-woocommerce' ), 'error' );
+ wp_safe_redirect( wc_get_account_endpoint_url( 'payment-methods' ) );
exit;
}
protected function change_payment_method() {
- wc_add_notice(__('Could not add card details', 'paytrail-for-woocommerce'), 'error');
- wp_safe_redirect(wc_get_account_endpoint_url('subscriptions'));
+ wc_add_notice( __( 'Could not add card details', 'paytrail-for-woocommerce' ), 'error' );
+ wp_safe_redirect( wc_get_account_endpoint_url( 'subscriptions' ) );
exit;
}
}
diff --git a/src/Controllers/CardSuccess.php b/src/Controllers/CardSuccess.php
index d60363cc..932b9df5 100644
--- a/src/Controllers/CardSuccess.php
+++ b/src/Controllers/CardSuccess.php
@@ -7,49 +7,49 @@
use Paytrail\SDK\Exception\HmacException;
use Paytrail\SDK\Exception\ValidationException;
-use Paytrail\WooCommercePaymentGateway\Gateway;
+use Paytrail\WooCommercePaymentGateway\Plugin;
class CardSuccess extends AbstractController {
protected function checkout() {
- $gateway = new Gateway();
+ $gateway = Plugin::instance()->gateway();
try {
$gateway->process_card_token();
- wc_add_notice(__('Card was added successfully', 'paytrail-for-woocommerce'), 'success');
- } catch (HmacException $e) {
- wc_add_notice(__('Could not add card details', 'paytrail-for-woocommerce'), 'error');
- } catch (ValidationException $e) {
- wc_add_notice(__('Could not add card details', 'paytrail-for-woocommerce'), 'error');
+ wc_add_notice( __( 'Card was added successfully', 'paytrail-for-woocommerce' ), 'success' );
+ } catch ( HmacException $e ) {
+ wc_add_notice( __( 'Could not add card details', 'paytrail-for-woocommerce' ), 'error' );
+ } catch ( ValidationException $e ) {
+ wc_add_notice( __( 'Could not add card details', 'paytrail-for-woocommerce' ), 'error' );
}
- wp_safe_redirect(wc_get_checkout_url());
+ wp_safe_redirect( wc_get_checkout_url() );
exit;
}
protected function my_account() {
- $gateway = new Gateway();
+ $gateway = Plugin::instance()->gateway();
try {
$gateway->process_card_token();
- wc_add_notice(__('Card was added successfully', 'paytrail-for-woocommerce'), 'success');
- } catch (HmacException $e) {
- wc_add_notice(__('Could not add card details', 'paytrail-for-woocommerce'), 'error');
- } catch (ValidationException $e) {
- wc_add_notice(__('Could not add card details', 'paytrail-for-woocommerce'), 'error');
+ wc_add_notice( __( 'Card was added successfully', 'paytrail-for-woocommerce' ), 'success' );
+ } catch ( HmacException $e ) {
+ wc_add_notice( __( 'Could not add card details', 'paytrail-for-woocommerce' ), 'error' );
+ } catch ( ValidationException $e ) {
+ wc_add_notice( __( 'Could not add card details', 'paytrail-for-woocommerce' ), 'error' );
}
- wp_safe_redirect(wc_get_account_endpoint_url('payment-methods'));
+ wp_safe_redirect( wc_get_account_endpoint_url( 'payment-methods' ) );
exit;
}
protected function change_payment_method() {
- $gateway = new Gateway();
+ $gateway = Plugin::instance()->gateway();
try {
$gateway->process_card_token();
- wc_add_notice(__('Card was added successfully', 'paytrail-for-woocommerce'), 'success');
- } catch (HmacException $e) {
- wc_add_notice(__('Could not add card details', 'paytrail-for-woocommerce'), 'error');
- } catch (ValidationException $e) {
- wc_add_notice(__('Could not add card details', 'paytrail-for-woocommerce'), 'error');
+ wc_add_notice( __( 'Card was added successfully', 'paytrail-for-woocommerce' ), 'success' );
+ } catch ( HmacException $e ) {
+ wc_add_notice( __( 'Could not add card details', 'paytrail-for-woocommerce' ), 'error' );
+ } catch ( ValidationException $e ) {
+ wc_add_notice( __( 'Could not add card details', 'paytrail-for-woocommerce' ), 'error' );
}
- wp_safe_redirect(wc_get_account_endpoint_url('subscriptions'));
+ wp_safe_redirect( wc_get_account_endpoint_url( 'subscriptions' ) );
exit;
}
}
diff --git a/src/Controllers/MetaBox.php b/src/Controllers/MetaBox.php
new file mode 100644
index 00000000..5f756a79
--- /dev/null
+++ b/src/Controllers/MetaBox.php
@@ -0,0 +1,126 @@
+ID ) : $order;
+ if ( Plugin::GATEWAY_ID === $order->get_payment_method() ) {
+ add_meta_box(
+ 'paytrail_meta_box',
+ __( 'Paytrail', 'paytrail-for-woocommerce' ),
+ function () use ( $order ) {
+ $this->meta_box_content( $order );
+ },
+ $screen_id,
+ 'side',
+ 'core'
+ );
+ }
+ }
+ }
+
+ /**
+ * Determines whether the success or error content should be printed.
+ *
+ * @param \WC_Order $order The WC order.
+ * @return void
+ */
+ public function meta_box_content( $order ) {
+ // Note: when this method is called, we've already registered the metabox. Thus, it will appear for the merchant. We should display something, even if it is something as simple as error message that explains why it is empty.
+
+ if ( empty( $order->get_transaction_id() ) ) {
+ $data = array( 'error' => __( 'The order is missing transaction ID.', 'paytrail-for-woocommerce' ) );
+ } else {
+
+ $model = new Model\MetaBox( $order );
+ $paytrail_order = $model->get_status();
+ if ( empty( $paytrail_order ) ) {
+ $data = array( 'error' => __( 'Failed to retrieve the order from Paytrail.', 'paytrail-for-woocommerce' ) );
+ } else {
+ $data = array(
+ 'status' => $model->get_status(),
+ 'amount' => $model->get_amount(),
+ 'currency' => $model->get_currency(),
+ 'transaction_id' => $model->get_transaction_id(),
+ );
+ }
+ }
+
+ ( new View( 'MetaBox' ) )->render( $data );
+ }
+
+ /**
+ * Handles manual invoice request if submitted.
+ *
+ * @param int $order_id The WC order ID.
+ * @return void
+ */
+ public function maybe_handle_manual_invoice_request( $order_id ) {
+ $order = wc_get_order( $order_id );
+ try {
+ if ( ! $order ) {
+ return;
+ }
+
+ // If the WooCommerce order is not for Paytrail or it has already been paid.
+ if ( Plugin::GATEWAY_ID !== $order->get_payment_method() ) {
+ return;
+ }
+
+ // Only if the order is for a manual invoice order.
+ $model = new Model\MetaBox( $order );
+ $payment_status = $model->get_payment_status();
+ $payment_provider = $payment_status ? strtolower( $payment_status->getProvider() ) : '';
+
+ // Ensure the payment status was retrieved, is still pending, and the provider is one that supports manual invoices. Otherwise skip.
+ if ( empty( $payment_status ) || 'pending' !== $payment_status->getStatus() || ( ! str_contains( $payment_provider, 'walley' ) && ! str_contains( $payment_provider, 'klarna' ) ) ) {
+ return;
+ }
+
+ $gateway = Plugin::instance()->gateway();
+ $client = $gateway->get_client();
+ $response = $client->activateInvoice( $order->get_transaction_id() );
+ Plugin::instance()->gateway()->log( InvoiceActivationResponse::class . " Successfully activated invoice for order $order_id with transaction id {$order->get_transaction_id()}: " . json_encode( $response ) );
+ } catch ( \Exception $e ) {
+ $message = $e->getMessage();
+ $gateway->log( "Failed to send manual invoice for order $order_id with transaction id {$order->get_transaction_id()}: $message", 'error' );
+ $order->set_status( 'on-hold', __( 'Failed to activate manual invoice: ' . $message, 'paytrail-for-woocommerce' ) );
+ $order->save();
+ return;
+ }
+ }
+}
diff --git a/src/Gateway.php b/src/Gateway.php
index b4f47419..6adb4f7f 100644
--- a/src/Gateway.php
+++ b/src/Gateway.php
@@ -20,9 +20,7 @@
use Paytrail\SDK\Request\RefundRequest;
use Paytrail\SDK\Client;
use Paytrail\SDK\Request\EmailRefundRequest;
-use Paytrail\SDK\Model\Provider;
use Paytrail\SDK\Response\GetTokenResponse;
-use Paytrail\SDK\Response\InvoiceActivationResponse;
use Paytrail\WooCommercePaymentGateway\Model\PaymentSubscriptionMigration;
use Paytrail\WooCommercePaymentGateway\Model\PaymentTokenMigration;
use Paytrail\WooCommercePaymentGateway\Providers\OPLasku;
@@ -58,8 +56,6 @@ final class Gateway extends \WC_Payment_Gateway {
/**
* Transaction settlement declaration
- *
- *
*/
protected $transaction_settlement_enable;
@@ -70,6 +66,7 @@ final class Gateway extends \WC_Payment_Gateway {
*/
public $enable_test_mode = false;
+
/**
* Whether the debug mode is enabled.
*
@@ -77,14 +74,19 @@ final class Gateway extends \WC_Payment_Gateway {
*/
public $debug = false;
- public $callbackMode = false;
+ /**
+ * Whether we are in callback mode.
+ *
+ * @var boolean
+ */
+ public $callback_mode = false;
/**
* Supported features.
*
* @var array
*/
- public $supports = [
+ public $supports = array(
'products',
'refunds',
'tokenization',
@@ -97,15 +99,15 @@ final class Gateway extends \WC_Payment_Gateway {
'subscription_payment_method_change',
'subscription_payment_method_change_customer',
'subscription_payment_method_change_admin',
- 'multiple_subscriptions'
- ];
+ 'multiple_subscriptions',
+ );
/**
* Dynamic method info that will be populated from an endpoint.
*
* @var array
*/
- public $method_info = [];
+ public $method_info = array();
/**
* WooCommerce logger instance
@@ -127,14 +129,22 @@ final class Gateway extends \WC_Payment_Gateway {
* @var Helper
*/
protected $helper = null;
- const TAX_RATE_PRECISION = 1;
- const SUPPORTED_CURRENCIES = ['EUR'];
+
+ /**
+ * Settlement prefix
+ *
+ * @var int
+ */
+ private $settlement_prefix = 10;
+
+ const TAX_RATE_PRECISION = 1;
+ const SUPPORTED_CURRENCIES = array( 'EUR' );
/**
* Object constructor
*/
- public function __construct( $params = []) {
- // Set payment gateway ID
+ public function __construct() {
+ // Set payment gateway ID.
$this->id = Plugin::GATEWAY_ID;
$this->has_fields = $this->use_provider_selection();
@@ -147,8 +157,8 @@ public function __construct( $params = []) {
$this->method_description = $this->method_info['description'];
// These strings may show in the frontend.
- $this->title = !empty($this->get_option('custom_provider_name')) ? $this->get_option('custom_provider_name') : $this->method_info['title'];
- $this->description = !empty($this->get_option('custom_provider_description')) ? $this->get_option('custom_provider_description') : $this->method_info['description'];
+ $this->title = ! empty( $this->get_option( 'custom_provider_name' ) ) ? $this->get_option( 'custom_provider_name' ) : $this->method_info['title'];
+ $this->description = ! empty( $this->get_option( 'custom_provider_description' ) ) ? $this->get_option( 'custom_provider_description' ) : $this->method_info['description'];
// Icon temporarily disabled for size issues
// $this->icon = Plugin::ICON_URL;
@@ -160,50 +170,56 @@ public function __construct( $params = []) {
$this->init_settings();
// Whether we are in test mode or not.
- $this->enable_test_mode = 'yes' === $this->get_option('enable_test_mode', 'no');
+ $this->enable_test_mode = wc_string_to_bool( $this->get_option( 'enable_test_mode', 'no' ) );
// Set merchant ID and secret key either from the options or for test mode.
- if ($this->enable_test_mode) {
+ if ( $this->enable_test_mode ) {
$this->merchant_id = (int) Plugin::TEST_MERCHANT_ID;
$this->secret_key = Plugin::TEST_SECRET_KEY;
} else {
- $this->merchant_id = (int) $this->get_option('merchant_id');
- $this->secret_key = $this->get_option('secret_key');
+ $this->merchant_id = (int) $this->get_option( 'merchant_id' );
+ $this->secret_key = $this->get_option( 'secret_key' );
}
- $platformName = 'paytrail-for-woocommerce-' . \Paytrail\WooCommercePaymentGateway\Plugin::$version;
+ $platform_name = 'paytrail-for-woocommerce-' . \Paytrail\WooCommercePaymentGateway\Plugin::$version;
- // Create SDK client instance
+ // Create SDK client instance.
$this->client = new Client(
$this->merchant_id,
$this->secret_key,
- $platformName
+ $platform_name
);
- // Create Helper instance
+ // Create Helper instance.
$this->helper = new Helper();
// Whether we are in debug mode or not.
- $this->debug = 'yes' === $this->get_option('debug', 'no');
+ $this->debug = wc_string_to_bool( $this->get_option( 'debug', 'no' ) );
- // Check if transaction settlement is enabled
- $this->transaction_settlement_enable = $this->get_option( 'settlement_enablement', 'no' ) === 'yes';
+ // Check if transaction settlement is enabled.
+ $this->transaction_settlement_enable = wc_string_to_bool( $this->get_option( 'settlement_enablement', 'no' ) );
- if (!empty($params) && isset($params['callbackMode'])) {
- $this->callbackMode = true;
- }
+ $this->settlement_prefix = $this->get_option( 'settlement_prefix', '10' );
// Add actions and filters.
$this->add_actions();
- // Register stylesheet for payment fields
+ // Register stylesheet for payment fields.
$this->register_styles();
- // Register scripts for payment fields
+ // Register scripts for payment fields.
$this->register_scripts();
- // Check if we are in response phase
- $this->check_paytrail_response();
+ new Controllers\MetaBox();
+ }
+
+ /**
+ * Get Paytrail SDK Client instance.
+ *
+ * @return Client
+ */
+ public function get_client() {
+ return $this->client;
}
/**
@@ -212,41 +228,72 @@ public function __construct( $params = []) {
* @return void
*/
protected function add_actions() {
- add_action('woocommerce_update_options_payment_gateways_' . $this->id, [ $this, 'process_admin_options' ]);
- add_action('woocommerce_scheduled_subscription_payment_' . Plugin::GATEWAY_ID, [ $this, 'scheduled_subscription_payment' ], 10, 2);
- add_action('woocommerce_receipt_' . $this->id, [ $this, 'receipt_page' ]);
- add_filter('woocommerce_admin_order_items_after_refunds', [ $this, 'refund_items' ], 10, 1);
- add_filter('woocommerce_order_data_store_cpt_get_orders_query', [ $this, 'handle_custom_searches' ], 10, 2);
- add_filter('woocommerce_payment_gateway_get_saved_payment_method_option_html', [ $this, 'get_token_payment_option_html' ], 10, 2);
- add_action('admin_footer', [$this, 'display_user_data_form']);
- add_action('admin_notices', [$this, 'admin_notices']);
- add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
- add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_styles']);
+ add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
+ add_action( 'woocommerce_scheduled_subscription_payment_' . Plugin::GATEWAY_ID, array( $this, 'scheduled_subscription_payment' ), 10, 2 );
+ add_action( 'woocommerce_receipt_' . $this->id, array( $this, 'receipt_page' ) );
+ add_filter( 'woocommerce_admin_order_items_after_refunds', array( $this, 'refund_items' ), 10, 1 );
+ add_filter( 'woocommerce_order_data_store_cpt_get_orders_query', array( $this, 'handle_custom_searches' ), 10, 2 );
+ add_filter( 'woocommerce_payment_gateway_get_saved_payment_method_option_html', array( $this, 'get_token_payment_option_html' ), 10, 2 );
+ add_action( 'admin_footer', array( $this, 'display_user_data_form' ) );
+ add_action( 'admin_notices', array( $this, 'admin_notices' ) );
+ add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
+ add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );
+
+ // Check if we are in response phase.
+ add_action( 'template_redirect', array( $this, 'on_redirect_to_thankyou_page' ) );
+ }
+
+ /**
+ * Set callback mode
+ *
+ * @param boolean $mode Callback mode.
+ */
+ public function set_callback_mode( $mode ) {
+ $this->callback_mode = $mode;
+ }
+
+ /**
+ * Process Paytrail order on redirect to thankyou-page.
+ *
+ * @return void
+ */
+ public function on_redirect_to_thankyou_page() {
+ $order_id = absint( get_query_var( 'order-received', 0 ) );
+ $order = wc_get_order( $order_id );
+ if ( empty( $order ) ) {
+ return;
+ }
+
+ $order_key = filter_input( INPUT_GET, 'key', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
+ if ( empty( $order_key ) || ! hash_equals( $order->get_order_key(), $order_key ) ) {
+ return;
+ }
+ $this->check_paytrail_response();
}
/**
* Display the user_data_form as an overlay
*/
public function display_user_data_form() {
- $merchant_id = $this->get_option('merchant_id');
- $test_mode_enabled = $this->get_option('enable_test_mode', 'no') === 'yes';
- $current_screen = get_current_screen();
+ $merchant_id = $this->get_option( 'merchant_id' );
+ $test_mode_enabled = $this->get_option( 'enable_test_mode', 'no' ) === 'yes';
+ $current_screen = get_current_screen();
$is_paytrail_settings_page = (
- !$test_mode_enabled &&
+ ! $test_mode_enabled &&
$current_screen && 'woocommerce_page_wc-settings' === $current_screen->id &&
- isset($_GET['tab']) && 'checkout' === $_GET['tab'] &&
- isset($_GET['section']) && 'paytrail' === $_GET['section']
+ isset( $_GET['tab'] ) && 'checkout' === $_GET['tab'] &&
+ isset( $_GET['section'] ) && 'paytrail' === $_GET['section']
);
// Check if merchant_id is already submitted
- if (!empty($merchant_id) || $this->get_option('enable_test_mode', 'no') === 'yes') {
+ if ( ! empty( $merchant_id ) || $this->get_option( 'enable_test_mode', 'no' ) === 'yes' ) {
return;
}
- if ($is_paytrail_settings_page) {
- $template_path = plugin_dir_path(__FILE__) . 'View/Intro-form.php';
- if (file_exists($template_path)) {
+ if ( $is_paytrail_settings_page ) {
+ $template_path = plugin_dir_path( __FILE__ ) . 'View/Intro-form.php';
+ if ( file_exists( $template_path ) ) {
include_once $template_path;
}
}
@@ -258,33 +305,32 @@ public function display_user_data_form() {
*/
public function user_data_form() {
$current_user = wp_get_current_user();
- $user_email = $current_user->user_email;
- $first_name = $current_user->first_name;
- $last_name = $current_user->last_name;
+ $user_email = $current_user->user_email;
+ $first_name = $current_user->first_name;
+ $last_name = $current_user->last_name;
- if (class_exists('WooCommerce')) {
- $wc_billing_data = get_user_meta($current_user->ID, 'billing', true);
- $company_name = isset($wc_billing_data['company']) ? $wc_billing_data['company'] : '';
- $phone_number = isset($wc_billing_data['phone']) ? $wc_billing_data['phone'] : '';
+ if ( class_exists( 'WooCommerce' ) ) {
+ $wc_billing_data = get_user_meta( $current_user->ID, 'billing', true );
+ $company_name = isset( $wc_billing_data['company'] ) ? $wc_billing_data['company'] : '';
+ $phone_number = isset( $wc_billing_data['phone'] ) ? $wc_billing_data['phone'] : '';
// Fetch shop's address using WC_Countries
- $wc_countries = WC()->countries;
- $shop_address = $wc_countries->get_base_address();
- $shop_city = $wc_countries->get_base_city();
+ $wc_countries = WC()->countries;
+ $shop_address = $wc_countries->get_base_address();
+ $shop_city = $wc_countries->get_base_city();
$shop_postcode = $wc_countries->get_base_postcode();
} else {
- $company_name = '';
- $phone_number = '';
- $shop_address = '';
- $shop_city = '';
+ $company_name = '';
+ $phone_number = '';
+ $shop_address = '';
+ $shop_city = '';
$shop_postcode = '';
}
+ $site_url = esc_url( get_site_url() );
- $site_url = esc_url(get_site_url());
-
- $template_path = plugin_dir_path(__FILE__) . 'View/User-data-form.php';
- if (file_exists($template_path)) {
+ $template_path = plugin_dir_path( __FILE__ ) . 'View/User-data-form.php';
+ if ( file_exists( $template_path ) ) {
include_once $template_path;
}
}
@@ -296,11 +342,11 @@ public function user_data_form() {
* @return array
*/
protected function get_method_info() {
- $method_info = [
- 'title' => __('Paytrail for WooCommerce', 'paytrail-for-woocommerce'),
- 'description' => __('Paytrail for WooCommerce - the most comprehensive suite of payment methods in the market with a single contract', 'paytrail-for-woocommerce'),
- 'save_card' => 1,
- ];
+ $method_info = array(
+ 'title' => __( 'Paytrail for WooCommerce', 'paytrail-for-woocommerce' ),
+ 'description' => __( 'Paytrail for WooCommerce - the most comprehensive suite of payment methods in the market with a single contract', 'paytrail-for-woocommerce' ),
+ 'save_card' => 1,
+ );
return $method_info;
}
@@ -310,131 +356,138 @@ protected function get_method_info() {
* @return void
*/
protected function set_form_fields() {
- $test_mode_enabled = $this->get_option('enable_test_mode', 'no') === 'yes';
- $merchant_id_disabled = $this->get_option( 'enable_test_mode', 'no' ) === 'yes';
- $secret_key_disabled = $this->get_option( 'enable_test_mode', 'no' ) === 'yes';
- $enable_test_mode_disabled = !$test_mode_enabled && (
- !empty($this->get_option('merchant_id')) ||
- !empty($this->get_option('secret_key'))
+ $test_mode_enabled = $this->get_option( 'enable_test_mode', 'no' ) === 'yes';
+ $merchant_id_disabled = $this->get_option( 'enable_test_mode', 'no' ) === 'yes';
+ $secret_key_disabled = $this->get_option( 'enable_test_mode', 'no' ) === 'yes';
+ $enable_test_mode_disabled = ! $test_mode_enabled && (
+ ! empty( $this->get_option( 'merchant_id' ) ) ||
+ ! empty( $this->get_option( 'secret_key' ) )
);
- $this->form_fields = [
+ $this->form_fields = array(
// Whether the payment gateway is enabled.
- 'enabled' => [
- 'title' => __('Payment gateway status', 'paytrail-for-woocommerce'),
+ 'enabled' => array(
+ 'title' => __( 'Payment gateway status', 'paytrail-for-woocommerce' ),
'type' => 'checkbox',
- 'label' => __('Enable Paytrail for WooCommerce', 'paytrail-for-woocommerce'),
+ 'label' => __( 'Enable Paytrail for WooCommerce', 'paytrail-for-woocommerce' ),
'default' => 'yes',
- ],
+ ),
// Credentials
- 'credentials_title' => [
- 'title' => __('Credentials', 'paytrail-for-woocommerce'),
- 'type' => 'title',
- ],
+ 'credentials_title' => array(
+ 'title' => __( 'Credentials', 'paytrail-for-woocommerce' ),
+ 'type' => 'title',
+ ),
// Paytrail credentials
- 'merchant_id' => [
- 'title' => __('Paytrail Merchant ID', 'paytrail-for-woocommerce'),
- 'type' => 'text',
- 'label' => __('Merchant ID', 'paytrail-for-woocommerce'),
- 'default' => '',
+ 'merchant_id' => array(
+ 'title' => __( 'Paytrail Merchant ID', 'paytrail-for-woocommerce' ),
+ 'type' => 'text',
+ 'label' => __( 'Merchant ID', 'paytrail-for-woocommerce' ),
+ 'default' => '',
'disabled' => $merchant_id_disabled, // Disable if enable_test_mode is checked
- ],
- 'secret_key' => [
- 'title' => __('Paytrail Secret key', 'paytrail-for-woocommerce'),
- 'type' => 'password',
- 'label' => __('Secret key', 'paytrail-for-woocommerce'),
- 'default' => '',
- 'description' => __('Credentials can be found in the merchant panel.', 'paytrail-for-woocommerce'),
- 'disabled' => $secret_key_disabled, // Disable if enable_test_mode is checked
- ],
+ ),
+ 'secret_key' => array(
+ 'title' => __( 'Paytrail Secret key', 'paytrail-for-woocommerce' ),
+ 'type' => 'password',
+ 'label' => __( 'Secret key', 'paytrail-for-woocommerce' ),
+ 'default' => '',
+ 'description' => __( 'Credentials can be found in the merchant panel.', 'paytrail-for-woocommerce' ),
+ 'disabled' => $secret_key_disabled, // Disable if enable_test_mode is checked
+ ),
// Whether test mode is enabled
- 'enable_test_mode' => [
- 'title' => __('Test mode', 'paytrail-for-woocommerce'),
+ 'enable_test_mode' => array(
+ 'title' => __( 'Test mode', 'paytrail-for-woocommerce' ),
'type' => 'checkbox',
- 'label' => __('Enable test mode', 'paytrail-for-woocommerce'),
+ 'label' => __( 'Enable test mode', 'paytrail-for-woocommerce' ),
'default' => 'no',
- 'description' => __('You can use test mode to simulate payments with Paytrail\'s test credentials. To enable test mode, please first clear the Credentials and save settings.', 'paytrail-for-woocommerce'),
+ 'description' => __( 'You can use test mode to simulate payments with Paytrail\'s test credentials. To enable test mode, please first clear the Credentials and save settings.', 'paytrail-for-woocommerce' ),
'disabled' => $enable_test_mode_disabled, // Disable the checkbox if merchant_id or secret_key has a value
- ],
+ ),
// General settings
- 'general_settings_title' => [
- 'title' => __('General settings', 'paytrail-for-woocommerce'),
- 'type' => 'title',
- ],
+ 'general_settings_title' => array(
+ 'title' => __( 'General settings', 'paytrail-for-woocommerce' ),
+ 'type' => 'title',
+ ),
// Whether to show the payment provider wall or choose the method in the store
- 'provider_selection' => [
- 'title' => __('Payment provider selection', 'paytrail-for-woocommerce'),
+ 'provider_selection' => array(
+ 'title' => __( 'Payment provider selection', 'paytrail-for-woocommerce' ),
'type' => 'checkbox',
- 'label' => __('Enable payment provider selection in the checkout page', 'paytrail-for-woocommerce'),
+ 'label' => __( 'Enable payment provider selection in the checkout page', 'paytrail-for-woocommerce' ),
'default' => 'yes',
- 'description' => __('Choose whether you want the payment provider selection to happen in the checkout page or in a separate page.', 'paytrail-for-woocommerce'),
- ],
+ 'description' => __( 'Choose whether you want the payment provider selection to happen in the checkout page or in a separate page.', 'paytrail-for-woocommerce' ),
+ ),
// Alternative text + description to show on the Checkout page
- 'custom_provider_name' => [
- 'title' => __('Payment provider title', 'paytrail-for-woocommerce'),
+ 'custom_provider_name' => array(
+ 'title' => __( 'Payment provider title', 'paytrail-for-woocommerce' ),
'type' => 'text',
- 'label' => __('Used on the Checkout page title', 'paytrail-for-woocommerce'),
+ 'label' => __( 'Used on the Checkout page title', 'paytrail-for-woocommerce' ),
'default' => 'Paytrail for WooCommerce',
- 'description' => __('This title is displayed on the Checkout page before the payment provider images.', 'paytrail-for-woocommerce')
- ],
- 'custom_provider_description' => [
- 'title' => __('Payment provider description', 'paytrail-for-woocommerce'),
+ 'description' => __( 'This title is displayed on the Checkout page before the payment provider images.', 'paytrail-for-woocommerce' ),
+ ),
+ 'custom_provider_description' => array(
+ 'title' => __( 'Payment provider description', 'paytrail-for-woocommerce' ),
'type' => 'text',
- 'label' => __('Used on the Checkout page title', 'paytrail-for-woocommerce'),
+ 'label' => __( 'Used on the Checkout page title', 'paytrail-for-woocommerce' ),
'default' => 'Paytrail for WooCommerce',
- 'description' => __('Depending on your theme, this description might be displayed on the Checkout page before the payment provider images.', 'paytrail-for-woocommerce')
- ],
+ 'description' => __( 'Depending on your theme, this description might be displayed on the Checkout page before the payment provider images.', 'paytrail-for-woocommerce' ),
+ ),
// OP Lasku
- 'op_lasku_calculator' => [
+ 'op_lasku_calculator' => array(
'title' => OPLasku::settings_title(),
'type' => 'checkbox',
- 'label' => __('Enable OP Lasku calculator', 'paytrail-for-woocommerce'),
+ 'label' => __( 'Enable OP Lasku calculator', 'paytrail-for-woocommerce' ),
'default' => 'no',
- 'description' => __('Display OP Lasku calculator on the product and cart page.', 'paytrail-for-woocommerce'),
- ],
+ 'description' => __( 'Display OP Lasku calculator on the product and cart page.', 'paytrail-for-woocommerce' ),
+ ),
// Advanced settings
- 'advanced_settings_title' => [
- 'title' => __('Advanced settings', 'paytrail-for-woocommerce'),
- 'type' => 'title',
- ],
- 'settlement_enablement' => [
- 'title' => __( 'Enable individual settlements', 'paytrail-for-woocommerce' ),
- 'type' => 'checkbox',
- 'default' => 'no',
+ 'advanced_settings_title' => array(
+ 'title' => __( 'Advanced settings', 'paytrail-for-woocommerce' ),
+ 'type' => 'title',
+ ),
+ 'manual_invoice_activation' => array(
+ 'title' => __( 'Manual invoice activation', 'paytrail-for-woocommerce' ),
+ 'label' => __( 'Enable manual invoice activation', 'paytrail-for-woocommerce' ),
+ 'type' => 'checkbox',
+ 'default' => 'no',
+ 'description' => __( 'For certain invoice payment methods (Walley/Klarna), you can activate the invoice at a later time, for example for pre-ordered products.
Activation window
Walley: Up to 90 days
Klarna: Up to 28 days', 'paytrail-for-woocommerce' ),
+ ),
+ 'settlement_enablement' => array(
+ 'title' => __( 'Enable individual settlements', 'paytrail-for-woocommerce' ),
+ 'type' => 'checkbox',
+ 'default' => 'no',
'description' => __( 'This setting is required only if you are using transaction-by-transaction settlements in Paytrail.', 'paytrail-for-woocommerce' ),
- ],
- 'settlement_prefix' => [
- 'title' => __( 'Bank reference prefix', 'paytrail-for-woocommerce' ),
- 'type' => 'text',
+ ),
+ 'settlement_prefix' => array(
+ 'title' => __( 'Bank reference prefix', 'paytrail-for-woocommerce' ),
+ 'type' => 'text',
'description' => __( 'Add Prefix', 'paytrail-for-woocommerce' ),
- 'default' => '10'
- ],
- 'fallback_country' => [
- 'title' => __('Default country', 'paytrail-for-woocommerce'),
- 'type' => 'select',
- 'label' => __('Fallback country', 'paytrail-for-woocommerce'),
- 'default' => '',
- 'description' => __('Select country to be used as fallback if no country specified in checkout.', 'paytrail-for-woocommerce'),
- 'options' => array_merge(['' => 'Select country'], WC()->countries->get_countries())
- ],
+ 'default' => '10',
+ ),
+ 'fallback_country' => array(
+ 'title' => __( 'Default country', 'paytrail-for-woocommerce' ),
+ 'type' => 'select',
+ 'label' => __( 'Fallback country', 'paytrail-for-woocommerce' ),
+ 'default' => '',
+ 'description' => __( 'Select country to be used as fallback if no country specified in checkout.', 'paytrail-for-woocommerce' ),
+ 'options' => array_merge( array( '' => 'Select country' ), WC()->countries->get_countries() ),
+ ),
// Whether debug mode is enabled
- 'debug' => [
- 'title' => __('Debug log', 'paytrail-for-woocommerce'),
+ 'debug' => array(
+ 'title' => __( 'Debug log', 'paytrail-for-woocommerce' ),
'type' => 'checkbox',
- 'label' => __('Enable logging', 'paytrail-for-woocommerce'),
+ 'label' => __( 'Enable logging', 'paytrail-for-woocommerce' ),
'default' => 'no',
// translators: %s: URL
- 'description' => sprintf(__('This enables logging all payment gateway events. The log will be written in %1$s. Recommended only for debugging purposes as this might save personal data. All logs can be viewed here: %2$s', 'paytrail-for-woocommerce'), '' . \WC_Log_Handler_File::get_log_file_path(Plugin::GATEWAY_ID) . '', 'Logs'),
- ],
+ 'description' => sprintf( __( 'This enables logging all payment gateway events. The log will be written in %1$s. Recommended only for debugging purposes as this might save personal data. All logs can be viewed here: %2$s', 'paytrail-for-woocommerce' ), '' . \WC_Log_Handler_File::get_log_file_path( Plugin::GATEWAY_ID ) . '', 'Logs' ),
+ ),
// Update tokens if enabled
- 'tokenize' => [
- 'title' => __('Update tokens', 'paytrail-for-woocommerce'),
+ 'tokenize' => array(
+ 'title' => __( 'Update tokens', 'paytrail-for-woocommerce' ),
'type' => 'checkbox',
- 'label' => __('Enable token update', 'paytrail-for-woocommerce'),
+ 'label' => __( 'Enable token update', 'paytrail-for-woocommerce' ),
'default' => 'no',
// translators: %s: URL
- 'description' => __('Choose this to update card information (tokens) from the old Checkout Finland for WooCommerce -plugin. The update is done upon saving settings. This will also update tokens for the current WooCommerce Subscriptions orders, if that module is in use. CAUTION: This action cannot be reverted.', 'paytrail-for-woocommerce'),
- ],
- ];
+ 'description' => __( 'Choose this to update card information (tokens) from the old Checkout Finland for WooCommerce -plugin. The update is done upon saving settings. This will also update tokens for the current WooCommerce Subscriptions orders, if that module is in use. CAUTION: This action cannot be reverted.', 'paytrail-for-woocommerce' ),
+ ),
+ );
}
/**
@@ -446,16 +499,16 @@ public function process_admin_options() {
$saved = parent::process_admin_options();
// Clear logs if debugging was disabled.
- if ('yes' !== $this->get_option('debug', 'no')) {
- if (empty($this->logger)) {
+ if ( 'yes' !== $this->get_option( 'debug', 'no' ) ) {
+ if ( empty( $this->logger ) ) {
$this->logger = wc_get_logger();
}
- $this->logger->clear(Plugin::GATEWAY_ID);
+ $this->logger->clear( Plugin::GATEWAY_ID );
}
// Update tokens if checkbx was checked
- if ('yes' === $this->get_option('tokenize', 'yes')) {
+ if ( 'yes' === $this->get_option( 'tokenize', 'yes' ) ) {
$token_migration = new PaymentTokenMigration();
$token_migration->execute();
$subscription_migration = new PaymentSubscriptionMigration();
@@ -470,19 +523,19 @@ public function process_admin_options() {
*/
public function display_test_mode_notice() {
// Check if test mode is enabled
- $test_mode_enabled = $this->get_option('enable_test_mode', 'no') === 'yes';
+ $test_mode_enabled = $this->get_option( 'enable_test_mode', 'no' ) === 'yes';
// Check if the notice should be displayed
- if ($test_mode_enabled) {
+ if ( $test_mode_enabled ) {
?>
' . esc_html__('here', 'paytrail-for-woocommerce') . ''
+ esc_html__( 'If you have not registered yet, you can do so on our website %s to get your credentials!', 'paytrail-for-woocommerce' ),
+ '' . esc_html__( 'here', 'paytrail-for-woocommerce' ) . ''
);
?>
@@ -498,20 +551,21 @@ public function display_test_mode_notice() {
*/
public function display_currency_notice() {
// Check the currently selected currency
- $current_currency = get_woocommerce_currency();
- $currency_is_not_supported = !in_array($current_currency, self::SUPPORTED_CURRENCIES);
+ $current_currency = get_woocommerce_currency();
+ $currency_is_not_supported = ! in_array( $current_currency, self::SUPPORTED_CURRENCIES );
// Check if the notice should be displayed
- if ($currency_is_not_supported) {
- $currency_settings_url = admin_url('admin.php?page=wc-settings&tab=general');
+ if ( $currency_is_not_supported ) {
+ $currency_settings_url = admin_url( 'admin.php?page=wc-settings&tab=general' );
?>
@@ -531,9 +585,9 @@ public function admin_notices() {
* Calculate bank reference
*/
private function calculate_reference( $base ) {
- $base = sprintf( '%s%s', $this->settlement_prefix, $base );
- $base = trim( str_replace( ' ', '', $base ) );
- $base = str_split( $base );
+ $base = sprintf( '%s%s', $this->settlement_prefix, $base );
+ $base = trim( str_replace( ' ', '', $base ) );
+ $base = str_split( $base );
$reversed_base = array_reverse( $base );
$weights = array( 7, 3, 1, 7, 3, 1, 7, 3, 1, 7, 3, 1, 7, 3, 1, 7, 3, 1, 7 );
@@ -541,7 +595,7 @@ private function calculate_reference( $base ) {
$sum = 0;
for ( $i = 0; $i < count( $reversed_base ); $i++ ) {
$coefficient = array_shift( $weights );
- $sum += intval( $reversed_base[$i] ) * $coefficient;
+ $sum += intval( $reversed_base[ $i ] ) * $coefficient;
}
$checksum = ( 0 == ( $sum % 10 ) ) ? 0 : ( 10 - ( $sum % 10 ) );
@@ -557,11 +611,11 @@ private function calculate_reference( $base ) {
* @return void
*/
public function receipt_page() {
- $view = new View('CheckoutForm');
+ $view = new View( 'CheckoutForm' );
- $provider = WC()->session->get('payment_provider');
+ $provider = WC()->session->get( 'payment_provider' );
- $view->render($provider);
+ $view->render( $provider );
}
/**
@@ -569,8 +623,8 @@ public function receipt_page() {
*
* @return void
*/
- public function render_saved_payment_methods() {
- $view = new View('SavedPaymentMethods');
+ public static function render_saved_payment_methods() {
+ $view = new View( 'SavedPaymentMethods' );
$view->render();
}
@@ -582,44 +636,44 @@ public function render_saved_payment_methods() {
* @throws HmacException
* @throws ValidationException
*/
- public function add_card_form( $context = Plugin::ADD_CARD_CONTEXT_CHECKOUT) {
- $datetime = new \DateTime();
- $checkout_nonce = sha1(uniqid(true));
+ public function add_card_form( $context = Plugin::ADD_CARD_CONTEXT_CHECKOUT ) {
+ $datetime = new \DateTime();
+ $checkout_nonce = sha1( uniqid( true ) );
- if (Plugin::ADD_CARD_CONTEXT_MY_ACCOUNT === $context) {
- $success_url = Router::get_url(Plugin::ADD_CARD_REDIRECT_SUCCESS_URL, Plugin::ADD_CARD_CONTEXT_MY_ACCOUNT);
- $cancel_url = Router::get_url(Plugin::ADD_CARD_REDIRECT_CANCEL_URL, Plugin::ADD_CARD_CONTEXT_MY_ACCOUNT);
- } elseif (Helper::getIsChangeSubscriptionPaymentMethod()) {
+ if ( Plugin::ADD_CARD_CONTEXT_MY_ACCOUNT === $context ) {
+ $success_url = Router::get_url( Plugin::ADD_CARD_REDIRECT_SUCCESS_URL, Plugin::ADD_CARD_CONTEXT_MY_ACCOUNT );
+ $cancel_url = Router::get_url( Plugin::ADD_CARD_REDIRECT_CANCEL_URL, Plugin::ADD_CARD_CONTEXT_MY_ACCOUNT );
+ } elseif ( Helper::getIsChangeSubscriptionPaymentMethod() ) {
$success_url = Router::get_url(
Plugin::ADD_CARD_REDIRECT_SUCCESS_URL,
Plugin::ADD_CARD_CONTEXT_CHANGE_PAYMENT_METHOD
);
- $cancel_url = Router::get_url(
+ $cancel_url = Router::get_url(
Plugin::ADD_CARD_REDIRECT_CANCEL_URL,
Plugin::ADD_CARD_CONTEXT_CHANGE_PAYMENT_METHOD
);
} else {
- $success_url = Router::get_url(Plugin::ADD_CARD_REDIRECT_SUCCESS_URL, Plugin::ADD_CARD_CONTEXT_CHECKOUT);
- $cancel_url = Router::get_url(Plugin::ADD_CARD_REDIRECT_CANCEL_URL, Plugin::ADD_CARD_CONTEXT_CHECKOUT);
+ $success_url = Router::get_url( Plugin::ADD_CARD_REDIRECT_SUCCESS_URL, Plugin::ADD_CARD_CONTEXT_CHECKOUT );
+ $cancel_url = Router::get_url( Plugin::ADD_CARD_REDIRECT_CANCEL_URL, Plugin::ADD_CARD_CONTEXT_CHECKOUT );
}
- $this->log('Paytrail: try to add new card', 'debug');
+ $this->log( 'Paytrail: try to add new card', 'debug' );
$add_card_form_request = new AddCardFormRequest();
- $add_card_form_request->setCheckoutAccount($this->merchant_id);
- $add_card_form_request->setCheckoutAlgorithm('sha256');
- $add_card_form_request->setCheckoutMethod('POST');
- $add_card_form_request->setCheckoutTimestamp($datetime->format('Y-m-d\TH:i:s.u\Z'));
- $add_card_form_request->setCheckoutNonce($checkout_nonce);
- $add_card_form_request->setCheckoutRedirectSuccessUrl($success_url);
- $add_card_form_request->setCheckoutRedirectCancelUrl($cancel_url);
- $add_card_form_request->setLanguage(Helper::getLocale());
+ $add_card_form_request->setCheckoutAccount( $this->merchant_id );
+ $add_card_form_request->setCheckoutAlgorithm( 'sha256' );
+ $add_card_form_request->setCheckoutMethod( 'POST' );
+ $add_card_form_request->setCheckoutTimestamp( $datetime->format( 'Y-m-d\TH:i:s.u\Z' ) );
+ $add_card_form_request->setCheckoutNonce( $checkout_nonce );
+ $add_card_form_request->setCheckoutRedirectSuccessUrl( $success_url );
+ $add_card_form_request->setCheckoutRedirectCancelUrl( $cancel_url );
+ $add_card_form_request->setLanguage( Helper::getLocale() );
// Create a addCardFormRequest via Paytrail SDK
// @var \GuzzleHttp\Psr7\Response $response
- $response = $this->client->createAddCardFormRequest($add_card_form_request);
+ $response = $this->client->createAddCardFormRequest( $add_card_form_request );
- if ($response->getHeader('Location')) {
- wp_redirect($response->getHeader('Location')[0]);
+ if ( $response->getHeader( 'Location' ) ) {
+ wp_redirect( $response->getHeader( 'Location' )[0] );
exit;
}
}
@@ -633,12 +687,12 @@ public function add_card_form( $context = Plugin::ADD_CARD_CONTEXT_CHECKOUT) {
*/
public function process_card_token() {
$getTokenRequest = new GetTokenRequest();
- $getTokenRequest->setCheckoutTokenizationId(filter_input(INPUT_GET, 'checkout-tokenization-id'));
- $this->log('Paytrail: process_card_token', 'debug');
+ $getTokenRequest->setCheckoutTokenizationId( filter_input( INPUT_GET, 'checkout-tokenization-id' ) );
+ $this->log( 'Paytrail: process_card_token', 'debug' );
- $response = $this->client->createGetTokenRequest($getTokenRequest);
+ $response = $this->client->createGetTokenRequest( $getTokenRequest );
- return (bool) $this->save_card_token($response);
+ return (bool) $this->save_card_token( $response );
}
/**
@@ -646,18 +700,18 @@ public function process_card_token() {
*
* @param GetTokenResponse $card_token
*/
- private function save_card_token( GetTokenResponse $card_token) {
- $this->log('Paytrail: save_card_token', 'debug');
+ private function save_card_token( GetTokenResponse $card_token ) {
+ $this->log( 'Paytrail: save_card_token', 'debug' );
$token = new WC_Payment_Token_CC();
- $token->set_card_type($card_token->getCard()->getType());
- $token->set_expiry_month($card_token->getCard()->getExpireMonth());
- $token->set_expiry_year($card_token->getCard()->getExpireYear());
- $token->set_last4($card_token->getCard()->getPartialPan());
- $token->set_token($card_token->getToken());
- $token->set_user_id(get_current_user_id());
- $token->set_gateway_id(Plugin::GATEWAY_ID);
- \WC_Payment_Tokens::set_users_default(get_current_user_id(), $token->get_id());
+ $token->set_card_type( $card_token->getCard()->getType() );
+ $token->set_expiry_month( $card_token->getCard()->getExpireMonth() );
+ $token->set_expiry_year( $card_token->getCard()->getExpireYear() );
+ $token->set_last4( $card_token->getCard()->getPartialPan() );
+ $token->set_token( $card_token->getToken() );
+ $token->set_user_id( get_current_user_id() );
+ $token->set_gateway_id( Plugin::GATEWAY_ID );
+ \WC_Payment_Tokens::set_users_default( get_current_user_id(), $token->get_id() );
return $token->save();
}
@@ -670,11 +724,11 @@ private function save_card_token( GetTokenResponse $card_token) {
* @throws ValidationException
*/
public function add_payment_method() {
- $this->add_card_form(Plugin::ADD_CARD_CONTEXT_MY_ACCOUNT);
+ $this->add_card_form( Plugin::ADD_CARD_CONTEXT_MY_ACCOUNT );
return array(
- 'result' => 'success',
- 'redirect' => wc_get_endpoint_url('payment-methods'),
+ 'result' => 'success',
+ 'redirect' => wc_get_endpoint_url( 'payment-methods' ),
);
}
@@ -682,33 +736,33 @@ public function add_payment_method() {
* Grab and display users saved card payment methods.
*/
public function saved_payment_methods() {
- $html = '
';
- foreach ($this->get_tokens() as $token) {
- $html .= $this->get_saved_payment_method_option_html($token);
+ $html = '';
+ foreach ( $this->get_tokens() as $token ) {
+ $html .= $this->get_saved_payment_method_option_html( $token );
}
$html .= '
';
- $kses_arr = [
- 'li' => ['class' => []],
- 'label' => ['for' => []],
- 'input' => [
- 'id' => [],
- 'type' => [],
- 'name' => [],
- 'value'=> [],
- 'class' => []
- ],
- 'div' => ['class' => []],
- 'ul' => ['class' => []]
- ];
+ $kses_arr = array(
+ 'li' => array( 'class' => array() ),
+ 'label' => array( 'for' => array() ),
+ 'input' => array(
+ 'id' => array(),
+ 'type' => array(),
+ 'name' => array(),
+ 'value' => array(),
+ 'class' => array(),
+ ),
+ 'div' => array( 'class' => array() ),
+ 'ul' => array( 'class' => array() ),
+ );
/**
* Show payment methods
*
* @since 1.0
*/
- echo wp_kses(apply_filters('wc_payment_gateway_form_saved_payment_methods_html', $html, $this), $kses_arr);
+ echo wp_kses( apply_filters( 'wc_payment_gateway_form_saved_payment_methods_html', $html, $this ), $kses_arr );
}
/**
@@ -718,9 +772,8 @@ public function saved_payment_methods() {
* @param $token
* @return string
*/
- public function get_token_payment_option_html( $html, $token) {
- if (Plugin::GATEWAY_ID !== $token->get_gateway_id()) {
- error_log('Not the expected gateway ID. Returning original HTML.');
+ public function get_token_payment_option_html( $html, $token ) {
+ if ( Plugin::GATEWAY_ID !== $token->get_gateway_id() ) {
return $html;
}
$html = sprintf(
@@ -730,12 +783,12 @@ public function get_token_payment_option_html( $html, $token) {
%5$s%3$s
',
- esc_attr($this->id),
- esc_attr($token->get_id()),
- $this->get_display_name($token),
- esc_html($token->get_display_name()),
- $this->get_card_image($token),
- checked($token->is_default(), true, false)
+ esc_attr( $this->id ),
+ esc_attr( $token->get_id() ),
+ $this->get_display_name( $token ),
+ esc_html( $token->get_display_name() ),
+ $this->get_card_image( $token ),
+ checked( $token->is_default(), true, false )
);
return $html;
@@ -747,13 +800,13 @@ public function get_token_payment_option_html( $html, $token) {
* @param $token
* @return string
*/
- private function get_display_name( $token) {
+ private function get_display_name( $token ) {
$display = sprintf(
/* translators: 1: last 4 digits 2: expiry month 3: expiry year */
- __('xxxx xxxx xxxx %1$s %2$s/%3$s', 'paytrail-for-woocommerce'),
+ __( 'xxxx xxxx xxxx %1$s %2$s/%3$s', 'paytrail-for-woocommerce' ),
$token->get_last4(),
'' . $token->get_expiry_month(),
- substr($token->get_expiry_year(), 2) . ''
+ substr( $token->get_expiry_year(), 2 ) . ''
);
return $display;
@@ -765,16 +818,16 @@ private function get_display_name( $token) {
* @param $token
* @return string
*/
- private function get_card_image( $token) {
- $token_card_type = strtolower($token->get_card_type());
+ private function get_card_image( $token ) {
+ $token_card_type = strtolower( $token->get_card_type() );
- if ('amex' === $token_card_type) {
+ if ( 'amex' === $token_card_type ) {
$token_card_type = 'american-express';
}
$html = sprintf(
'
',
- esc_html(preg_replace('/[[:space:]]+/', '-', $token_card_type))
+ esc_html( preg_replace( '/[[:space:]]+/', '-', $token_card_type ) )
);
return $html;
@@ -786,78 +839,78 @@ private function get_card_image( $token) {
* @return void
*/
public function check_paytrail_response() {
- $status = filter_input(INPUT_GET, 'checkout-status');
- $refund_callback = filter_input(INPUT_GET, 'refund_callback');
- $refund_unique_id = filter_input(INPUT_GET, 'refund_unique_id');
- $order_id = filter_input(INPUT_GET, 'order_id');
- $reference = filter_input(INPUT_GET, 'checkout-reference');
- $cancel_order = filter_input(INPUT_GET, 'cancel_order');
- $pay_for_order = filter_input(INPUT_GET, 'pay_for_order');
- $payment_method = filter_input(INPUT_POST, 'payment_method');
-
- if (!$status && !$reference && !$refund_callback && !$refund_unique_id) {
- //no log to reduce number of log entries
+ $status = filter_input( INPUT_GET, 'checkout-status' );
+ $refund_callback = filter_input( INPUT_GET, 'refund_callback' );
+ $refund_unique_id = filter_input( INPUT_GET, 'refund_unique_id' );
+ $order_id = filter_input( INPUT_GET, 'order_id' );
+ $reference = filter_input( INPUT_GET, 'checkout-reference' );
+ $cancel_order = filter_input( INPUT_GET, 'cancel_order' );
+ $pay_for_order = filter_input( INPUT_GET, 'pay_for_order' );
+ $payment_method = filter_input( INPUT_POST, 'payment_method' );
+
+ if ( ! $status && ! $reference && ! $refund_callback && ! $refund_unique_id ) {
+ // no log to reduce number of log entries
return;
}
- if (!$reference && $status && !$refund_callback && !$refund_unique_id) {
- $this->log('Paytrail: check_paytrail_response, no reference found for status: ' . $status, 'debug');
+ if ( ! $reference && $status && ! $refund_callback && ! $refund_unique_id ) {
+ $this->log( 'Paytrail: check_paytrail_response, no reference found for status: ' . $status, 'debug' );
return;
}
- if (!$status && $reference && !$refund_callback && !$refund_unique_id) {
- $this->log('Paytrail: check_paytrail_response, no status found for reference ' . $reference, 'debug');
+ if ( ! $status && $reference && ! $refund_callback && ! $refund_unique_id ) {
+ $this->log( 'Paytrail: check_paytrail_response, no status found for reference ' . $reference, 'debug' );
return;
}
- if ($cancel_order) {
- //Do not attempt to process further. Woo Commerce will cancel the order
- $this->log('Paytrail: check_paytrail_response, cancel_order is true. Order will be cancelled. Reference: ' . $reference, 'debug');
+ if ( $cancel_order ) {
+ // Do not attempt to process further. Woo Commerce will cancel the order
+ $this->log( 'Paytrail: check_paytrail_response, cancel_order is true. Order will be cancelled. Reference: ' . $reference, 'debug' );
return;
}
- if ($pay_for_order) {
- //The customer will be shown a page to choose payment methods
+ if ( $pay_for_order ) {
+ // The customer will be shown a page to choose payment methods
wc_clear_notices();
$message = __(
'Payment failed or was cancelled. Please try again',
'paytrail-for-woocommerce'
);
- wc_add_notice( $message, 'notice');
- $this->log('Paytrail: check_paytrail_response, pay_for_order is true. Payment page will be shown. Reference: ' . $reference, 'debug');
+ wc_add_notice( $message, 'notice' );
+ $this->log( 'Paytrail: check_paytrail_response, pay_for_order is true. Payment page will be shown. Reference: ' . $reference, 'debug' );
- //Check to see if this is the first load of the page
- if (!$payment_method) {
- //Handle the payment response so that orders will change to Failed status
- $this->log('Paytrail: Start handle_payment_response for reference ' . $reference, 'debug');
+ // Check to see if this is the first load of the page
+ if ( ! $payment_method ) {
+ // Handle the payment response so that orders will change to Failed status
+ $this->log( 'Paytrail: Start handle_payment_response for reference ' . $reference, 'debug' );
$this->handle_payment_response( $status );
}
return;
}
- $sleepTime = rand(0, 3);
- $sleepTimeCallback = rand(3, 6);
+ $sleepTime = wp_rand( 0, 3 );
+ $sleepTimeCallback = wp_rand( 3, 6 );
- if (true === $this->callbackMode) {
- $this->log('Paytrail: Callback check_paytrail_response for order ' . $reference, 'debug');
- $this->log('Paytrail: Wait for ' . $sleepTimeCallback . ' seconds until processing order ' . $reference, 'debug');
- sleep($sleepTimeCallback);
+ if ( true === $this->callback_mode ) {
+ $this->log( 'Paytrail: Callback check_paytrail_response for order ' . $reference, 'debug' );
+ $this->log( 'Paytrail: Wait for ' . $sleepTimeCallback . ' seconds until processing order ' . $reference, 'debug' );
+ sleep( $sleepTimeCallback );
} else {
- $this->log('Paytrail: Redirect check_paytrail_response for reference ' . $reference, 'debug');
- $this->log('Paytrail: Wait for ' . $sleepTime . ' seconds until processing reference ' . $reference, 'debug');
- sleep($sleepTime);
+ $this->log( 'Paytrail: Redirect check_paytrail_response for reference ' . $reference, 'debug' );
+ $this->log( 'Paytrail: Wait for ' . $sleepTime . ' seconds until processing reference ' . $reference, 'debug' );
+ sleep( $sleepTime );
}
// Handle the response only if the status exists.
- if ($refund_callback) {
- $this->log('Paytrail: Start handle_refund_response for order_id ' . $order_id, 'debug');
- $this->handle_refund_response($refund_callback, $refund_unique_id, $order_id);
+ if ( $refund_callback ) {
+ $this->log( 'Paytrail: Start handle_refund_response for order_id ' . $order_id, 'debug' );
+ $this->handle_refund_response( $refund_callback, $refund_unique_id, $order_id );
} else {
- $this->log('Paytrail: Start handle_payment_response for reference ' . $reference, 'debug');
- $this->handle_payment_response($status);
+ $this->log( 'Paytrail: Start handle_payment_response for reference ' . $reference, 'debug' );
+ $this->handle_payment_response( $status );
}
}
@@ -866,127 +919,129 @@ public function check_paytrail_response() {
*
* @param string $status The status of the response.
*
- * @return void
+ * @return bool|null
*/
- public function handle_payment_response( $status) {
- // Check the HMAC
+ public function handle_payment_response( $status ) {
+ // Check the HMAC.
try {
- $this->client->validateHmac(filter_input_array(INPUT_GET), '', filter_input(INPUT_GET, 'signature'));
- } catch (HmacException $exception) {
- $this->signature_error($exception);
+ $this->client->validateHmac( filter_input_array( INPUT_GET ), '', filter_input( INPUT_GET, 'signature' ) );
+ } catch ( HmacException $exception ) {
+ $this->signature_error( $exception );
}
- $reference = filter_input(INPUT_GET, 'checkout-reference');
- $transaction_id = filter_input(INPUT_GET, 'checkout-transaction-id');
+ $reference = filter_input( INPUT_GET, 'checkout-reference' );
+ $transaction_id = filter_input( INPUT_GET, 'checkout-transaction-id' );
try {
- $order_query = new WC_Order_Query([
- 'limit' => 1,
- 'meta_key' => '_checkout_reference',
- 'meta_value' => $reference,
- ]);
-
- $orders = $order_query->get_orders();
+ $orders = wc_get_orders(
+ array(
+ 'limit' => 1,
+ 'meta_key' => '_checkout_reference',
+ 'meta_value' => $reference,
+ )
+ );
- if (empty($orders)) {
- $this->log('Paytrail: handle_payment_response, orders collection empty for reference: ' . $reference, 'debug');
+ if ( empty( $orders ) ) {
+ $this->log( 'Paytrail: handle_payment_response, orders collection empty for reference: ' . $reference, 'debug' );
return;
}
- $order = $orders[0];
- } catch (\Exception $e) {
- $this->log('Paytrail: order_query, failed for reference: ' . $reference, 'debug');
+ $order = reset( $orders );
+ if ( $order->get_meta( '_checkout_reference' ) !== $reference ) {
+ $this->log( "Paytrail: handle_payment_response, reference mismatch for order {$order->get_id()} and reference: {$reference}", 'debug' );
+ return false;
+ }
+ } catch ( \Exception $e ) {
+ $this->log( "Paytrail: orders query, failed for reference: $reference", 'debug' );
return false;
}
try {
- $transaction_query = new WC_Order_Query( [
- 'transaction_id' => $transaction_id,
- ] );
+ $transaction_query = new WC_Order_Query(
+ array(
+ 'transaction_id' => $transaction_id,
+ )
+ );
$existing_orders = $transaction_query->get_orders();
- // Cross-check if any other order already has this transaction ID
- foreach ($existing_orders as $existing_order) {
+ // Cross-check if any other order already has this transaction ID.
+ foreach ( $existing_orders as $existing_order ) {
$existing_transaction_id = $existing_order->get_transaction_id();
- if (empty($existing_transaction_id)) {
- $this->log('Paytrail: Order ID ' . $existing_order->get_id() . ' has an empty transaction ID. Aborting processing.', 'debug');
+ if ( empty( $existing_transaction_id ) ) {
+ $this->log( 'Paytrail: Order ID ' . $existing_order->get_id() . ' has an empty transaction ID. Aborting processing.', 'debug' );
return false;
}
- if ($existing_order->get_id() !== $order->get_id()) {
- $this->log('Paytrail: Duplicate transaction ID ' . $transaction_id . ' detected. Already associated with order ' . $existing_order->get_id() . '.', 'debug');
+ if ( $existing_order->get_id() !== $order->get_id() ) {
+ $this->log( 'Paytrail: Duplicate transaction ID ' . $transaction_id . ' detected. Already associated with order ' . $existing_order->get_id() . '.', 'debug' );
return false;
}
}
-
- } catch (\Exception $e) {
- $this->log('Paytrail: transaction_query, failed for reference: ' . $reference, 'debug');
+ } catch ( \Exception $e ) {
+ $this->log( 'Paytrail: transaction_query, failed for reference: ' . $reference, 'debug' );
return false;
}
-
-
- // Store information that transaction-specific settlement was used
+ // Store information that transaction-specific settlement was used.
if ( $this->transaction_settlement_enable ) {
$order->update_meta_data( '_paytrail_ppa_transaction_settlement', true );
$order->save();
}
-
- switch ($status) {
+ switch ( $status ) {
case 'ok':
- $this->log('Paytrail: handle_payment_response, case = ok for order ' . $order->get_id(), 'debug');
- if (!$this->validate_order_payment_processing($order)) {
+ $this->log( 'Paytrail: handle_payment_response, case = ok for order ' . $order->get_id(), 'debug' );
+ if ( ! $this->validate_order_payment_processing( $order ) ) {
return;
}
- $this->log('Paytrail: handle_payment_response payment_complete, order ' . $order->get_id() . ' needs processing ' . $order->needs_processing(), 'debug');
+ $this->log( 'Paytrail: handle_payment_response payment_complete, order ' . $order->get_id() . ' needs processing ' . $order->needs_processing(), 'debug' );
- $transaction_id = filter_input(INPUT_GET, 'checkout-transaction-id');
+ $transaction_id = filter_input( INPUT_GET, 'checkout-transaction-id' );
- // If this transaction has already been processed, don't process again
- if ($order->get_transaction_id() === $transaction_id) {
- $this->log('Paytrail: handle_payment_response, transaction id ' . $transaction_id . ' already processed for order ' . $order->get_id(), 'debug');
+ // If this transaction has already been processed, don't process again.
+ if ( $order->get_transaction_id() === $transaction_id && ! empty( $order->get_date_paid() ) ) {
+ $this->log( 'Paytrail: handle_payment_response, transaction id ' . $transaction_id . ' already processed for order ' . $order->get_id(), 'debug' );
return false;
}
- // Save transient to avoid race condition between redirect and callback processing
- \set_transient('checkout_transaction_id_processing_' . $transaction_id, 'yes', 60);
+ // Save transient to avoid race condition between redirect and callback processing.
+ \set_transient( 'checkout_transaction_id_processing_' . $transaction_id, 'yes', 60 );
- if (! $this->use_provider_selection()) {
- $this->log('Paytrail: handle_payment_response, use_provider_selection = false for order ' . $order->get_id(), 'debug');
- // Get the chosen payment provider and save it to the order
- $payment_provider = filter_input(INPUT_GET, 'checkout-provider');
- $payment_amount = filter_input(INPUT_GET, 'checkout-amount');
+ if ( ! $this->use_provider_selection() ) {
+ $this->log( 'Paytrail: handle_payment_response, use_provider_selection = false for order ' . $order->get_id(), 'debug' );
+ // Get the chosen payment provider and save it to the order.
+ $payment_provider = filter_input( INPUT_GET, 'checkout-provider' );
+ $payment_amount = filter_input( INPUT_GET, 'checkout-amount' );
- $order->update_meta_data('_checkout_payment_provider', $payment_provider);
+ $order->update_meta_data( '_checkout_payment_provider', $payment_provider );
$order->save();
- $providers = $this->get_payment_providers($payment_amount);
+ $providers = $this->get_payment_providers( $payment_amount );
- if (! empty($providers['error'])) {
- $provider_name = ucfirst($payment_provider);
+ if ( ! empty( $providers['error'] ) ) {
+ $provider_name = ucfirst( $payment_provider );
} else {
- // Get only the wanted payment provider object
- $wanted_provider = $this->get_wanted_provider($providers, $payment_provider);
- if (null !== $wanted_provider) {
- $provider_name = !empty($wanted_provider->getName()) ? $wanted_provider->getName() : ucfirst($wanted_provider->getId());
+ // Get only the wanted payment provider object.
+ $wanted_provider = $this->get_wanted_provider( $providers, $payment_provider );
+ if ( null !== $wanted_provider ) {
+ $provider_name = ! empty( $wanted_provider->getName() ) ? $wanted_provider->getName() : ucfirst( $wanted_provider->getId() );
} else {
- $provider_name = ucfirst($payment_provider);
+ $provider_name = ucfirst( $payment_provider );
}
}
- WC()->session->set('payment_provider', $wanted_provider);
+ WC()->session->set( 'payment_provider', $wanted_provider );
$message = sprintf(
// translators: First parameter is transaction ID, the other is the name of the payment provider.
- __('Payment completed with transaction ID %1$s and payment provider %2$s.', 'paytrail-for-woocommerce'),
+ __( 'Payment completed with transaction ID %1$s and payment provider %2$s.', 'paytrail-for-woocommerce' ),
$transaction_id,
$provider_name
);
- $this->log('Paytrail: handle_payment_response, use_provider_selection = false, add_order_note', 'debug');
+ $this->log( 'Paytrail: handle_payment_response, use_provider_selection = false, add_order_note', 'debug' );
- $order->add_order_note($message);
+ $order->add_order_note( $message );
} else {
$order_note = sprintf(
// Translators: The placeholder is a transaction ID.
@@ -996,51 +1051,55 @@ public function handle_payment_response( $status) {
),
$transaction_id
);
- $this->log('Paytrail: handle_payment_response, use_provider_selection = true, add_order_note', 'debug');
+ $this->log( 'Paytrail: handle_payment_response, use_provider_selection = true, add_order_note', 'debug' );
- $order->add_order_note($order_note);
+ $order->add_order_note( $order_note );
}
// Mark payment completed and store the transaction ID.
- $order->payment_complete($transaction_id);
+ $order->payment_complete( $transaction_id );
// Clear the cart.
WC()->cart->empty_cart();
- // Delete transient
- \delete_transient('checkout_transaction_id_processing_' . $transaction_id);
+ // Delete transient.
+ \delete_transient( 'checkout_transaction_id_processing_' . $transaction_id );
break;
case 'pending':
- $this->log('Paytrail: handle_payment_response, case = pending', 'debug');
- if (!$this->validate_order_payment_process_status($order)) {
+ $transaction_id = filter_input( INPUT_GET, 'checkout-transaction-id' );
+ $this->log( 'Paytrail: handle_payment_response, case = pending', 'debug' );
+ if ( ! $this->validate_order_payment_process_status( $order ) ) {
break;
}
- $order->update_status('on-hold');
- $order->add_order_note(__('Payment pending.', 'paytrail-for-woocommerce'));
+ $order->set_transaction_id( $transaction_id );
+ $order->update_status( 'on-hold' );
+ $order->add_order_note( __( 'Payment pending.', 'paytrail-for-woocommerce' ) );
break;
default:
- $this->log('Paytrail: handle_payment_response, case = failed', 'debug');
- if (!$this->validate_order_payment_process_status($order)) {
+ $this->log( 'Paytrail: handle_payment_response, case = failed', 'debug' );
+ if ( ! $this->validate_order_payment_process_status( $order ) ) {
break;
}
- $order->update_status('failed');
- $failed_order_note = __('Payment failed.', 'paytrail-for-woocommerce');
-
- $latest_order_note = wc_get_order_notes([
- 'order_id' => $order->get_id(),
- 'limit' => 1,
- 'orderby' => 'date_created',
- 'order' => 'DESC',
- ]);
-
- if (is_array($latest_order_note) && isset($latest_order_note[0])) {
- if ($latest_order_note[0]->content === $failed_order_note) {
- break;//Don't add another note if the latest note is the same
+ $order->update_status( 'failed' );
+ $failed_order_note = __( 'Payment failed.', 'paytrail-for-woocommerce' );
+
+ $latest_order_note = wc_get_order_notes(
+ array(
+ 'order_id' => $order->get_id(),
+ 'limit' => 1,
+ 'orderby' => 'date_created',
+ 'order' => 'DESC',
+ )
+ );
+
+ if ( \is_array( $latest_order_note ) && isset( $latest_order_note[0] ) ) {
+ if ( $latest_order_note[0]->content === $failed_order_note ) {
+ break;// Don't add another note if the latest note is the same.
}
}
- $order->add_order_note($failed_order_note);
+ $order->add_order_note( $failed_order_note );
break;
}
}
@@ -1049,49 +1108,49 @@ public function handle_payment_response( $status) {
* Validate payment processing
*
* @param WC_Order $order
- * @param bool $retry Whether to try again after 15 seconds if order is being processed
+ * @param bool $retry Whether to try again after 15 seconds if order is being processed
* @return bool
*/
- protected function validate_order_payment_processing( WC_Order $order, $retry = true) {
- $transaction_id = filter_input(INPUT_GET, 'checkout-transaction-id');
+ protected function validate_order_payment_processing( WC_Order $order, $retry = true ) {
+ $transaction_id = filter_input( INPUT_GET, 'checkout-transaction-id' );
- if (!$transaction_id) {
- $this->log('Paytrail: validate_order_payment_processing, transaction id empty for order: ' . $order->get_id(), 'debug');
+ if ( ! $transaction_id ) {
+ $this->log( 'Paytrail: validate_order_payment_processing, transaction id empty for order: ' . $order->get_id(), 'debug' );
return false;
}
$order_status = $order->get_status();
- if ('completed' === $order_status || 'processing' === $order_status) {
- $this->log('Paytrail: validate_order_payment_processing, order already processed ' . $order->get_id(), 'debug');
+ if ( 'completed' === $order_status || 'processing' === $order_status ) {
+ $this->log( 'Paytrail: validate_order_payment_processing, order already processed ' . $order->get_id(), 'debug' );
// This order has already been processed.
return false;
}
// If the transaction is currently being processed, wait for 15 seconds and check again
- if ('yes' === \get_transient('checkout_transaction_id_processing_' . $transaction_id)) {
- $this->log('Paytrail: validate_order_payment_processing, order is currently being processed ' . $order->get_id(), 'debug');
+ if ( 'yes' === \get_transient( 'checkout_transaction_id_processing_' . $transaction_id ) ) {
+ $this->log( 'Paytrail: validate_order_payment_processing, order is currently being processed ' . $order->get_id(), 'debug' );
- if (true === $retry) {
- $this->log('Paytrail: validate_order_payment_processing, waiting for 15 seconds ' . $order->get_id(), 'debug');
- sleep(15);
+ if ( true === $retry ) {
+ $this->log( 'Paytrail: validate_order_payment_processing, waiting for 15 seconds ' . $order->get_id(), 'debug' );
+ sleep( 15 );
- return $this->validate_order_payment_processing($order, false);
+ return $this->validate_order_payment_processing( $order, false );
}
- $this->log('Paytrail: validate_order_payment_processing, not trying again ' . $order->get_id(), 'debug');
+ $this->log( 'Paytrail: validate_order_payment_processing, not trying again ' . $order->get_id(), 'debug' );
return false;
}
- $this->log('Paytrail: validate_order_payment_processing, order is valid ' . $order->get_id(), 'debug');
+ $this->log( 'Paytrail: validate_order_payment_processing, order is valid ' . $order->get_id(), 'debug' );
return true;
}
- protected function validate_order_payment_process_status( WC_Order $order) {
+ protected function validate_order_payment_process_status( WC_Order $order ) {
$order_status = $order->get_status();
- if ('completed' === $order_status || 'processing' === $order_status) {
+ if ( 'completed' === $order_status || 'processing' === $order_status ) {
// This order has already been processed.
return false;
}
@@ -1104,7 +1163,7 @@ protected function validate_order_payment_process_status( WC_Order $order) {
* @return boolean
*/
protected function use_provider_selection() {
- return 'yes' === $this->get_option('provider_selection', 'yes');
+ return 'yes' === $this->get_option( 'provider_selection', 'yes' );
}
/**
@@ -1115,84 +1174,88 @@ protected function use_provider_selection() {
* @param string $order_id Order ID.
* @return void
*/
- public function handle_refund_response( $refund_callback, $refund_unique_id, $order_id) {
+ public function handle_refund_response( $refund_callback, $refund_unique_id, $order_id ) {
// Remove the callback indicators from the GET array
- $get = filter_input_array(INPUT_GET);
+ $get = filter_input_array( INPUT_GET );
- unset($get['refund_callback']);
- unset($get['refund_unique_id']);
- unset($get['order_id']);
+ unset( $get['refund_callback'] );
+ unset( $get['refund_unique_id'] );
+ unset( $get['order_id'] );
// Check the HMAC
try {
- $this->client->validateHmac($get, '', filter_input(INPUT_GET, 'signature'));
- } catch (HmacException $exception) {
- $this->signature_error($exception);
+ $this->client->validateHmac( $get, '', filter_input( INPUT_GET, 'signature' ) );
+ } catch ( HmacException $exception ) {
+ $this->signature_error( $exception );
}
// Check if HPOS is enabled
- if (class_exists('Automattic\WooCommerce\Utilities\OrderUtil') && \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled()) {
- $refunds = \wc_get_orders([
- 'type' => 'shop_order_refund',
- 'meta_query' => [
- [
- 'key' => '_checkout_refund_unique_id',
- 'value' => $refund_unique_id,
- 'compare' => '='
- ]
- ]
- ]);
+ if ( class_exists( 'Automattic\WooCommerce\Utilities\OrderUtil' ) && \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
+ $refunds = \wc_get_orders(
+ array(
+ 'type' => 'shop_order_refund',
+ 'meta_query' => array(
+ array(
+ 'key' => '_checkout_refund_unique_id',
+ 'value' => $refund_unique_id,
+ 'compare' => '=',
+ ),
+ ),
+ )
+ );
} else {
- $refunds = \wc_get_orders([
- 'type' => 'shop_order_refund',
- 'checkout_refund_unique_id' => $refund_unique_id,
- ]);
+ $refunds = \wc_get_orders(
+ array(
+ 'type' => 'shop_order_refund',
+ 'checkout_refund_unique_id' => $refund_unique_id,
+ )
+ );
}
- if (empty($refunds)) {
- wp_die(esc_html__('Refund cannot be found.', 'paytrail-for-woocommerce'), '', 404);
+ if ( empty( $refunds ) ) {
+ wp_die( esc_html__( 'Refund cannot be found.', 'paytrail-for-woocommerce' ), '', 404 );
} else {
$refund = $refunds[0];
}
- switch ($refund_callback) {
+ switch ( $refund_callback ) {
case 'success':
- $amount = $refund->get_meta('_checkout_refund_amount');
- $reason = $refund->get_meta('_checkout_refund_reason');
+ $amount = $refund->get_meta( '_checkout_refund_amount' );
+ $reason = $refund->get_meta( '_checkout_refund_reason' );
- $refund->set_amount($amount);
- $refund->set_reason($reason);
+ $refund->set_amount( $amount );
+ $refund->set_reason( $reason );
- $order = \wc_get_order($order_id);
+ $order = \wc_get_order( $order_id );
$order->add_order_note(
- __('Refund process completed.', 'paytrail-for-woocommerce')
+ __( 'Refund process completed.', 'paytrail-for-woocommerce' )
);
- $refund->update_meta_data('_checkout_refund_processing', false);
+ $refund->update_meta_data( '_checkout_refund_processing', false );
$refund->save();
break;
case 'cancel':
- $refund->delete(true);
+ $refund->delete( true );
$order_note = __(
'Refund was cancelled by the payment provider.',
'paytrail-for-woocommerce'
);
- $order = \wc_get_order($order_id);
- $order->add_order_note($order_note);
+ $order = \wc_get_order( $order_id );
+ $order->add_order_note( $order_note );
/**
* Delete refund action
*
* @since 1.0
*/
- do_action('woocommerce_refund_delete', $refund->get_id(), $order_id);
+ do_action( 'woocommerce_refund_delete', $refund->get_id(), $order_id );
break;
}
- die('ok');
+ die( 'ok' );
}
/**
@@ -1201,9 +1264,9 @@ public function handle_refund_response( $refund_callback, $refund_unique_id, $or
* @return void
*/
public function payment_fields() {
- if (is_checkout() && $this->use_provider_selection()) {
+ if ( is_checkout() && $this->use_provider_selection() ) {
$this->provider_form();
- } elseif (is_checkout()) {
+ } elseif ( is_checkout() ) {
$this->payment_description();
}
}
@@ -1215,196 +1278,197 @@ public function payment_fields() {
* @return array
* @throws \Exception If the processing fails, this error is handled by WooCommerce.
*/
- public function process_payment( $order_id) {
- $this->log('Paytrail: process_payment', 'debug');
+ public function process_payment( $order_id ) {
+ $this->log( 'Paytrail: process_payment', 'debug' );
// @var WC_Order $order
- $order = wc_get_order($order_id);
- $token_id = filter_input(INPUT_POST, 'wc-paytrail-payment-token');
+ $order = wc_get_order( $order_id );
+ $token_id = filter_input( INPUT_POST, 'wc-paytrail-payment-token' );
// Define if the process should die if an error occurs.
- $die_on_error = filter_input(INPUT_POST, 'woocommerce_pay') ? true : false;
+ $die_on_error = filter_input( INPUT_POST, 'woocommerce_pay' ) ? true : false;
// Get the wanted payment provider and check that it exists
- if ($this->use_provider_selection()) {
- $this->log('Paytrail: use_provider_selection true', 'debug');
+ if ( $this->use_provider_selection() ) {
+ $this->log( 'Paytrail: use_provider_selection true', 'debug' );
// Try to get payment provider from POST
- $payment_provider = filter_input(INPUT_POST, 'payment_provider');
+ $payment_provider = filter_input( INPUT_POST, 'payment_provider' );
// If empty, fallback to the meta data stored in the order
- if (empty($payment_provider)) {
- $payment_provider = get_post_meta($order_id, '_payment_provider', true);
- $this->log('Paytrail: payment_provider retrieved from meta: ' . print_r($payment_provider, true), 'debug');
+ if ( empty( $payment_provider ) ) {
+ $payment_provider = get_post_meta( $order_id, '_payment_provider', true );
+ $this->log( 'Paytrail: payment_provider retrieved from meta: ' . print_r( $payment_provider, true ), 'debug' );
} else {
- $this->log('Paytrail: payment_provider from POST: ' . print_r($payment_provider, true), 'debug');
+ $this->log( 'Paytrail: payment_provider from POST: ' . print_r( $payment_provider, true ), 'debug' );
}
-
} else {
// Try to get payment method from POST
- $payment_provider = filter_input(INPUT_POST, 'payment_method');
- $this->log('Paytrail: use_provider_selection false', 'debug');
+ $payment_provider = filter_input( INPUT_POST, 'payment_method' );
+ $this->log( 'Paytrail: use_provider_selection false', 'debug' );
// If empty, fallback to the meta data stored in the order
- if (empty($payment_provider)) {
- $payment_provider = get_post_meta($order_id, '_payment_method', true);
- $this->log('Paytrail: payment_method retrieved from meta: ' . print_r($payment_provider, true), 'debug');
+ if ( empty( $payment_provider ) ) {
+ $payment_provider = get_post_meta( $order_id, '_payment_method', true );
+ $this->log( 'Paytrail: payment_method retrieved from meta: ' . print_r( $payment_provider, true ), 'debug' );
} else {
- $this->log('Paytrail: payment_method from POST: ' . print_r($payment_provider, true), 'debug');
+ $this->log( 'Paytrail: payment_method from POST: ' . print_r( $payment_provider, true ), 'debug' );
}
}
return $this->process_paytrail_payment( $order, $token_id, $payment_provider, $die_on_error );
}
- public function process_paytrail_payment( $order, $token_id, $payment_provider, $die_on_error) {
+ public function process_paytrail_payment( $order, $token_id, $payment_provider, $die_on_error ) {
- $is_token_payment = !empty($token_id);
+ $is_token_payment = ! empty( $token_id );
- if (! $payment_provider && ! $is_token_payment) {
- wc_add_notice(__(
- 'The payment provider was not chosen.',
- 'paytrail-for-woocommerce'
- ), 'error');
- return [
- 'result' => 'failure'
- ];
- } elseif ($is_token_payment) {
- $this->log('Paytrail: process_payment, is token payment', 'debug');
+ if ( ! $payment_provider && ! $is_token_payment ) {
+ wc_add_notice(
+ __(
+ 'The payment provider was not chosen.',
+ 'paytrail-for-woocommerce'
+ ),
+ 'error'
+ );
+ return array(
+ 'result' => 'failure',
+ );
+ } elseif ( $is_token_payment ) {
+ $this->log( 'Paytrail: process_payment, is token payment', 'debug' );
$payment_provider = 'creditcard';
}
- if ($is_token_payment) {
- $token = \WC_Payment_Tokens::get($token_id);
+ if ( $is_token_payment ) {
+ $token = \WC_Payment_Tokens::get( $token_id );
- $this->log('Paytrail: process_payment, add_payment_token', 'debug');
- $order->add_payment_token($token);
+ $this->log( 'Paytrail: process_payment, add_payment_token', 'debug' );
+ $order->add_payment_token( $token );
- if ($this->helper::getIsSubscriptionsEnabled()) {
- $subscriptions = wcs_get_subscriptions_for_order($order->ID);
- $this->log('Paytrail: add_payment_token to subscriptions', 'debug');
- foreach ($subscriptions as $subscription) {
- $subscription->add_payment_token($token);
+ if ( $this->helper::getIsSubscriptionsEnabled() ) {
+ $subscriptions = wcs_get_subscriptions_for_order( $order->ID );
+ $this->log( 'Paytrail: add_payment_token to subscriptions', 'debug' );
+ foreach ( $subscriptions as $subscription ) {
+ $subscription->add_payment_token( $token );
}
}
$payment = new CitPaymentRequest();
- if ($token && method_exists($token, 'get_token')) {
- $payment->setToken($token->get_token());
+ if ( $token && method_exists( $token, 'get_token' ) ) {
+ $payment->setToken( $token->get_token() );
} else {
- $this->log('Paytrail: Token value: ' . print_r($token, true), 'debug');
+ $this->log( 'Paytrail: Token value: ' . print_r( $token, true ), 'debug' );
}
-
} else {
- $this->log('Paytrail: init PaymentRequest', 'debug');
+ $this->log( 'Paytrail: init PaymentRequest', 'debug' );
$payment = new PaymentRequest();
}
- if (0 == floatval($order->get_total())) {
- $this->log('Paytrail: process_payment, order total 0, payment complete, order needs processing' . $order->needs_processing(), 'debug');
+ if ( 0 == floatval( $order->get_total() ) ) {
+ $this->log( 'Paytrail: process_payment, order total 0, payment complete, order needs processing' . $order->needs_processing(), 'debug' );
$order->payment_complete();
- return [
+ return array(
'result' => 'success',
- 'redirect' => $this->get_return_url($order)
- ];
+ 'redirect' => $this->get_return_url( $order ),
+ );
}
- $this->set_base_payment_data($payment, $order);
+ $this->set_base_payment_data( $payment, $order );
- $this->log('Paytrail: process_payment, order update_meta_data', 'debug');
+ $this->log( 'Paytrail: process_payment, order update_meta_data', 'debug' );
// Save the reference for possible later use.
- $order->update_meta_data('_checkout_reference', $payment->getReference());
+ $order->update_meta_data( '_checkout_reference', $payment->getReference() );
// Save it also as a key for fast indexed searches.
- $order->update_meta_data('_checkout_reference_' . $payment->getReference(), true);
+ $order->update_meta_data( '_checkout_reference_' . $payment->getReference(), true );
// Save the wanted payment provider to the order
- $order->update_meta_data('_checkout_payment_provider', $payment_provider);
+ $order->update_meta_data( '_checkout_payment_provider', $payment_provider );
$order->save();
// Create a payment via Paytrail SDK
try {
- if ($is_token_payment) {
- return $this->create_cit_payment($payment, $order);
+ if ( $is_token_payment ) {
+ return $this->create_cit_payment( $payment, $order );
} else {
- return $this->create_normal_payment($payment, $order, $payment_provider);
+ return $this->create_normal_payment( $payment, $order, $payment_provider );
}
- } catch (ValidationException $exception) {
+ } catch ( ValidationException $exception ) {
$message = __(
'An error occurred validating the payment.',
'paytrail-for-woocommerce'
);
- $this->error($exception, $message, $die_on_error);
- } catch (HmacException $exception) {
- $this->signature_error($exception, $die_on_error);
- } catch (\Exception $exception) {
+ $this->error( $exception, $message, $die_on_error );
+ } catch ( HmacException $exception ) {
+ $this->signature_error( $exception, $die_on_error );
+ } catch ( \Exception $exception ) {
$message = __(
'An error occurred performing the payment request.',
'paytrail-for-woocommerce'
);
- $this->error($exception, $message, $die_on_error);
+ $this->error( $exception, $message, $die_on_error );
}
- return [
- 'result' => 'failure'
- ];
+ return array(
+ 'result' => 'failure',
+ );
}
/**
* Create payment
*
* @param PaymentRequest|CitPaymentRequest $payment
- * @param WC_Order $order
+ * @param WC_Order $order
* @param $payment_provider
* @return array
* @throws HmacException
* @throws ValidationException
* @throws \Exception
*/
- private function create_normal_payment( $payment, $order, $payment_provider) {
- $this->log('Paytrail: create_normal_payment', 'debug');
+ private function create_normal_payment( $payment, $order, $payment_provider ) {
+ $this->log( 'Paytrail: create_normal_payment', 'debug' );
try {
// Log the payment request if debug log is enabled.
- $this->log('Paytrail\SDK\Request\PaymentRequest: ' . json_encode($payment), 'info');
- $response = $this->client->createPayment($payment);
- } catch (\Exception $exception) {
+ $this->log( 'Paytrail\SDK\Request\PaymentRequest: ' . json_encode( $payment ), 'info' );
+ $response = $this->client->createPayment( $payment );
+ } catch ( \Exception $exception ) {
// Log the error message if debug log is enabled.
- $this->log($exception->getMessage() . $exception->getTraceAsString(), 'error');
- new \WP_Error($exception->getCode(), $exception->getMessage());
+ $this->log( $exception->getMessage() . $exception->getTraceAsString(), 'error' );
+ new \WP_Error( $exception->getCode(), $exception->getMessage() );
- //Add error messages to be displayed to the user by Woocommerce
+ // Add error messages to be displayed to the user by Woocommerce
$exceptionError = $exception->getMessage();
- $jsonData = json_decode($exceptionError, true);
-
- //The API may return JSON data in the message rather than plain string
- if ($jsonData && isset($jsonData['message'])) {
- wc_add_notice ($jsonData['message'], 'error');
- //The API can return multiple error messages so add each of these messages
- if (isset($jsonData['meta']) && is_array($jsonData['meta'])) {
- foreach ($jsonData['meta'] as $meta) {
- wc_add_notice ($meta, 'error');
+ $jsonData = json_decode( $exceptionError, true );
+
+ // The API may return JSON data in the message rather than plain string
+ if ( $jsonData && isset( $jsonData['message'] ) ) {
+ wc_add_notice( $jsonData['message'], 'error' );
+ // The API can return multiple error messages so add each of these messages
+ if ( isset( $jsonData['meta'] ) && is_array( $jsonData['meta'] ) ) {
+ foreach ( $jsonData['meta'] as $meta ) {
+ wc_add_notice( $meta, 'error' );
}
}
} else {
- wc_add_notice (ucwords($exceptionError), 'error');
+ wc_add_notice( ucwords( $exceptionError ), 'error' );
}
}
- if (!isset($response) || null === $response) {
- $this->log('FAILURE: Response is NULL or empty', 'error');
- return [
- 'result' => 'failure'
- ];
+ if ( ! isset( $response ) || null === $response ) {
+ $this->log( 'FAILURE: Response is NULL or empty', 'error' );
+ return array(
+ 'result' => 'failure',
+ );
}
- if ($this->use_provider_selection()) {
- $this->log('Paytrail: create_normal_payment, use_provider_selection = true', 'debug');
+ if ( $this->use_provider_selection() ) {
+ $this->log( 'Paytrail: create_normal_payment, use_provider_selection = true', 'debug' );
$providers = $response->getProviders();
- //Get only the wanted payment provider object
- $wanted_provider = $this->get_wanted_provider($providers, $payment_provider);
+ // Get only the wanted payment provider object
+ $wanted_provider = $this->get_wanted_provider( $providers, $payment_provider );
- WC()->session->set('payment_provider', $wanted_provider);
+ WC()->session->set( 'payment_provider', $wanted_provider );
$message = sprintf(
// translators: First parameter is transaction ID, the other is the name of the payment provider.
@@ -1413,17 +1477,17 @@ private function create_normal_payment( $payment, $order, $payment_provider) {
'paytrail-for-woocommerce'
),
$response->getTransactionId(),
- !empty($wanted_provider->getName()) ? $wanted_provider->getName() : ucfirst($payment_provider)
+ ! empty( $wanted_provider->getName() ) ? $wanted_provider->getName() : ucfirst( $payment_provider )
);
- $this->log('Paytrail: create_normal_payment, use_provider_selection = true, redirect', 'debug');
- $order->add_order_note($message);
+ $this->log( 'Paytrail: create_normal_payment, use_provider_selection = true, redirect', 'debug' );
+ $order->add_order_note( $message );
- return [
+ return array(
'result' => 'success',
- 'redirect' => $order->get_checkout_payment_url(true),
- ];
+ 'redirect' => $order->get_checkout_payment_url( true ),
+ );
} else {
- $this->log('Paytrail: create_normal_payment, use_provider_selection = false', 'debug');
+ $this->log( 'Paytrail: create_normal_payment, use_provider_selection = false', 'debug' );
$message = sprintf(
// translators: First parameter is transaction ID, the other is the name of the payment provider.
__(
@@ -1433,12 +1497,12 @@ private function create_normal_payment( $payment, $order, $payment_provider) {
$response->getTransactionId()
);
- $order->add_order_note($message);
- $this->log('Paytrail: create_normal_payment, use_provider_selection = false, redirect', 'debug');
- return [
+ $order->add_order_note( $message );
+ $this->log( 'Paytrail: create_normal_payment, use_provider_selection = false, redirect', 'debug' );
+ return array(
'result' => 'success',
'redirect' => $response->getHref(),
- ];
+ );
}
}
@@ -1446,37 +1510,37 @@ private function create_normal_payment( $payment, $order, $payment_provider) {
* Create CIT payment
*
* @param CitPaymentRequest $payment
- * @param WC_Order $order
+ * @param WC_Order $order
* @throws HmacException
* @throws ValidationException
*/
- private function create_cit_payment( $payment, $order) {
- $this->log('Paytrail: create_cit_payment', 'debug');
+ private function create_cit_payment( $payment, $order ) {
+ $this->log( 'Paytrail: create_cit_payment', 'debug' );
try {
- $response = $this->client->createCitPaymentCharge($payment);
+ $response = $this->client->createCitPaymentCharge( $payment );
// Log the payment request if debug log is enabled.
- $this->log('Paytrail\SDK\Request\CitPaymentRequest: ' . json_encode($payment), 'info');
- } catch (\Exception $exception) {
- $fail_message = __('Failed to create token payment using card.', 'paytrail-for-woocommerce');
+ $this->log( 'Paytrail\SDK\Request\CitPaymentRequest: ' . json_encode( $payment ), 'info' );
+ } catch ( \Exception $exception ) {
+ $fail_message = __( 'Failed to create token payment using card.', 'paytrail-for-woocommerce' );
// Log the error message if debug log is enabled.
- $this->log($exception->getMessage() . $exception->getTraceAsString(), 'error');
- new \WP_Error($exception->getCode(), $exception->getMessage());
+ $this->log( $exception->getMessage() . $exception->getTraceAsString(), 'error' );
+ new \WP_Error( $exception->getCode(), $exception->getMessage() );
- wc_add_notice($fail_message, 'error');
+ wc_add_notice( $fail_message, 'error' );
- $order->add_order_note($fail_message);
+ $order->add_order_note( $fail_message );
- return [
- 'result' => 'fail'
- ];
+ return array(
+ 'result' => 'fail',
+ );
}
$requires_threeds = $response->getThreeDSecureUrl() !== null;
- if ($response->getTransactionId() === null && $requires_threeds) {
- throw new \Exception('Transcaction Id not found');
+ if ( $response->getTransactionId() === null && $requires_threeds ) {
+ throw new \Exception( 'Transcaction Id not found' );
}
$message = sprintf(
@@ -1486,52 +1550,52 @@ private function create_cit_payment( $payment, $order) {
'paytrail-for-woocommerce'
),
$response->getTransactionId(),
- $requires_threeds ? __('yes', 'paytrail-for-woocommerce') : __('no', 'paytrail-for-woocommerce')
+ $requires_threeds ? __( 'yes', 'paytrail-for-woocommerce' ) : __( 'no', 'paytrail-for-woocommerce' )
);
- $order->add_order_note($message);
+ $order->add_order_note( $message );
- if (!$requires_threeds) {
- $this->log('Paytrail: create_cit_payment, No 3DS required, payment_complete ', 'info');
- $order->payment_complete($response->getTransactionId());
+ if ( ! $requires_threeds ) {
+ $this->log( 'Paytrail: create_cit_payment, No 3DS required, payment_complete ', 'info' );
+ $order->payment_complete( $response->getTransactionId() );
}
- $redirect_url = !empty($response->getThreeDSecureUrl()) ? $response->getThreeDSecureUrl() : $this->get_return_url($order);
+ $redirect_url = ! empty( $response->getThreeDSecureUrl() ) ? $response->getThreeDSecureUrl() : $this->get_return_url( $order );
- return [
+ return array(
'result' => 'success',
- 'redirect' => $redirect_url
- ];
+ 'redirect' => $redirect_url,
+ );
}
/**
* Create MIT payment
*
* @param MitPaymentRequest $payment
- * @param WC_Order $order
+ * @param WC_Order $order
* @return bool
* @throws \Exception
*/
- private function create_mit_payment( $payment, $order) {
+ private function create_mit_payment( $payment, $order ) {
try {
- $response = $this->client->createMitPaymentCharge($payment);
+ $response = $this->client->createMitPaymentCharge( $payment );
// Log the payment request if debug log is enabled.
- $this->log('Paytrail\SDK\Request\MitPaymentRequest: ' . json_encode($payment), 'info');
- } catch (\Exception $exception) {
- $fail_message = __('Failed to create token payment using card.', 'paytrail-for-woocommerce');
+ $this->log( 'Paytrail\SDK\Request\MitPaymentRequest: ' . json_encode( $payment ), 'info' );
+ } catch ( \Exception $exception ) {
+ $fail_message = __( 'Failed to create token payment using card.', 'paytrail-for-woocommerce' );
// Log the error message if debug log is enabled.
- $this->log($exception->getMessage() . $exception->getTraceAsString(), 'error');
- new \WP_Error($exception->getCode(), $exception->getMessage());
+ $this->log( $exception->getMessage() . $exception->getTraceAsString(), 'error' );
+ new \WP_Error( $exception->getCode(), $exception->getMessage() );
- $order->add_order_note($fail_message);
+ $order->add_order_note( $fail_message );
return false;
}
- if ($response->getTransactionId() === null) {
- throw new \Exception('Transcaction Id not found');
+ if ( $response->getTransactionId() === null ) {
+ throw new \Exception( 'Transcaction Id not found' );
}
$message = sprintf(
@@ -1543,9 +1607,9 @@ private function create_mit_payment( $payment, $order) {
$response->getTransactionId()
);
- $order->add_order_note($message);
- $this->log('Paytrail: create_mit_payment payment_complete ', 'info');
- $order->payment_complete($response->getTransactionId());
+ $order->add_order_note( $message );
+ $this->log( 'Paytrail: create_mit_payment payment_complete ', 'info' );
+ $order->payment_complete( $response->getTransactionId() );
return true;
}
@@ -1554,67 +1618,70 @@ private function create_mit_payment( $payment, $order) {
* Set payment data
*
* @param PaymentRequest|CitPaymentRequest|MitPaymentRequest $payment
- * @param WC_Order $order
+ * @param WC_Order $order
* @return mixed
* @throws \Exception
*/
- private function set_base_payment_data( $payment, $order) {
- // Set the order ID as the stamp to the payment request
- $payment->setStamp(get_current_blog_id() . '-' . $order->get_id() . '-' . time());
+ private function set_base_payment_data( $payment, $order ) {
+ // Set the order ID as the stamp to the payment request.
+ $payment->setStamp( get_current_blog_id() . '-' . $order->get_id() . '-' . time() );
- // Use WooCom order number as reference
+ // Use WooCom order number as reference.
$reference = $order->get_order_number();
- // Calculate bank reference for transaction-specific settlements
+ // Calculate bank reference for transaction-specific settlements.
if ( $this->transaction_settlement_enable ) {
$reference = $this->calculate_reference( $reference );
}
- // Set WooCommerce order number as the payment reference
- $payment->setReference($reference);
+ // Set WooCommerce order number as the payment reference.
+ $payment->setReference( $reference );
- // Fetch current currency and the cart total
+ // Fetch current currency and the cart total.
$currency = get_woocommerce_currency();
- $order_total = $this->helper->handle_currency($order->get_total());
+ $order_total = $this->helper->handle_currency( $order->get_total() );
- // Set the aforementioned values to the payment request
- $payment->setCurrency($currency)
- ->setAmount($order_total);
+ // Set the aforementioned values to the payment request.
+ $payment->setCurrency( $currency )
+ ->setAmount( $order_total );
- // Create a customer object from the order
- $customer = $this->create_customer($order);
+ // Create a customer object from the order.
+ $customer = $this->create_customer( $order );
- // Set the customer object to the payment request
- $payment->setCustomer($customer);
+ // Set the customer object to the payment request.
+ $payment->setCustomer( $customer );
- // Create a billing address and assign it to the payment request
- $billing_address = $this->create_address($order, 'invoicing');
+ // Create a billing address and assign it to the payment request.
+ $billing_address = $this->create_address( $order, 'invoicing' );
- if ($billing_address) {
- $payment->setInvoicingAddress($billing_address);
+ if ( $billing_address ) {
+ $payment->setInvoicingAddress( $billing_address );
}
- // Create a shipping address and assign it to the payment request
- $shipping_address = $this->create_address($order, 'delivery');
+ // Create a shipping address and assign it to the payment request.
+ $shipping_address = $this->create_address( $order, 'delivery' );
- if ($shipping_address) {
- $payment->setDeliveryAddress($shipping_address);
+ if ( $shipping_address ) {
+ $payment->setDeliveryAddress( $shipping_address );
}
- $payment->setLanguage(Helper::getLocale());
+ $payment->setLanguage( Helper::getLocale() );
- // Get the items from the order
- $items = $this->get_order_items($order);
+ // Get the items from the order.
+ $items = $this->get_order_items( $order );
// Assign the items to the payment request.
- $payment->setItems(array_filter($items));
+ $payment->setItems( array_filter( $items ) );
+
+ // Create and assign the return urls.
+ $payment->setRedirectUrls( $this->create_redirect_url( $order ) );
+ $payment->setCallbackUrls( $this->create_callback_url() );
- // Create and assign the return urls
- $payment->setRedirectUrls($this->create_redirect_url($order));
- $payment->setCallbackUrls($this->create_callback_url());
+ // Set callback delay to the payment request.
+ $payment->setCallbackDelay( 3 );
- // Set callback delay to the payment request
- $payment->setCallbackDelay(3);
+ $manual_invoice_activation = wc_string_to_bool( $this->get_option( 'manual_invoice_activation', 'no' ) );
+ $payment->setManualInvoiceActivation( $manual_invoice_activation );
return $payment;
}
@@ -1626,41 +1693,48 @@ private function set_base_payment_data( $payment, $order) {
* @return array
* @throws \Exception
*/
- private function get_order_items( $order) {
+ private function get_order_items( $order ) {
/**
* Get the items from the order
*
* @since 1.0
*/
- $order_items = apply_filters('woocommerce_paytrail_gateway_get_order_items', $order->get_items([ 'line_item', 'fee', 'shipping' ]), $order);
- $order_total = intval($this->helper->handle_currency($order->get_total()));
+ $order_items = apply_filters( 'woocommerce_paytrail_gateway_get_order_items', $order->get_items( array( 'line_item', 'fee', 'shipping' ) ), $order );
+ $order_total = intval( $this->helper->handle_currency( $order->get_total() ) );
// Convert items to SDK Item objects.
$items = array_map(
- function ( $item) use ( $order) {
- return $this->create_item($item, $order);
+ function ( $item ) use ( $order ) {
+ return $this->create_item( $item, $order );
},
$order_items
);
- $sub_sum = intval(array_sum(array_map(function ( Item $item) {
- return ( $item->getUnitPrice() * $item->getUnits() );
- }, $items)));
+ $sub_sum = intval(
+ array_sum(
+ array_map(
+ function ( Item $item ) {
+ return ( $item->getUnitPrice() * $item->getUnits() );
+ },
+ $items
+ )
+ )
+ );
$diff = $order_total - $sub_sum;
// If item total is negative, add positive amount for it.
- if ($diff > 0) {
+ if ( $diff > 0 ) {
$rounding_item = new Item();
- $rounding_item->setDescription(__('Rounding', 'paytrail-for-woocommerce'));
- $rounding_item->setVatPercentage(0);
- $rounding_item->setUnits(1);
- $rounding_item->setUnitPrice(abs($diff));
- $rounding_item->setProductCode('rounding-row');
- $rounding_item->setStamp($this->helper->generate_item_stamp($order->get_id()));
+ $rounding_item->setDescription( __( 'Rounding', 'paytrail-for-woocommerce' ) );
+ $rounding_item->setVatPercentage( 0 );
+ $rounding_item->setUnits( 1 );
+ $rounding_item->setUnitPrice( abs( $diff ) );
+ $rounding_item->setProductCode( 'rounding-row' );
+ $rounding_item->setStamp( $this->helper->generate_item_stamp( $order->get_id() ) );
$items[] = $rounding_item;
- } elseif ($diff < 0) {
- $items = $this->fix_rounding_error($items, $diff, $order->get_id());
+ } elseif ( $diff < 0 ) {
+ $items = $this->fix_rounding_error( $items, $diff, $order->get_id() );
}
return $items;
@@ -1668,22 +1742,22 @@ function ( $item) use ( $order) {
private function fix_rounding_error( $items, $diff, $order_id ) {
// Subtract rounding error from first not zero price item if sub sum is too high.
- $lastItemKey = $this->getLastNonZeroItemKey($items, $diff);
- $lastItem = $items[$lastItemKey];
- $lastItem->setUnitPrice($lastItem->getUnitPrice() + $diff);
- $items[$lastItemKey] = $lastItem;
+ $lastItemKey = $this->getLastNonZeroItemKey( $items, $diff );
+ $lastItem = $items[ $lastItemKey ];
+ $lastItem->setUnitPrice( $lastItem->getUnitPrice() + $diff );
+ $items[ $lastItemKey ] = $lastItem;
// If item quantity is not one, there's still negative difference to fix.
- if ($lastItem->getUnits() > 1) {
- $difference = ( $lastItem->getUnits() -1 )*$diff;
+ if ( $lastItem->getUnits() > 1 ) {
+ $difference = ( $lastItem->getUnits() - 1 ) * $diff;
$rounding_item = new Item();
- $rounding_item->setDescription(__('Rounding', 'paytrail-for-woocommerce'));
- $rounding_item->setVatPercentage(0);
- $rounding_item->setUnits(1);
- $rounding_item->setUnitPrice(abs($difference));
- $rounding_item->setProductCode('rounding-row');
- $rounding_item->setStamp($this->helper->generate_item_stamp($order_id));
+ $rounding_item->setDescription( __( 'Rounding', 'paytrail-for-woocommerce' ) );
+ $rounding_item->setVatPercentage( 0 );
+ $rounding_item->setUnits( 1 );
+ $rounding_item->setUnitPrice( abs( $difference ) );
+ $rounding_item->setProductCode( 'rounding-row' );
+ $rounding_item->setStamp( $this->helper->generate_item_stamp( $order_id ) );
$items[] = $rounding_item;
}
@@ -1695,8 +1769,8 @@ private function fix_rounding_error( $items, $diff, $order_id ) {
* Loop items and find first non zero item to subtract difference.
*/
private function getLastNonZeroItemKey( $items, $diff ) {
- foreach ($items as $key => $item) {
- if (( $item->getUnitPrice() + $diff ) > 0) {
+ foreach ( $items as $key => $item ) {
+ if ( ( $item->getUnitPrice() + $diff ) > 0 ) {
// Return on first non zero item
return $key;
}
@@ -1710,18 +1784,17 @@ private function getLastNonZeroItemKey( $items, $diff ) {
* @param $payment_provider
* @return mixed|null
*/
- private function get_wanted_provider( $providers, $payment_provider) {
+ private function get_wanted_provider( $providers, $payment_provider ) {
// Get only the wanted payment provider object
- return
- array_reduce(
- $providers,
- function ( $carry, $item = null) use ( $payment_provider) {
- if ($item && $item->getId() === $payment_provider) {
- return $item;
- }
- return $carry;
+ return array_reduce(
+ $providers,
+ function ( $carry, $item = null ) use ( $payment_provider ) {
+ if ( $item && $item->getId() === $payment_provider ) {
+ return $item;
}
- );
+ return $carry;
+ }
+ );
}
/**
@@ -1731,42 +1804,42 @@ function ( $carry, $item = null) use ( $payment_provider) {
* @param WC_Order $order
* @throws \Exception
*/
- public function scheduled_subscription_payment( $amount, $order) {
- $this->log('Paytrail: scheduled_subscription_payment', 'debug');
- $fail_message = __('Cannot schedule subscription payment. No valid tokens found for order.', 'paytrail-for-woocommerce');
+ public function scheduled_subscription_payment( $amount, $order ) {
+ $this->log( 'Paytrail: scheduled_subscription_payment', 'debug' );
+ $fail_message = __( 'Cannot schedule subscription payment. No valid tokens found for order.', 'paytrail-for-woocommerce' );
- $tokens = \WC_Payment_Tokens::get_order_tokens($order->get_id());
- $validTokens = [];
- foreach ($tokens as $token) {
- if (!$token->validate()) {
+ $tokens = \WC_Payment_Tokens::get_order_tokens( $order->get_id() );
+ $validTokens = array();
+ foreach ( $tokens as $token ) {
+ if ( ! $token->validate() ) {
continue;
}
$validTokens[] = $token;
}
- if (empty($validTokens)) {
+ if ( empty( $validTokens ) ) {
// Log the error message if debug log is enabled.
- $this->log($fail_message, 'error');
- $order->add_order_note($fail_message);
+ $this->log( $fail_message, 'error' );
+ $order->add_order_note( $fail_message );
return false;
}
try {
- $token = reset($validTokens);
+ $token = reset( $validTokens );
$payment = new MitPaymentRequest();
- $payment->setToken($token->get_token());
+ $payment->setToken( $token->get_token() );
- $this->set_base_payment_data($payment, $order);
+ $this->set_base_payment_data( $payment, $order );
// Save the reference for possible later use.
- $order->update_meta_data('_checkout_reference', $payment->getReference());
+ $order->update_meta_data( '_checkout_reference', $payment->getReference() );
// Save it also as a key for fast indexed searches.
- $order->update_meta_data('_checkout_reference_' . $payment->getReference(), true);
+ $order->update_meta_data( '_checkout_reference_' . $payment->getReference(), true );
$order->save();
- $this->create_mit_payment($payment, $order);
- } catch (\Exception $exception) {
+ $this->create_mit_payment( $payment, $order );
+ } catch ( \Exception $exception ) {
// Log the error message if debug log is enabled.
- $this->log($exception->getMessage() . $exception->getTraceAsString(), 'error');
+ $this->log( $exception->getMessage() . $exception->getTraceAsString(), 'error' );
return false;
}
return true;
@@ -1780,25 +1853,25 @@ public function scheduled_subscription_payment( $amount, $order) {
* @param string $reason Optional reason for the refund.
* @return boolean|\WP_Error
*/
- public function process_refund( $order_id, $amount = null, $reason = '') {
- $this->log('Paytrail: process_refund', 'debug');
+ public function process_refund( $order_id, $amount = null, $reason = '' ) {
+ $this->log( 'Paytrail: process_refund', 'debug' );
try {
- $order = \wc_get_order($order_id);
+ $order = \wc_get_order( $order_id );
// Create a unique identifier for the refund
- $refund_unique_id = sha1(uniqid(true));
+ $refund_unique_id = sha1( uniqid( true ) );
$refund = new RefundRequest();
- if ($amount) {
- $refund->setAmount($this->helper->handle_currency($amount));
+ if ( $amount ) {
+ $refund->setAmount( $this->helper->handle_currency( $amount ) );
} else {
- $refund->setAmount($this->helper->handle_currency($order->get_total()));
+ $refund->setAmount( $this->helper->handle_currency( $order->get_total() ) );
$amount = $order->get_total();
}
- if ($refund->getAmount() === 0) {
+ if ( $refund->getAmount() === 0 ) {
return new \WP_Error(
'400',
__(
@@ -1812,115 +1885,115 @@ public function process_refund( $order_id, $amount = null, $reason = '') {
$url = new CallbackUrl();
- $callbacks = $this->create_redirect_url($order);
+ $callbacks = $this->create_redirect_url( $order );
$success_callback = add_query_arg(
array(
- 'refund_callback' => 'success',
+ 'refund_callback' => 'success',
'refund_unique_id' => $refund_unique_id,
- 'order_id' => $order_id
+ 'order_id' => $order_id,
),
$callbacks->getSuccess()
);
- $cancel_callback = add_query_arg(
+ $cancel_callback = add_query_arg(
array(
- 'refund_callback' => 'cancel',
+ 'refund_callback' => 'cancel',
'refund_unique_id' => $refund_unique_id,
- 'order_id' => $order_id
+ 'order_id' => $order_id,
),
$callbacks->getSuccess()
);
- $url->setSuccess($success_callback)
- ->setCancel($cancel_callback);
+ $url->setSuccess( $success_callback )
+ ->setCancel( $cancel_callback );
- $refund->setCallbackUrls($url);
+ $refund->setCallbackUrls( $url );
$transaction_id = $order->get_transaction_id();
$order->add_order_note(
sprintf(
// Translators: placeholder is the optional reason for the refund.
- __('Refunding process started.%s', 'paytrail-for-woocommerce'),
- $reason ? esc_html__(' Reason: ', 'paytrail-for-woocommerce') . esc_html($reason) : ''
+ __( 'Refunding process started.%s', 'paytrail-for-woocommerce' ),
+ $reason ? esc_html__( ' Reason: ', 'paytrail-for-woocommerce' ) . esc_html( $reason ) : ''
)
);
// Do some additional stuff after the refund object has been created
add_action(
'woocommerce_order_refunded',
- function ( $order_id, $refund_id) use ( $order, $refund, $reason, $transaction_id, $amount, $price, $refund_unique_id) {
- $refund_object = wc_get_order($refund_id);
+ function ( $order_id, $refund_id ) use ( $order, $refund, $reason, $transaction_id, $amount, $price, $refund_unique_id ) {
+ $refund_object = wc_get_order( $refund_id );
try {
- $this->client->refund($refund, $transaction_id);
- } catch (\Exception $e) {
- switch ($e->getCode()) {
+ $this->client->refund( $refund, $transaction_id );
+ } catch ( \Exception $e ) {
+ switch ( $e->getCode() ) {
case 422:
// An email refund request is needed
$email = $order->get_billing_email();
$email_refund_request = new EmailRefundRequest();
- $email_refund_request->setEmail($email);
- $email_refund_request->setAmount($refund->getAmount());
- $email_refund_request->setCallbackUrls($refund->getCallbackUrls());
+ $email_refund_request->setEmail( $email );
+ $email_refund_request->setAmount( $refund->getAmount() );
+ $email_refund_request->setCallbackUrls( $refund->getCallbackUrls() );
- if (count($refund->getItems()) > 0) {
- $email_refund_request->setItems($refund->getItems());
+ if ( count( $refund->getItems() ) > 0 ) {
+ $email_refund_request->setItems( $refund->getItems() );
}
try {
- $this->client->emailRefund($email_refund_request, $transaction_id);
- } catch (\Exception $e) {
- switch ($e->getCode()) {
+ $this->client->emailRefund( $email_refund_request, $transaction_id );
+ } catch ( \Exception $e ) {
+ switch ( $e->getCode() ) {
case 422:
- $refund_object->delete(true);
+ $refund_object->delete( true );
$order->add_order_note(
__(
'The payment provider does not support either regular or email refunds. The refund was cancelled.',
'paytrail-for-woocommerce'
)
);
- $order->update_status('failed');
+ $order->update_status( 'failed' );
return false; // Return when an error occurred.
// Default, should be 400.
default:
- $refund_object->delete(true);
+ $refund_object->delete( true );
$order->add_order_note(
__(
'Something went wrong with the email refund and it was cancelled.',
'paytrail-for-woocommerce'
)
);
- $order->update_status('failed');
+ $order->update_status( 'failed' );
return false; // Return when an error occurred.
}
}
break; // Break the email refund processing.
// Default, should be 400.
default:
- $refund_object->delete(true);
+ $refund_object->delete( true );
$order->add_order_note(
__(
'Something went wrong with the refund and it was cancelled.',
'paytrail-for-woocommerce'
)
);
- $order->update_status('failed');
+ $order->update_status( 'failed' );
return false; // Return when an error occurred.
}
}
$reason = $refund_object->get_reason();
- $refund_object->update_meta_data( '_checkout_refund_amount', $amount);
- $refund_object->update_meta_data( '_checkout_refund_reason', $reason);
- $refund_object->update_meta_data( '_checkout_refund_unique_id', $refund_unique_id);
- $refund_object->update_meta_data( '_checkout_refund_processing', true);
+ $refund_object->update_meta_data( '_checkout_refund_amount', $amount );
+ $refund_object->update_meta_data( '_checkout_refund_reason', $reason );
+ $refund_object->update_meta_data( '_checkout_refund_unique_id', $refund_unique_id );
+ $refund_object->update_meta_data( '_checkout_refund_processing', true );
- $refund_object->set_amount(0);
- $refund_object->set_reason($reason . ' Refund is still being processed. The status and the amount (' . $price . ') of the refund will update when the processing is completed.');
+ $refund_object->set_amount( 0 );
+ $refund_object->set_reason( $reason . ' Refund is still being processed. The status and the amount (' . $price . ') of the refund will update when the processing is completed.' );
$refund_object->save();
@@ -1931,10 +2004,10 @@ function ( $order_id, $refund_id) use ( $order, $refund, $reason, $transaction_i
);
return true;
- } catch (\Exception $exception) {
- $this->log($exception->getMessage() . $exception->getTraceAsString(), 'error');
+ } catch ( \Exception $exception ) {
+ $this->log( $exception->getMessage() . $exception->getTraceAsString(), 'error' );
- return new \WP_Error($exception->getCode(), $exception->getMessage());
+ return new \WP_Error( $exception->getCode(), $exception->getMessage() );
}
}
@@ -1944,22 +2017,22 @@ function ( $order_id, $refund_id) use ( $order, $refund, $reason, $transaction_i
* @param int $order_id Order ID to handle.
* @return void
*/
- public function refund_items( $order_id) {
- $order = new \WC_Order($order_id);
+ public function refund_items( $order_id ) {
+ $order = new \WC_Order( $order_id );
$refunds = $order->get_refunds();
- if ($refunds) {
+ if ( $refunds ) {
array_walk(
$refunds,
- function ( $refund) {
- $meta = $refund->get_meta('_checkout_refund_processing');
- if ($meta) {
+ function ( $refund ) {
+ $meta = $refund->get_meta( '_checkout_refund_processing' );
+ if ( $meta ) {
echo '';
- };
+ }
}
);
}
@@ -1972,28 +2045,28 @@ function ( $refund) {
*/
protected function provider_form() {
$cart_total = $this->helper->get_cart_total();
- $res = [];
+ $res = array();
- $providers = $this->get_grouped_payment_providers($cart_total, Helper::getLocale());
+ $providers = $this->get_grouped_payment_providers( $cart_total, Helper::getLocale() );
// If there was an error getting the payment providers, show it
- if (! empty($providers['error'])) {
- echo '' . esc_html($providers['error']) . '
';
+ if ( ! empty( $providers['error'] ) ) {
+ echo '' . esc_html( $providers['error'] ) . '
';
return;
}
- $res['terms'] = !empty($providers['terms']) ? $providers['terms'] : '';
+ $res['terms'] = ! empty( $providers['terms'] ) ? $providers['terms'] : '';
$res['groups'] = $providers['groups'];
- $provider_form_view = new View('ProviderForm');
+ $provider_form_view = new View( 'ProviderForm' );
- $provider_form_view->render($res);
+ $provider_form_view->render( $res );
}
protected function payment_description() {
$data['description'] = $this->description;
- $view = new View('PaymentDescription');
- $view->render($data);
+ $view = new View( 'PaymentDescription' );
+ $view->render( $data );
}
/**
@@ -2001,20 +2074,20 @@ protected function payment_description() {
*
* @param \WC_Order $order The order to create the customer object from.
*
- * @return \CheckoutFinland\SDK\Model\Customer
+ * @return Paytrail\SDK\Model\Customer
*/
- protected function create_customer( \WC_Order $order) {
+ protected function create_customer( \WC_Order $order ) {
$customer = new Customer();
- if (!$order) {
+ if ( ! $order ) {
return $customer;
}
- $customer->setEmail($order->get_billing_email())
- ->setFirstName($order->get_billing_first_name())
- ->setLastName($order->get_billing_last_name())
- ->setPhone($order->get_billing_phone())
- ->setCompanyName($order->get_billing_company());
+ $customer->setEmail( $order->get_billing_email() )
+ ->setFirstName( $order->get_billing_first_name() )
+ ->setLastName( $order->get_billing_last_name() )
+ ->setPhone( $order->get_billing_phone() )
+ ->setCompanyName( $order->get_billing_company() );
return $customer;
}
@@ -2025,13 +2098,13 @@ protected function create_customer( \WC_Order $order) {
* @param integer $payment_amount Payment amount in currency minor unit, eg. cents.
* @return array
*/
- protected function get_payment_providers( $payment_amount) {
+ protected function get_payment_providers( $payment_amount ) {
try {
- $providers = $this->client->getPaymentProviders($payment_amount);
- } catch (HmacException $exception) {
- $providers = $this->get_payment_providers_error_handler($exception);
- } catch (\Exception $exception) {
- $providers = $this->get_payment_providers_error_handler($exception);
+ $providers = $this->client->getPaymentProviders( $payment_amount );
+ } catch ( HmacException $exception ) {
+ $providers = $this->get_payment_providers_error_handler( $exception );
+ } catch ( \Exception $exception ) {
+ $providers = $this->get_payment_providers_error_handler( $exception );
}
return $providers;
@@ -2041,27 +2114,27 @@ protected function get_payment_providers( $payment_amount) {
* Get the grouped list of payment providers
*
* @param integer $payment_amount Payment amount in currency minor unit, eg. cents.
- * @param string $locale
+ * @param string $locale
* @return array
*/
- public function get_grouped_payment_providers( $payment_amount = null, $locale = null) {
- $groups = [];
+ public function get_grouped_payment_providers( $payment_amount = null, $locale = null ) {
+ $groups = array();
- if ($this->helper::getIsSubscriptionsEnabled()) {
- $groups = ['creditcard'];
+ if ( $this->helper::getIsSubscriptionsEnabled() ) {
+ $groups = array( 'creditcard' );
}
try {
$providers = $this->client->getGroupedPaymentProviders(
- isset($payment_amount) ? $payment_amount : $this->get_cart_total(),
- isset($locale) ? $locale : Helper::getLocale(),
+ isset( $payment_amount ) ? $payment_amount : $this->get_cart_total(),
+ isset( $locale ) ? $locale : Helper::getLocale(),
$groups
);
- } catch (HmacException $exception) {
- $providers = $this->get_payment_providers_error_handler($exception);
- } catch (\Exception $exception) {
- $providers = $this->get_payment_providers_error_handler($exception);
+ } catch ( HmacException $exception ) {
+ $providers = $this->get_payment_providers_error_handler( $exception );
+ } catch ( \Exception $exception ) {
+ $providers = $this->get_payment_providers_error_handler( $exception );
}
return $providers;
@@ -2073,10 +2146,10 @@ public function get_grouped_payment_providers( $payment_amount = null, $locale =
* @param \Exception $exception Exception to handle.
* @return array
*/
- protected function get_payment_providers_error_handler( \Exception $exception) {
+ protected function get_payment_providers_error_handler( \Exception $exception ) {
// Log the error message.
- $this->log($exception->getMessage() . $exception->getTraceAsString(), 'error');
+ $this->log( $exception->getMessage() . $exception->getTraceAsString(), 'error' );
$error = __(
'An error occurred loading the payment providers.',
@@ -2088,10 +2161,10 @@ protected function get_payment_providers_error_handler( \Exception $exception) {
*
* @since 1.0
*/
- $error = apply_filters('paytrail_provider_form_error', $error);
- return [
+ $error = apply_filters( 'paytrail_provider_form_error', $error );
+ return array(
'error' => $error,
- ];
+ );
}
/**
@@ -2101,14 +2174,14 @@ protected function get_payment_providers_error_handler( \Exception $exception) {
* @param string $type Whether we are creating an invoicing or a delivery address.
* @return Address|null
*/
- protected function create_address( \WC_Order $order, $type = 'invoicing') {
+ protected function create_address( \WC_Order $order, $type = 'invoicing' ) {
$address = new Address();
- if (!$order) {
+ if ( ! $order ) {
return;
}
- switch ($type) {
+ switch ( $type ) {
case 'delivery':
$prefix = 'shipping_';
break;
@@ -2117,25 +2190,25 @@ protected function create_address( \WC_Order $order, $type = 'invoicing') {
break;
}
- $address_suffix = empty($order->{ 'get_' . $prefix . 'address_2' }())
+ $address_suffix = empty( $order->{ 'get_' . $prefix . 'address_2' }() )
? null : ' ' . $order->{ 'get_' . $prefix . 'address_2' }();
// Append 2nd address line to the address field if present
- $address->setStreetAddress(( $order->{ 'get_' . $prefix . 'address_1' }() . $address_suffix ))
- ->setPostalCode($order->{ 'get_' . $prefix . 'postcode' }())
- ->setCity($order->{ 'get_' . $prefix . 'city' }())
- ->setCounty($order->{ 'get_' . $prefix . 'state' }())
- ->setCountry($order->{ 'get_' . $prefix . 'country' }());
+ $address->setStreetAddress( ( $order->{ 'get_' . $prefix . 'address_1' }() . $address_suffix ) )
+ ->setPostalCode( $order->{ 'get_' . $prefix . 'postcode' }() )
+ ->setCity( $order->{ 'get_' . $prefix . 'city' }() )
+ ->setCounty( $order->{ 'get_' . $prefix . 'state' }() )
+ ->setCountry( $order->{ 'get_' . $prefix . 'country' }() );
- if (empty($address->getCountry())) {
- $address->setCountry($this->get_option('fallback_country', ''));
+ if ( empty( $address->getCountry() ) ) {
+ $address->setCountry( $this->get_option( 'fallback_country', '' ) );
}
// If we have any of the listed properties, we are good to go
$has_values = array_filter(
- [ 'StreetAddress', 'PostalCode', 'City', 'County' ],
- function ( $key) use ( $address) {
- return ! empty($address->{ 'get' . $key }());
+ array( 'StreetAddress', 'PostalCode', 'City', 'County' ),
+ function ( $key ) use ( $address ) {
+ return ! empty( $address->{ 'get' . $key }() );
}
);
@@ -2150,21 +2223,21 @@ function ( $key) use ( $address) {
*
* @return Item|null
*/
- protected function create_item( WC_Order_Item $order_item, WC_Order $order) {
+ protected function create_item( WC_Order_Item $order_item, WC_Order $order ) {
$item = new Item();
// Get the item total with taxes and without rounding.
// Then convert it into the integer format required by Paytrail.
- $sub_total = $this->helper->handle_currency($order->get_item_total($order_item, true, false));
- $item->setUnitPrice($sub_total)
- ->setUnits((int) $order_item->get_quantity());
+ $sub_total = $this->helper->handle_currency( $order->get_item_total( $order_item, true, false ) );
+ $item->setUnitPrice( $sub_total )
+ ->setUnits( (int) $order_item->get_quantity() );
- $tax_rate = $this->get_item_tax_rate($order_item);
+ $tax_rate = $this->get_item_tax_rate( $order_item );
- $item->setVatPercentage($tax_rate)
- ->setProductCode($this->get_item_product_code($order_item))
- ->setDescription($this->get_item_description($order_item))
- ->setStamp((string) $order_item->get_id());
+ $item->setVatPercentage( $tax_rate )
+ ->setProductCode( $this->get_item_product_code( $order_item ) )
+ ->setDescription( $this->get_item_description( $order_item ) )
+ ->setStamp( (string) $order_item->get_id() );
return $item;
}
@@ -2176,18 +2249,18 @@ protected function create_item( WC_Order_Item $order_item, WC_Order $order) {
*
* @return string
*/
- protected function get_item_product_code( WC_Order_Item $item) {
+ protected function get_item_product_code( WC_Order_Item $item ) {
$product_code = '';
- switch (get_class($item)) {
+ switch ( get_class( $item ) ) {
case WC_Order_Item_Product::class:
- $product_code = !empty($item->get_product()->get_sku()) ? $item->get_product()->get_sku() : $item->get_product()->get_id();
+ $product_code = ! empty( $item->get_product()->get_sku() ) ? $item->get_product()->get_sku() : $item->get_product()->get_id();
break;
case WC_Order_Item_Fee::class:
- $product_code = __('fee', 'paytrail-for-woocommerce');
+ $product_code = __( 'fee', 'paytrail-for-woocommerce' );
$item->get_type();
break;
case WC_Order_Item_Shipping::class:
- $product_code = __('shipping', 'paytrail-for-woocommerce');
+ $product_code = __( 'shipping', 'paytrail-for-woocommerce' );
break;
}
@@ -2196,7 +2269,7 @@ protected function get_item_product_code( WC_Order_Item $item) {
*
* @since 1.0
*/
- return apply_filters('paytrail_item_product_code', $product_code, $item);
+ return apply_filters( 'paytrail_item_product_code', $product_code, $item );
}
/**
@@ -2206,10 +2279,10 @@ protected function get_item_product_code( WC_Order_Item $item) {
*
* @return string
*/
- protected function get_item_description( WC_Order_Item $item) {
- switch (get_class($item)) {
+ protected function get_item_description( WC_Order_Item $item ) {
+ switch ( get_class( $item ) ) {
case WC_Order_Item_Product::class:
- $description = !empty($item->get_product()->get_name()) ? $item->get_product()->get_name() : $item->get_product()->get_id();
+ $description = ! empty( $item->get_product()->get_name() ) ? $item->get_product()->get_name() : $item->get_product()->get_id();
break;
default:
$description = $item->get_name();
@@ -2217,14 +2290,14 @@ protected function get_item_description( WC_Order_Item $item) {
}
// Ensure the description is maximum of 1000 characters long.
- $description = mb_substr($description, 0, 1000);
+ $description = mb_substr( $description, 0, 1000 );
/**
* Return item description
*
* @since 1.0
*/
- return apply_filters('paytrail_item_description', $description, $item);
+ return apply_filters( 'paytrail_item_description', $description, $item );
}
/**
@@ -2234,7 +2307,7 @@ protected function get_item_description( WC_Order_Item $item) {
*
* @return float The tax percentage.
*/
- protected function get_item_tax_rate( WC_Order_Item $item) {
+ protected function get_item_tax_rate( WC_Order_Item $item ) {
$taxes = $item->get_taxes();
$tax_total = 0;
$total_price = $item->get_total();
@@ -2243,7 +2316,7 @@ protected function get_item_tax_rate( WC_Order_Item $item) {
$tax_total += (float) $tax;
}
- if ( $total_price > 0 && $tax_total > 0) {
+ if ( $total_price > 0 && $tax_total > 0 ) {
$tax_rate = NumberUtil::round( ( $tax_total / $total_price ) * 100, self::TAX_RATE_PRECISION );
} else {
$tax_rate = 0;
@@ -2258,12 +2331,12 @@ protected function get_item_tax_rate( WC_Order_Item $item) {
* @param \WC_Order $order The order object.
* @return CallbackUrl
*/
- public function create_redirect_url( \WC_Order $order) {
+ public function create_redirect_url( \WC_Order $order ) {
$callback = new CallbackUrl();
- $callback->setSuccess($this->get_return_url($order));
- //Customers choosing cancel option will be shown a payment page to allow re-attempt to pay
- $callback->setCancel($order->get_checkout_payment_url());
+ $callback->setSuccess( $this->get_return_url( $order ) );
+ // Customers choosing cancel option will be shown a payment page to allow re-attempt to pay
+ $callback->setCancel( $order->get_checkout_payment_url() );
return $callback;
}
@@ -2275,8 +2348,8 @@ public function create_redirect_url( \WC_Order $order) {
protected function create_callback_url() {
$callback = new CallbackUrl();
- $callback->setSuccess(Router::get_url(Plugin::CALLBACK_URL, 'index'));
- $callback->setCancel(Router::get_url(Plugin::CALLBACK_URL, 'index'));
+ $callback->setSuccess( Router::get_url( Plugin::CALLBACK_URL, 'index' ) );
+ $callback->setCancel( Router::get_url( Plugin::CALLBACK_URL, 'index' ) );
return $callback;
}
@@ -2288,28 +2361,28 @@ protected function create_callback_url() {
* @param array $query_vars Query vars from WC_Order_Query.
* @return array
*/
- public function handle_custom_searches( $query, $query_vars) {
- if (! empty($query_vars['checkout_reference'])) {
- $query['meta_query'][] = [
- 'key' => '_checkout_reference_' . esc_attr($query_vars['checkout_reference']),
+ public function handle_custom_searches( $query, $query_vars ) {
+ if ( ! empty( $query_vars['checkout_reference'] ) ) {
+ $query['meta_query'][] = array(
+ 'key' => '_checkout_reference_' . esc_attr( $query_vars['checkout_reference'] ),
'compare' => 'EXISTS',
- ];
+ );
}
- if (! empty($query_vars['checkout_refund_unique_id'])) {
- $query['meta_query'][] = [
+ if ( ! empty( $query_vars['checkout_refund_unique_id'] ) ) {
+ $query['meta_query'][] = array(
'key' => '_checkout_refund_unique_id',
- 'value' => esc_attr($query_vars['checkout_refund_unique_id']),
+ 'value' => esc_attr( $query_vars['checkout_refund_unique_id'] ),
'compare' => '=',
- ];
+ );
}
return $query;
}
public function get_cart_total() {
- if (WC()->cart && is_callable([WC()->cart, 'get_total'])) {
- return (int) round(WC()->cart->get_total('edit') * 100);
+ if ( WC()->cart && is_callable( array( WC()->cart, 'get_total' ) ) ) {
+ return (int) round( WC()->cart->get_total( 'edit' ) * 100 );
}
return 0;
}
@@ -2329,7 +2402,7 @@ protected function register_scripts() {
wp_register_script(
'paytrail-woocommerce-payment-fields',
$plugin_dir_url . 'dist/assets/frontend/main.js',
- [],
+ array(),
$plugin_version
);
}
@@ -2338,9 +2411,9 @@ public function enqueue_admin_scripts() {
$screen = get_current_screen();
// Check if the current screen is the WooCommerce settings page
- if ($screen && 'woocommerce_page_wc-settings' === $screen->id) {
+ if ( $screen && 'woocommerce_page_wc-settings' === $screen->id ) {
// Enqueue the introScripts only on the WooCommerce settings page
- wp_enqueue_script('introScripts');
+ wp_enqueue_script( 'introScripts' );
}
}
@@ -2359,14 +2432,14 @@ protected function register_styles() {
wp_register_style(
'paytrail-woocommerce-payment-fields',
$plugin_dir_url . 'dist/assets/frontend/main.css',
- [],
+ array(),
$plugin_version
);
wp_register_style(
'introStyles',
$plugin_dir_url . 'dist/assets/frontend/main.css',
- [],
+ array(),
$plugin_version
);
}
@@ -2375,9 +2448,9 @@ public function enqueue_admin_styles() {
$screen = get_current_screen();
// Check if the current screen is the WooCommerce settings page
- if ($screen && 'woocommerce_page_wc-settings' === $screen->id) {
+ if ( $screen && 'woocommerce_page_wc-settings' === $screen->id ) {
// Enqueue the style 'paytrail-woocommerce-payment-fields'
- wp_enqueue_style('introStyles');
+ wp_enqueue_style( 'introStyles' );
}
}
@@ -2388,15 +2461,15 @@ public function enqueue_admin_styles() {
* @param string $level Log level. Defaults to 'info'. Possible values:
* emergency|alert|critical|error|warning|notice|info|debug.
*/
- public function log( $message, $level = 'info') {
- if ($this->debug) {
- if (empty($this->logger)) {
+ public function log( $message, $level = 'info' ) {
+ if ( $this->debug ) {
+ if ( empty( $this->logger ) ) {
$this->logger = \wc_get_logger();
}
- $context = [ 'source' => Plugin::GATEWAY_ID ];
+ $context = array( 'source' => Plugin::GATEWAY_ID );
- $this->logger->log($level, $message, $context);
+ $this->logger->log( $level, $message, $context );
}
}
@@ -2408,22 +2481,22 @@ public function log( $message, $level = 'info') {
* @param bool $die Defines if the process should be terminated.
* @throws \Exception If the process is not killed, the error is passed on.
*/
- protected function error( \Exception $exception, $message, $die = true) {
+ protected function error( \Exception $exception, $message, $die = true ) {
$glue = PHP_EOL . '- ';
$log_message = $message . $glue;
- $this->log($log_message . PHP_EOL . $exception->getTraceAsString(), 'error');
+ $this->log( $log_message . PHP_EOL . $exception->getTraceAsString(), 'error' );
/**
* You can use this filter to modify the error message.
*
* @since 1.0
*/
- $error = apply_filters('paytrail_error_message', $message, $exception);
+ $error = apply_filters( 'paytrail_error_message', $message, $exception );
- if (true === $die) {
- wp_die(esc_html($error), '', esc_html($exception->getCode()));
+ if ( true === $die ) {
+ wp_die( esc_html( $error ), '', esc_html( $exception->getCode() ) );
} else {
throw $exception;
}
@@ -2435,7 +2508,7 @@ protected function error( \Exception $exception, $message, $die = true) {
* @param HmacException $exception The exception instance.
* @param bool $die Defines if the process should be terminated.
*/
- protected function signature_error( HmacException $exception, $die = true) {
+ protected function signature_error( HmacException $exception, $die = true ) {
$message = __(
'An error occurred validating the signature.',
'paytrail-for-woocommerce'
@@ -2446,8 +2519,8 @@ protected function signature_error( HmacException $exception, $die = true) {
*
* @since 1.0
*/
- $message = apply_filters('paytrail_signature_error', $message, $exception);
+ $message = apply_filters( 'paytrail_signature_error', $message, $exception );
- $this->error($exception, $message, $die);
+ $this->error( $exception, $message, $die );
}
}
diff --git a/src/Helper.php b/src/Helper.php
index d701d659..414b47df 100644
--- a/src/Helper.php
+++ b/src/Helper.php
@@ -16,18 +16,18 @@ class Helper {
* @return bool
*/
public static function getIsSubscriptionsEnabled() {
- if (!class_exists('WC_Subscriptions_Cart')) {
+ if ( ! class_exists( 'WC_Subscriptions_Cart' ) ) {
return false;
}
- if (!class_exists('WC_Subscriptions_Change_Payment_Gateway')) {
+ if ( ! class_exists( 'WC_Subscriptions_Change_Payment_Gateway' ) ) {
return false;
}
- if (!function_exists('wcs_cart_contains_renewal')) {
+ if ( ! function_exists( 'wcs_cart_contains_renewal' ) ) {
return false;
}
- if (class_exists('\WC_Subscriptions_Admin')) {
- $accept_manual_renewals = ( 'no' !== get_option(\WC_Subscriptions_Admin::$option_prefix . '_accept_manual_renewals', 'no') );
- if (true == $accept_manual_renewals) {
+ if ( class_exists( '\WC_Subscriptions_Admin' ) ) {
+ $accept_manual_renewals = ( 'no' !== get_option( \WC_Subscriptions_Admin::$option_prefix . '_accept_manual_renewals', 'no' ) );
+ if ( true == $accept_manual_renewals ) {
return false;
}
}
@@ -35,12 +35,12 @@ public static function getIsSubscriptionsEnabled() {
return (
\WC_Subscriptions_Cart::cart_contains_subscription() ||
wcs_cart_contains_renewal() ||
- filter_input(INPUT_GET, 'change_payment_method')
+ filter_input( INPUT_GET, 'change_payment_method' )
);
}
public static function getIsChangeSubscriptionPaymentMethod() {
- return filter_input(INPUT_GET, 'change_payment_method');
+ return filter_input( INPUT_GET, 'change_payment_method' );
}
/**
@@ -49,8 +49,8 @@ public static function getIsChangeSubscriptionPaymentMethod() {
* @param int|double $sum The sum to format.
* @return integer
*/
- public function handle_currency( $sum) {
- return round($sum*100);
+ public function handle_currency( $sum ) {
+ return round( $sum * 100 );
}
/**
@@ -61,16 +61,16 @@ public function handle_currency( $sum) {
public function get_cart_total() {
$sum = WC()->cart->total;
- return $this->handle_currency($sum);
+ return $this->handle_currency( $sum );
}
public static function getLocale() {
$full_locale = get_locale();
- $short_locale = substr($full_locale, 0, 2);
+ $short_locale = substr( $full_locale, 0, 2 );
// Get and assign the WordPress locale
- switch ($short_locale) {
+ switch ( $short_locale ) {
case 'sv':
$locale = 'SV';
break;
@@ -91,8 +91,7 @@ public static function getLocale() {
*
* @return string
*/
- public function generate_item_stamp ( $order_id) {
- return uniqid($order_id . '-', true);
+ public function generate_item_stamp( $order_id ) {
+ return uniqid( $order_id . '-', true );
}
-
}
diff --git a/src/Model/MetaBox.php b/src/Model/MetaBox.php
new file mode 100644
index 00000000..ee4cf829
--- /dev/null
+++ b/src/Model/MetaBox.php
@@ -0,0 +1,157 @@
+order = $order;
+ }
+
+ /**
+ * Retrieves the Paytrail order status.
+ *
+ * @return array|null The Paytrail order status.
+ */
+ public function get_status() {
+ if ( empty( $this->status ) ) {
+
+ if ( empty( $this->payment_status ) ) {
+ $this->payment_status = $this->get_payment_status();
+ }
+ $this->status = empty( $this->payment_status ) ? null : $this->payment_status->getStatus();
+ }
+
+ return $this->status;
+ }
+
+ /**
+ * Retrieves the Paytrail order amount.
+ *
+ * @return string The Paytrail order amount.
+ */
+ public function get_amount() {
+ if ( null === $this->amount ) {
+
+ if ( empty( $this->payment_status ) ) {
+ $this->payment_status = $this->get_payment_status();
+ }
+ $this->amount = empty( $this->payment_status ) ? null : $this->payment_status->getAmount();
+ }
+
+ return $this->amount;
+ }
+
+ /**
+ * Retrieves the WC order currency.
+ *
+ * @return string The WC order currency.
+ */
+ public function get_currency() {
+ if ( empty( $this->currency ) ) {
+ $this->currency = $this->order->get_currency();
+ }
+
+ return $this->currency;
+ }
+
+ /**
+ * Retrieves the Paytrail transaction ID.
+ *
+ * @return string The Paytrail transaction ID.
+ */
+ public function get_transaction_id() {
+ // The Paytrail transaction ID is stored as the order's transaction ID. We don't need to fetch it from Paytrail.
+ if ( empty( $this->transaction_id ) ) {
+ $this->transaction_id = $this->order->get_transaction_id();
+ }
+
+ return $this->transaction_id;
+ }
+
+ /**
+ * Get the Payment status from Paytrail.
+ *
+ * @return PaymentStatusResponse|null
+ */
+ public function get_payment_status() {
+ $gateway = Plugin::instance()->gateway();
+
+ $request = new PaymentStatusRequest();
+ $request->setTransactionId( $this->order->get_transaction_id() );
+
+ $client = $gateway->get_client();
+ try {
+ $response = $client->getPaymentStatus( $request );
+ // Log the retrieved response for debugging purposes.
+ Plugin::instance()->gateway()->log( PaymentStatusRequest::class . ' retrieved: ' . $response->getTransactionId() . ', status: ' . $response->getStatus() . ', amount: ' . $response->getAmount() );
+ if ( $response->getTransactionId() === $this->order->get_transaction_id() ) {
+ return $response;
+ }
+ } catch ( \Exception $e ) {
+ Plugin::instance()->gateway()->log( 'Error retrieving ' . PaymentStatusRequest::class . ': ' . $e->getMessage(), 'error' );
+ return null;
+ }
+
+ return null;
+ }
+}
diff --git a/src/Model/PaymentSubscriptionMigration.php b/src/Model/PaymentSubscriptionMigration.php
index cdacb305..9300fa42 100644
--- a/src/Model/PaymentSubscriptionMigration.php
+++ b/src/Model/PaymentSubscriptionMigration.php
@@ -14,17 +14,18 @@ class PaymentSubscriptionMigration implements MigrationInterface {
protected $subscriptions;
public function __construct() {
- if (function_exists('wcs_get_subscriptions')) {
+ if ( function_exists( 'wcs_get_subscriptions' ) ) {
$this->subscriptions = wcs_get_subscriptions(
- ['subscriptions_per_page' => -1,
- 'meta_query' => [
- [
+ array(
+ 'subscriptions_per_page' => -1,
+ 'meta_query' => array(
+ array(
'key' => '_payment_method',
'value' => 'checkout_finland',
- 'compare' => '='
- ]
- ]
- ]
+ 'compare' => '=',
+ ),
+ ),
+ )
);
}
}
@@ -33,12 +34,12 @@ public function __construct() {
* Executes migration for Subscriptions
*/
public function execute() {
- if (empty($this->subscriptions)) {
+ if ( empty( $this->subscriptions ) ) {
return;
}
- foreach ($this->subscriptions as $subscription) {
- $subscription->set_payment_method('paytrail');
- $subscription->set_payment_method_title('Paytrail for Woocommerce');
+ foreach ( $this->subscriptions as $subscription ) {
+ $subscription->set_payment_method( 'paytrail' );
+ $subscription->set_payment_method_title( 'Paytrail for Woocommerce' );
$subscription->save();
}
}
diff --git a/src/Model/PaymentTokenMigration.php b/src/Model/PaymentTokenMigration.php
index 32a01a84..1a65bfcc 100644
--- a/src/Model/PaymentTokenMigration.php
+++ b/src/Model/PaymentTokenMigration.php
@@ -14,18 +14,18 @@ class PaymentTokenMigration implements MigrationInterface {
protected $tokens;
public function __construct() {
- $this->tokens = \WC_Payment_Tokens::get_tokens(['gateway_id' => 'checkout_finland']);
+ $this->tokens = \WC_Payment_Tokens::get_tokens( array( 'gateway_id' => 'checkout_finland' ) );
}
/**
* Executes migration for subscriptions
*/
public function execute() {
- if (empty($this->tokens)) {
+ if ( empty( $this->tokens ) ) {
return;
}
- foreach ($this->tokens as $token) {
- $token->set_gateway_id('paytrail');
+ foreach ( $this->tokens as $token ) {
+ $token->set_gateway_id( 'paytrail' );
$token->save();
}
}
diff --git a/src/PaytrailBlocks.php b/src/PaytrailBlocks.php
index 753dd58d..84037d3f 100644
--- a/src/PaytrailBlocks.php
+++ b/src/PaytrailBlocks.php
@@ -22,14 +22,14 @@ class Paytrail_Blocks_Support extends AbstractPaymentMethodType {
* Constructor.
*/
public function __construct() {
- add_action( 'woocommerce_rest_checkout_process_payment_with_context', [ $this, 'add_payment_request_order_meta' ], 8, 2 );
+ add_action( 'woocommerce_rest_checkout_process_payment_with_context', array( $this, 'add_payment_request_order_meta' ), 8, 2 );
}
/**
* Initialize the payment method settings.
*/
public function initialize() {
- $this->settings = get_option( 'woocommerce_paytrail_settings', [] );
+ $this->settings = get_option( 'woocommerce_paytrail_settings', array() );
}
/**
@@ -73,14 +73,14 @@ private function get_gateway() {
* @return array Script handles.
*/
public function get_payment_method_script_handles() {
- $script_handles = [];
+ $script_handles = array();
$script_path = '/dist/assets/frontend/blocks.js';
$script_asset_path = \Paytrail\WooCommercePaymentGateway\Plugin::plugin_abspath() . 'dist/assets/frontend/blocks.asset.php';
- $script_asset = file_exists( $script_asset_path ) ? require $script_asset_path : [
- 'dependencies' => [],
+ $script_asset = file_exists( $script_asset_path ) ? require $script_asset_path : array(
+ 'dependencies' => array(),
'version' => \Paytrail\WooCommercePaymentGateway\Plugin::$version,
- ];
+ );
$script_url = \Paytrail\WooCommercePaymentGateway\Plugin::plugin_url() . $script_path;
wp_register_script(
@@ -98,9 +98,9 @@ public function get_payment_method_script_handles() {
}
// Register OP Lasku scripts on cart page
- if (is_cart()) {
- $settings = get_option('woocommerce_paytrail_settings');
- if (isset($settings['op_lasku_calculator']) && 'yes' === $settings['op_lasku_calculator']) {
+ if ( is_cart() ) {
+ $settings = get_option( 'woocommerce_paytrail_settings' );
+ if ( isset( $settings['op_lasku_calculator'] ) && 'yes' === $settings['op_lasku_calculator'] ) {
OPLasku::register_blocks_cart_scripts();
$script_handles[] = 'paytrail-op-lasku-helper-blocks';
}
@@ -120,7 +120,7 @@ public function add_payment_request_order_meta( PaymentContext $context, Payment
if ( $context->payment_method !== $this->name ) {
return;
}
-
+
$payment_data = $context->payment_data;
$gateway = $this->get_gateway();
@@ -138,9 +138,9 @@ public function add_payment_request_order_meta( PaymentContext $context, Payment
} else {
$result->set_status( 'failure' );
$result->set_payment_details(
- [
+ array(
'error_message' => __( 'Payment failed, please try again.', 'paytrail-for-woocommerce' ),
- ]
+ )
);
}
@@ -152,21 +152,21 @@ public function add_payment_request_order_meta( PaymentContext $context, Payment
$payment_result = $gateway->process_paytrail_payment(
$context->order,
null,
- !empty($payment_data['payment_provider'])
- ? $payment_data['payment_provider']
+ ! empty( $payment_data['payment_provider'] )
+ ? $payment_data['payment_provider']
: $payment_data['payment_method'],
false
);
-
+
if ( 'success' === $payment_result['result'] ) {
$result->set_status( 'success' );
$result->set_redirect_url( $payment_result['redirect'] );
} else {
$result->set_status( 'failure' );
$result->set_payment_details(
- [
+ array(
'error_message' => __( 'Payment failed, please try again.', 'paytrail-for-woocommerce' ),
- ]
+ )
);
}
@@ -181,18 +181,18 @@ public function add_payment_request_order_meta( PaymentContext $context, Payment
public function get_payment_method_style_handles() {
$style_handle = 'paytrail-woocommerce-payment-fields';
$blocks_style_handle = 'paytrail-woocommerce-blocks-style';
- $blocks_css_url = plugins_url( 'dist/assets/frontend/blocks.css', dirname( __FILE__ ) );
- $blocks_css_file = plugin_dir_path( dirname( __FILE__ ) ) . 'dist/assets/frontend/blocks.css';
+ $blocks_css_url = plugins_url( 'dist/assets/frontend/blocks.css', __DIR__ );
+ $blocks_css_file = plugin_dir_path( __DIR__ ) . 'dist/assets/frontend/blocks.css';
if ( ! wp_style_is( $style_handle, 'enqueued' ) ) {
wp_enqueue_style( $style_handle );
}
if ( ! wp_style_is( $blocks_style_handle, 'enqueued' ) ) {
- wp_enqueue_style( $blocks_style_handle, $blocks_css_url, [], filemtime( $blocks_css_file ) );
+ wp_enqueue_style( $blocks_style_handle, $blocks_css_url, array(), filemtime( $blocks_css_file ) );
}
- return [ $style_handle, $blocks_style_handle ];
+ return array( $style_handle, $blocks_style_handle );
}
/**
@@ -213,37 +213,37 @@ public function is_active() {
public function get_payment_method_data( $context = null ) {
$gateway = $this->get_gateway();
if ( ! $this->is_provider_selection_enabled() ) {
- return [
+ return array(
'title' => $gateway->title,
'description' => $gateway->description,
- 'supports' => array_filter( $gateway->supports, [ $gateway, 'supports' ] ),
- 'groups' => [],
+ 'supports' => array_filter( $gateway->supports, array( $gateway, 'supports' ) ),
+ 'groups' => array(),
'terms' => '',
'no_providers' => true,
- ];
+ );
}
$grouped_providers = $gateway->get_grouped_payment_providers();
$this->get_payment_method_style_handles();
$tokens = WC_Payment_Tokens::get_customer_tokens( get_current_user_id() );
- return [
+ return array(
'title' => $gateway->title,
'description' => $gateway->description,
- 'supports' => array_filter( $gateway->supports, [ $gateway, 'supports' ] ),
- 'groups' => isset($grouped_providers['groups']) ? $grouped_providers['groups'] : [],
- 'terms' => isset($grouped_providers['terms']) ? $grouped_providers['terms'] : '',
+ 'supports' => array_filter( $gateway->supports, array( $gateway, 'supports' ) ),
+ 'groups' => isset( $grouped_providers['groups'] ) ? $grouped_providers['groups'] : array(),
+ 'terms' => isset( $grouped_providers['terms'] ) ? $grouped_providers['terms'] : '',
'saved_payment_methods' => ! empty( $tokens ) ? array_map(
function ( $token ) {
- return [
+ return array(
'id' => $token->get_id(),
'last4' => $token->get_last4(),
'expiry' => $token->get_expiry_month() . '/' . $token->get_expiry_year(),
'type' => $token->get_card_type(),
- ];
+ );
},
$tokens
- ) : [],
- ];
+ ) : array(),
+ );
}
}
diff --git a/src/Providers/OPLasku.php b/src/Providers/OPLasku.php
index 87774756..918e7b32 100644
--- a/src/Providers/OPLasku.php
+++ b/src/Providers/OPLasku.php
@@ -12,23 +12,27 @@ class OPLasku {
public function __construct() {
// Hooks for product and classic cart page
- add_action('woocommerce_before_add_to_cart_form', array($this, 'product_page'));
- add_action('woocommerce_proceed_to_checkout', array($this, 'cart_page'));
+ add_action( 'woocommerce_before_add_to_cart_form', array( $this, 'product_page' ) );
+ add_action( 'woocommerce_proceed_to_checkout', array( $this, 'cart_page' ) );
// Register scripts and styles
- add_action('wp_enqueue_scripts', array($this, 'register_scripts'));
- //Enqueue blocks cart scripts and styles
- add_action('woocommerce_blocks_cart_enqueue_data', array($this, 'enqueue_blocks_cart_assets'));
+ add_action( 'wp_enqueue_scripts', array( $this, 'register_scripts' ) );
+ // Enqueue blocks cart scripts and styles
+ add_action( 'woocommerce_blocks_cart_enqueue_data', array( $this, 'enqueue_blocks_cart_assets' ) );
}
/**
* Enqueue assets for blocks cart
*/
public function enqueue_blocks_cart_assets() {
- wp_enqueue_script('paytrail-op-lasku');
- wp_enqueue_style('paytrail-op-lasku');
- wp_localize_script('paytrail-op-lasku', 'op_lasku_data', array(
- 'language' => esc_js($this->get_language()),
- ));
+ wp_enqueue_script( 'paytrail-op-lasku' );
+ wp_enqueue_style( 'paytrail-op-lasku' );
+ wp_localize_script(
+ 'paytrail-op-lasku',
+ 'op_lasku_data',
+ array(
+ 'language' => esc_js( $this->get_language() ),
+ )
+ );
}
/**
@@ -37,10 +41,10 @@ public function enqueue_blocks_cart_assets() {
public static function register_blocks_cart_scripts() {
$op_lasku_script_path = '/dist/assets/frontend/op-lasku-helper-blocks.js';
$op_lasku_script_asset_path = \Paytrail\WooCommercePaymentGateway\Plugin::plugin_abspath() . 'dist/assets/frontend/op-lasku-helper-blocks.asset.php';
- $op_lasku_script_asset = file_exists($op_lasku_script_asset_path) ? require $op_lasku_script_asset_path : [
- 'dependencies' => [],
+ $op_lasku_script_asset = file_exists( $op_lasku_script_asset_path ) ? require $op_lasku_script_asset_path : array(
+ 'dependencies' => array(),
'version' => \Paytrail\WooCommercePaymentGateway\Plugin::$version,
- ];
+ );
$op_lasku_script_url = \Paytrail\WooCommercePaymentGateway\Plugin::plugin_url() . $op_lasku_script_path;
wp_register_script(
'paytrail-op-lasku-helper-blocks',
@@ -55,49 +59,57 @@ public static function register_blocks_cart_scripts() {
* Register scripts for product and classic cart page
*/
public function register_scripts() {
- wp_register_script('paytrail-op-lasku', Plugin::plugin_url() . '/assets/op-lasku-assets/op-lasku-widget.js', [], Plugin::$version, true);
- wp_register_script('paytrail-op-lasku-helper', Plugin::plugin_url() . '/assets/op-lasku-assets/op-lasku-helper.js', array('jquery'), Plugin::$version, true);
- wp_register_style('paytrail-op-lasku', Plugin::plugin_url() . '/assets/op-lasku-assets/op-lasku-widget.css', [], Plugin::$version);
+ wp_register_script( 'paytrail-op-lasku', Plugin::plugin_url() . '/assets/op-lasku-assets/op-lasku-widget.js', array(), Plugin::$version, true );
+ wp_register_script( 'paytrail-op-lasku-helper', Plugin::plugin_url() . '/assets/op-lasku-assets/op-lasku-helper.js', array( 'jquery' ), Plugin::$version, true );
+ wp_register_style( 'paytrail-op-lasku', Plugin::plugin_url() . '/assets/op-lasku-assets/op-lasku-widget.css', array(), Plugin::$version );
}
/**
* Display OP Lasku calculator in the product page
*/
public function product_page() {
- global $product;
- if (!$product) {
+ global $product;
+ if ( ! $product ) {
return;
}
$this->product_price = $product->get_price() ? $product->get_price() : 0;
- wp_enqueue_script('paytrail-op-lasku');
- wp_enqueue_script('paytrail-op-lasku-helper');
- wp_enqueue_style('paytrail-op-lasku');
-
- wp_localize_script('paytrail-op-lasku', 'op_lasku_data', array(
- 'product_price' => esc_js($this->product_price),
- 'language' => esc_js($this->get_language()),
- ));
+ wp_enqueue_script( 'paytrail-op-lasku' );
+ wp_enqueue_script( 'paytrail-op-lasku-helper' );
+ wp_enqueue_style( 'paytrail-op-lasku' );
+
+ wp_localize_script(
+ 'paytrail-op-lasku',
+ 'op_lasku_data',
+ array(
+ 'product_price' => esc_js( $this->product_price ),
+ 'language' => esc_js( $this->get_language() ),
+ )
+ );
- echo wp_kses_post('');
+ echo wp_kses_post( '' );
}
/**
* Display OP Lasku calculator in the cart page
*/
public function cart_page() {
- $this->cart_total = WC()->cart ? WC()->cart->get_total('raw') : 0;
-
- wp_enqueue_script('paytrail-op-lasku');
- wp_enqueue_script('paytrail-op-lasku-helper');
- wp_enqueue_style('paytrail-op-lasku');
-
- wp_localize_script('paytrail-op-lasku', 'op_lasku_data', array(
- 'cart_total' => esc_js($this->cart_total),
- 'language' => esc_js($this->get_language()),
- ));
- echo wp_kses_post('');
+ $this->cart_total = WC()->cart ? WC()->cart->get_total( 'raw' ) : 0;
+
+ wp_enqueue_script( 'paytrail-op-lasku' );
+ wp_enqueue_script( 'paytrail-op-lasku-helper' );
+ wp_enqueue_style( 'paytrail-op-lasku' );
+
+ wp_localize_script(
+ 'paytrail-op-lasku',
+ 'op_lasku_data',
+ array(
+ 'cart_total' => esc_js( $this->cart_total ),
+ 'language' => esc_js( $this->get_language() ),
+ )
+ );
+ echo wp_kses_post( '' );
}
/**
@@ -106,10 +118,10 @@ public function cart_page() {
* @return string
*/
public static function settings_title() {
- $icon_url = sprintf('%s/assets/img/icon_oplasku_admin.svg', Plugin::plugin_url());
+ $icon_url = sprintf( '%s/assets/img/icon_oplasku_admin.svg', Plugin::plugin_url() );
return sprintf(
- __('OP Lasku', 'paytrail-for-woocommerce') . '
',
- esc_url($icon_url)
+ __( 'OP Lasku', 'paytrail-for-woocommerce' ) . '
',
+ esc_url( $icon_url )
);
}
@@ -119,8 +131,8 @@ public static function settings_title() {
* @return string
*/
protected function get_language() {
- $locale = strtolower(Helper::getLocale());
- if ('sv' === $locale) {
+ $locale = strtolower( Helper::getLocale() );
+ if ( 'sv' === $locale ) {
$locale = 'se';
}
return $locale;
diff --git a/src/Router.php b/src/Router.php
index 539a446e..b8bdb66c 100644
--- a/src/Router.php
+++ b/src/Router.php
@@ -20,8 +20,8 @@ class Router {
* Router constructor.
*/
public function __construct() {
- add_filter('init', [$this, 'register_rewrites']);
- add_filter('template_include', [$this, 'routes']);
+ add_filter( 'init', array( $this, 'register_rewrites' ) );
+ add_filter( 'template_include', array( $this, 'routes' ) );
}
/**
@@ -31,13 +31,13 @@ public function __construct() {
* @param $action
* @return string
*/
- public static function get_url( $route, $action) {
- $home_url = esc_url(home_url('/'));
- $base_url = Plugin::BASE_URL;
- $route_base_url = self::ROUTE_BASE_URL;
+ public static function get_url( $route, $action ) {
+ $home_url = esc_url( home_url( '/' ) );
+ $base_url = Plugin::BASE_URL;
+ $route_base_url = self::ROUTE_BASE_URL;
$action_base_url = self::ACTION_BASE_URL;
- if (!get_option('permalink_structure')) {
+ if ( ! get_option( 'permalink_structure' ) ) {
return "{$home_url}index.php?{$route_base_url}={$route}&{$action_base_url}={$action}";
}
@@ -48,12 +48,12 @@ public static function get_url( $route, $action) {
* Register router rewrites
*/
public function register_rewrites() {
- $base_url = Plugin::BASE_URL;
+ $base_url = Plugin::BASE_URL;
$action_base_url = self::ACTION_BASE_URL;
- $route_base_url = self::ROUTE_BASE_URL;
- add_rewrite_rule('paytrail/([^/]*)/([^/]*)/?$', 'index.php?' . $route_base_url . '=$matches[1]&' . $action_base_url . '=$matches[2]', 'top');
- add_rewrite_tag("%$route_base_url%", '([^&]+)');
- add_rewrite_tag("%$action_base_url%", '([^&]+)');
+ $route_base_url = self::ROUTE_BASE_URL;
+ add_rewrite_rule( 'paytrail/([^/]*)/([^/]*)/?$', 'index.php?' . $route_base_url . '=$matches[1]&' . $action_base_url . '=$matches[2]', 'top' );
+ add_rewrite_tag( "%$route_base_url%", '([^&]+)' );
+ add_rewrite_tag( "%$action_base_url%", '([^&]+)' );
}
/**
@@ -62,14 +62,14 @@ public function register_rewrites() {
* @param $template
* @return mixed
*/
- public function routes( $template) {
- $route = get_query_var(self::ROUTE_BASE_URL);
+ public function routes( $template ) {
+ $route = get_query_var( self::ROUTE_BASE_URL );
- if (!$route) {
+ if ( ! $route ) {
return $template;
}
- $action = !empty(get_query_var(self::ACTION_BASE_URL)) ? get_query_var(self::ACTION_BASE_URL) : 'index';
- switch ($route) {
+ $action = ! empty( get_query_var( self::ACTION_BASE_URL ) ) ? get_query_var( self::ACTION_BASE_URL ) : 'index';
+ switch ( $route ) {
case Plugin::ADD_CARD_REDIRECT_SUCCESS_URL:
$controller = new CardSuccess();
break;
@@ -83,10 +83,10 @@ public function routes( $template) {
$controller = new Callback();
break;
default:
- echo esc_html('Route did not match');
+ echo esc_html( 'Route did not match' );
}
- $controller->execute($action);
+ $controller->execute( $action );
return $template;
}
diff --git a/src/View.php b/src/View.php
index 0698ebf8..69defe5d 100644
--- a/src/View.php
+++ b/src/View.php
@@ -29,8 +29,8 @@ class View {
*
* @param string $template The template to render.
*/
- public function __construct( $template) {
- $this->template = $this->get_template_path($template);
+ public function __construct( $template ) {
+ $this->template = $this->get_template_path( $template );
}
/**
@@ -39,7 +39,7 @@ public function __construct( $template) {
* @param mixed $data The data to render the view with.
* @return void
*/
- public function render( $data = null) {
+ public function render( $data = null ) {
// @codingStandardsIgnoreLine
require $this->template;
}
@@ -52,7 +52,7 @@ public function render( $data = null) {
*
* @throws \Exception An exception if the template file given was not found.
*/
- protected function get_template_path( $template) {
+ protected function get_template_path( $template ) {
$plugin_instance = Plugin::instance();
$plugin_dir = $plugin_instance->get_plugin_dir();
@@ -60,10 +60,10 @@ protected function get_template_path( $template) {
$templateFile = $plugin_dir . '/src/View/' . $template . '.php';
// Check the existence of the template.
- if (file_exists($templateFile)) {
+ if ( file_exists( $templateFile ) ) {
return $templateFile;
} else {
- throw new \Exception("Template $template ($templateFile) could not be found.");
+ throw new \Exception( "Template $template ($templateFile) could not be found." );
}
}
}
diff --git a/src/View/CheckoutForm.php b/src/View/CheckoutForm.php
index 94462cb7..b81069d9 100644
--- a/src/View/CheckoutForm.php
+++ b/src/View/CheckoutForm.php
@@ -4,27 +4,30 @@
*/
// Ensure that the file is being run within the WordPress context.
-if (! defined('ABSPATH')) {
+if ( ! defined( 'ABSPATH' ) ) {
die;
}
?>
-