Skip to content

Instantly share code, notes, and snippets.

@apkoponen
Created June 4, 2015 11:57
Show Gist options
  • Select an option

  • Save apkoponen/e1aab484e18fbea01db0 to your computer and use it in GitHub Desktop.

Select an option

Save apkoponen/e1aab484e18fbea01db0 to your computer and use it in GitHub Desktop.
Fixed WooCommerce gateway main file
<?php
/**
* Plugin Name: WooCommerce Paytrail Gateway
* Plugin URI: http://www.woothemes.com/products/suomen-verkkomaksut-gateway/
* Description: Accept payment in WooCommerce with the Paytrail gateway. Fixed by Valu.
* Author: SkyVerge
* Author URI: http://www.skyverge.com
* Version: 100.3.1
* Text Domain: woocommerce-gateway-paytrail
* Domain Path: /i18n/languages/
*
* Copyright: (c) 2011-2014 SkyVerge, Inc. ([email protected])
*
* License: GNU General Public License v3.0
* License URI: http://www.gnu.org/licenses/gpl-3.0.html
*
* @package WC-Paytrail
* @author SkyVerge
* @category Payment-Gateways
* @copyright Copyright (c) 2011-2015, SkyVerge, Inc.
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
// Required functions
if ( ! function_exists( 'woothemes_queue_update' ) ) {
require_once( 'woo-includes/woo-functions.php' );
}
// Plugin updates
woothemes_queue_update( plugin_basename( __FILE__ ), 'e09af7e519e970419cc6407165b51575', '18628' );
// Required library files
require_once( 'lib/Verkkomaksut_Module_Rest.php' );
require_once( 'lib/class-sv-wc-gateway-paytrail-plugin-compatibility.php' );
add_action( 'plugins_loaded', 'init_paytrail', 0 );
function init_paytrail() {
// Execute only if WooCommerce is enabled
if ( ! class_exists( 'WC_Payment_Gateway' ) ) { return; }
else {
/**
* Localisation
*/
load_plugin_textdomain( 'woocommerce-gateway-paytrail', false, dirname( plugin_basename( __FILE__ ) ) . '/i18n/languages');
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'paytrail_action_links' );
/**
* action_links function.
*/
function paytrail_action_links( $links ) {
$plugin_links = array(
'<a href="' . SV_WC_Gateway_Paytrail_Plugin_Compatibility::get_payment_gateway_configuration_url( 'WC_Gateway_Paytrail' ) . '">' . __( 'Settings', 'woocommerce-gateway-paytrail' ) . '</a>',
'<a href="http://docs.woothemes.com/document/suomen-verkkomaksut/">' . __( 'Docs', 'woocommerce-gateway-paytrail' ) . '</a>',
'<a href="http://support.woothemes.com/">' . __( 'Support', 'woocommerce-gateway-paytrail' ) . '</a>',
);
return array_merge( $plugin_links, $links );
}
define( 'WC_PAYTRAIL_VERSION', '1.3.0' );
// install
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
$installed_version = get_option( 'wc_paytrail_version' );
// installed version lower than plugin version?
if ( version_compare( $installed_version, WC_PAYTRAIL_VERSION, '<' ) ) {
if ( ! $installed_version ) {
// install
// Is this actually an upgrade from the previous plugin name of Suomen Verkkomaksut? Update the settings
$settings = get_option( 'woocommerce_suomen_verkkomaksut_settings' );
if ( $settings ) {
$settings['title'] = str_ireplace( 'Suomen Verkkomaksut', 'Paytrail', $settings['title'] );
$settings['description'] = str_ireplace( 'Suomen Verkkomaksut', 'Paytrail', $settings['description'] );
delete_option( 'woocommerce_suomen_verkkomaksut_settings' );
update_option( 'woocommerce_paytrail_settings', $settings );
}
} else {
// upgrade
}
// new version number
update_option( 'wc_paytrail_version', WC_PAYTRAIL_VERSION );
}
}
/**
* Paytrail extends default WooCommerce Payment Gateway class
*/
class WC_Gateway_Paytrail extends WC_Payment_Gateway {
public function __construct() {
$this->id = 'paytrail';
$this->method_title = __( 'Paytrail', 'woocommerce-gateway-paytrail' );
$this->icon = plugins_url( '/assets/images/paytrail.png', __FILE__ );
$this->has_fields = false;
// Load the form fields.
$this->init_form_fields();
// Load the settings.
$this->init_settings();
// Define user set variables
$this->title = $this->settings['title'];
$this->description = $this->settings['description'];
$this->merchant_id = $this->settings['merchant_id'];
$this->merchant_secret = $this->settings['merchant_secret'];
$this->extended_info = $this->settings['extended_info'];
$this->debug = isset( $this->settings['debug'] ) ? $this->settings['debug'] : 'no';
// Logs
if ( 'yes' == $this->debug ) {
$this->log = new WC_Logger();
}
// Actions
add_action( 'woocommerce_api_wc_gateway_paytrail', array( $this, 'check_paytrail_response' ) );
add_action( 'valid_paytrail_payment', array( $this, 'successful_request' ) );
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
add_action( 'woocommerce_receipt_' . $this->id, create_function( '$order', 'echo "<p>" . __( "Thank you for your order.", "woocommerce-gateway-paytrail" ) . "</p>";' ) );
}
/**
* Initialise Gateway Settings Form Fields
*/
function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'woocommerce-gateway-paytrail' ),
'type' => 'checkbox',
'label' => __( 'Enable Paytrail', 'woocommerce-gateway-paytrail' ),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Title', 'woocommerce-gateway-paytrail' ),
'type' => 'text',
'description' => __( 'This controls the title which the user sees during checkout.', 'woocommerce-gateway-paytrail' ),
'default' => __( 'Pay with Paytrail', 'woocommerce-gateway-paytrail' )
),
'description' => array(
'title' => __( 'Description', 'woocommerce-gateway-paytrail' ),
'type' => 'textarea',
'description' => __( 'This controls the description which the user sees during checkout.', 'woocommerce-gateway-paytrail' ),
'default' => 'Pay via Paytrail. You can pay with online bank account or with a credit card.',
),
'merchant_id' => array(
'title' => __( 'Merchant ID', 'woocommerce-gateway-paytrail' ),
'type' => 'text',
'description' => __( 'Please enter your Paytrail merchant id; this is needed in order to take payment.', 'woocommerce-gateway-paytrail' ),
'default' => ''
),
'merchant_secret' => array(
'title' => __( 'Merchant Secret', 'woocommerce-gateway-paytrail' ),
'type' => 'password',
'description' => __( 'Please enter your Paytrail merchant secret; this is needed in order to take payment.', 'woocommerce-gateway-paytrail' ),
'default' => ''
),
'extended_info' => array(
'title' => __( 'Use extended info', 'woocommerce-gateway-paytrail' ),
'type' => 'checkbox',
'label' => __( 'Enable extended info', 'woocommerce-gateway-paytrail' ),
'description' => __( 'When activated plugin will send extended user info to Paytrail instead of just sending the amount of payment.', 'woocommerce-gateway-paytrail'),
'default' => 'yes'
),
'debug' => array(
'title' => __( 'Debug Log', 'woocommerce-gateway-paytrail' ),
'type' => 'checkbox',
'label' => __( 'Enable logging', 'woocommerce-gateway-paytrail' ),
'default' => 'no',
'description' => sprintf( __( 'Log Paytrail events, inside %s', 'woocommerce-gateway-paytrail' ), '<code>' . SV_WC_Gateway_Paytrail_Plugin_Compatibility::wc_get_log_file_path( $this->id ) . '</code>' ),
)
);
} // End init_form_fields()
/**
* Admin Panel Options
* - Options for bits like 'title' and availability on a country-by-country basis
*
* @since 1.0.0
*/
public function admin_options() {
?>
<h3><?php _e('Paytrail', 'woocommerce-gateway-paytrail'); ?></h3>
<p><?php _e('This gateway works by sending user to Paytrail portal to enter their payment information.', 'woocommerce-gateway-paytrail'); ?></p>
<table class="form-table">
<?php
if ( 'EUR' == get_woocommerce_currency() ) {
?>
<table class="form-table"><?php
// Generate the HTML For the settings form.
$this->generate_settings_html();
?></table><!--/.form-table--><?php
} else {
?>
<div class="inline error"><p><strong><?php _e( 'Gateway Disabled', 'woocommerce-gateway-paytrail' ); ?></strong> <?php echo sprintf( __( 'Choose Euros as your store currency in <a href="%s">General Options</a> to enable this Gateway.', 'woocommerce-gateway-paytrail' ), admin_url( 'admin.php?page=wc-settings&tab=general' ) ); ?></p></div>
<?php
} // End check currency
?>
</table><!--/.form-table-->
<?php
} // End admin_options()
/**
* Check if this gateway is enabled and using correct currency. Only EUR allowed.
*/
function is_available() {
if ( $this->enabled == 'yes' ) {
// Currency check
if ( ! in_array( get_woocommerce_currency(), array('EUR') ) ) {
return false;
}
// Required fields check
if ( ! $this->merchant_id || ! $this->merchant_secret ) {
return false;
}
return true;
}
return false;
}
/**
* There are no payment fields for Paytrail, but we want to show the description if set.
*/
function payment_fields() {
if ( $this->description ) echo wpautop( wptexturize( $this->description ) );
}
/**
* Process the payment and return the result
*/
function process_payment( $order_id ) {
$order = SV_WC_Gateway_Paytrail_Plugin_Compatibility::wc_get_order( $order_id );
// Create urlset for Paytrail payment
$urlset = new Verkkomaksut_Module_Rest_Urlset(
add_query_arg('wc-api', 'wc_gateway_paytrail', $this->get_return_url( $order )), // Success URL
$order->get_cancel_order_url(), // Failure URL
add_query_arg( array( 'wc-api' => 'wc_gateway_paytrail', 'fwpListener' => 'fwp_notify' ), home_url( '/' ) ), // IPN Notification URL
add_query_arg( 'fwpListener', 'fwp_pending', $order->get_checkout_order_received_url() ) // Pending URL
);
$orderNumber = preg_replace( '/[^0-9]/', '', $order->get_order_number() );
add_option( 'wc_paytrail_order_id_' . $orderNumber, $order_id );
$result = NULL;
$payment_problem = FALSE;
// Create order details with extended info
if ( $this->extended_info == 'yes' ) {
// Create contact details for order
$contact = new Verkkomaksut_Module_Rest_Contact(
$order->billing_first_name,
$order->billing_last_name,
$order->billing_email,
$order->billing_address_1,
$order->billing_postcode,
$order->billing_city,
$order->billing_country,
$order->billing_phone,
'',
$order->billing_company
);
$payment = new Verkkomaksut_Module_Rest_Payment_E1( $orderNumber, $urlset, $contact );
/**
* Filter the locale of Paytrail pay page
*
* @since 1.2.6
* @param string $locale the locale of Paytrail pay page. One of 'fi_FI', 'en_US', 'sv_SE'
*/
$payment->setLocale( apply_filters( 'wc_gateway_paytrail_locale', 'fi_FI' ) );
// Loop through cart contents
$item_loop = 0;
if ( sizeof( $order->get_items() ) > 0 ) {
foreach ( $order->get_items() as $item ) {
if ( $item['qty'] ) {
$item_loop++;
// Calculate tax rate
$item_tax_percentage = number_format( ( $order->get_line_tax( $item ) / $order->get_line_total( $item, false ) ) * 100, 0, '.', '');
$product = $order->get_product_from_item( $item );
// Add product element with product details
$payment->addProduct(
$item['name'],
substr( $product->get_sku(), 0, 16 ),
$item['qty'],
number_format( $order->get_item_total( $item, true ), 2, '.', '' ),
number_format( $item_tax_percentage, 2, '.', '' ),
'0.00',
Verkkomaksut_Module_Rest_Product::TYPE_NORMAL
);
}
}
}
if ( $order->get_shipping_method() ) {
// Calculate tax rate
$shipping_tax_percentage = $order->get_total_shipping() == 0 ? 0 : number_format( ( $order->get_shipping_tax() / $order->get_total_shipping() ) * 100, 0, '.', '');
// Add product element with shipping details
$payment->addProduct(
$order->get_shipping_method(),
'',
'1',
number_format( $order->get_total_shipping() + $order->get_shipping_tax(), 2, '.', '' ),
number_format( $shipping_tax_percentage, 2, '.', '' ),
'0.00',
Verkkomaksut_Module_Rest_Product::TYPE_POSTAL
);
}
$discount = SV_WC_Gateway_Paytrail_Plugin_Compatibility::is_wc_version_gte_2_3() ? 0 : $order->get_order_discount();
if ( $discount > 0 ) {
// Add product element with shipping details
$payment->addProduct(
__( 'Order discount', 'woocommerce-gateway-paytrail' ),
'',
'1',
'-' . number_format( $discount, 2, '.', '' ),
'0',
'0.00',
Verkkomaksut_Module_Rest_Product::TYPE_NORMAL
);
}
$fwp_payment = new Verkkomaksut_Module_Rest( $this->merchant_id, $this->merchant_secret );
try {
$result = $fwp_payment->processPayment( $payment );
} catch ( Verkkomaksut_Exception $e ) {
$payment_problem = TRUE;
$order = SV_WC_Gateway_Paytrail_Plugin_Compatibility::wc_get_order( $orderNumber );
$order_note = sprintf( __('Paytrail payment failed: %s.', 'woocommerce-gateway-paytrail'), $e->getMessage() );
if ( 'yes' == $this->debug ) {
$this->log->add( 'paytrail', sprintf( __('Paytrail payment failed: %s.', 'woocommerce-gateway-paytrail'), $e->getMessage() ) );
}
if ( ! SV_WC_Gateway_Paytrail_Plugin_Compatibility::order_has_status( $order, 'failed' ) ) {
$order->update_status( 'failed', $order_note );
} else {
$order->add_order_note( $order_note );
}
}
} else {
// Create payment
$price = number_format( $order->get_total(), 2, '.', '' );
$payment = new Verkkomaksut_Module_Rest_Payment_S1( $orderNumber, $urlset, $price );
// Send payment to Paytrail and handle possible errors
$fwp_payment = new Verkkomaksut_Module_Rest( $this->merchant_id, $this->merchant_secret );
try {
$result = $fwp_payment->processPayment( $payment );
} catch ( Verkkomaksut_Exception $e ) {
$payment_problem = TRUE;
$order = SV_WC_Gateway_Paytrail_Plugin_Compatibility::wc_get_order( $orderNumber );
$order_note = sprintf( __('Paytrail payment failed: %s.', 'woocommerce-gateway-paytrail'), $e->getMessage() );
if ( 'yes' == $this->debug ) {
$this->log->add( 'paytrail', sprintf( __('Paytrail payment failed: %s.', 'woocommerce-gateway-paytrail'), $e->getMessage() ) );
}
if ( ! SV_WC_Gateway_Paytrail_Plugin_Compatibility::order_has_status( $order, 'failed' ) ) {
$order->update_status('failed', $order_note );
} else {
$order->add_order_note( $order_note );
}
}
}
// Create form with the return url to redirect client to Paytrail payment page
if ( ! $payment_problem ) {
return array(
'result' => 'success',
'redirect' => $result->getUrl()
);
} else {
wc_add_notice( __( 'An error occurred, please try again or try an alternate form of payment.', 'woocommerce-gateway-paytrail' ), 'error' );
}
}
/**
* Check for valid response
*/
function check_paytrail_response() {
// Check if needed vars are actually set
if ( isset( $_GET['wc-api'], $_GET['ORDER_NUMBER'], $_GET['TIMESTAMP'], $_GET['PAID'], $_GET['METHOD'], $_GET['RETURN_AUTHCODE'] ) && $_GET['wc-api'] == 'wc_gateway_paytrail' ) {
if ( isset( $_GET['fwpListener'] ) && $_GET['fwpListener'] != 'fwp_pending' ) {
if ( $_GET['fwpListener'] == 'fwp_notify' ) {
//We got payment notification so let's validate it
$module = new Verkkomaksut_Module_Rest( $this->merchant_id, $this->merchant_secret );
if ( $module->confirmPayment( $_GET['ORDER_NUMBER'], $_GET['TIMESTAMP'], $_GET['PAID'], $_GET['METHOD'], $_GET['RETURN_AUTHCODE'] ) ) {
// Payment was valid so let's proceed with the order
$orderdetails = array( 'orderid' => get_option( 'wc_paytrail_order_id_' . $_GET['ORDER_NUMBER'] ), 'ordermethod' => $_GET['METHOD'] );
WC()->cart->empty_cart();
header( 'HTTP/1.1 200 OK' );
do_action( 'valid_paytrail_payment', $orderdetails );
} else {
$order = SV_WC_Gateway_Paytrail_Plugin_Compatibility::wc_get_order( get_option( 'wc_paytrail_order_id_' . $_GET['ORDER_NUMBER'] ) );
$order->update_status('failed', sprintf( __('Paytrail payment failed via %s. Possible hacking attempt.', 'woocommerce-gateway-paytrail' ), strtolower( $_GET['METHOD'] ) ) );
wp_die( 'Paytrail notify request failure.' );
}
}
} else {
$module = new Verkkomaksut_Module_Rest( $this->merchant_id, $this->merchant_secret );
if ( $module->confirmPayment( $_GET['ORDER_NUMBER'], $_GET['TIMESTAMP'], $_GET['PAID'], $_GET['METHOD'], $_GET['RETURN_AUTHCODE'] ) ) {
WC()->cart->empty_cart();
// Payment was valid so let's proceed with the order
$orderdetails = array( 'orderid' => get_option( 'wc_paytrail_order_id_' . $_GET['ORDER_NUMBER'] ), 'ordermethod' => $_GET['METHOD'] );
if ( $_GET['fwpListener'] == 'fwp_pending' ) {
$order = SV_WC_Gateway_Paytrail_Plugin_Compatibility::wc_get_order( get_option( 'wc_paytrail_order_id_' . $_GET['ORDER_NUMBER'] ) );
$order->update_status('pending', __('Order payment via Paytrail is pending for confirmation.', 'woocommerce-gateway-paytrail'));
} else {
do_action( 'valid_paytrail_payment', $orderdetails );
$order = SV_WC_Gateway_Paytrail_Plugin_Compatibility::wc_get_order( $orderdetails['orderid'] );
wp_redirect( $this->get_return_url( $order ) );
delete_option( 'wc_paytrail_order_id_' . $_GET['ORDER_NUMBER'] );
exit;
}
} else {
$order = SV_WC_Gateway_Paytrail_Plugin_Compatibility::wc_get_order( get_option( 'wc_paytrail_order_id_' . $_GET['ORDER_NUMBER'] ) );
$order->update_status('failed', sprintf( __( 'Paytrail payment failed via %s. Possible hacking attempt.', 'woocommerce-gateway-paytrail' ), strtolower( $_GET['METHOD'] ) ) );
wp_die( 'Paytrail notify request failure.' );
}
}
}
delete_option( 'wc_paytrail_order_id_' . $_GET['ORDER_NUMBER'] );
}
/**
* Successful Payment!
*/
function successful_request( $orderdetails ) {
$order = SV_WC_Gateway_Paytrail_Plugin_Compatibility::wc_get_order( $orderdetails['orderid'] );
if ( $order ) {
$order->payment_complete();
$order->add_order_note( sprintf( __( 'Paytrail payment complete via %s.', 'woocommerce-gateway-paytrail' ), strtolower( $orderdetails['ordermethod'] ) ) );
if ( 'yes' == $this->debug ) {
$this->log->add( 'paytrail', 'Found order #' . $order->id );
$this->log->add( 'paytrail', 'Payment complete.' );
}
}
}
}
/**
* Add the gateway to WooCommerce
*/
function add_paytrail_gateway( $methods ) {
$methods[] = 'WC_Gateway_Paytrail';
return $methods;
}
add_filter( 'woocommerce_payment_gateways', 'add_paytrail_gateway' );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment