Completed
Pull Request — master (#2066)
by
unknown
08:12
created

WPSC_WorldPay_Payments_Order_Handler   B

Complexity

Total Complexity 47

Size/Duplication

Total Lines 390
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 1

Importance

Changes 8
Bugs 1 Features 0
Metric Value
wmc 47
c 8
b 1
f 0
lcom 2
cbo 1
dl 0
loc 390
rs 8.439

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A init() 0 5 1
A get_instance() 0 7 2
A set_purchase_log() 0 3 1
B order_actions() 0 35 6
A meta_box() 0 9 2
C authorization_box() 0 131 11
C refresh_transaction_info() 0 40 11
A void_payment() 0 21 3
B refund_payment() 0 24 3
A capture_payment() 0 22 3
A void_refund() 0 23 3

How to fix   Complexity   

Complex Class

Complex classes like WPSC_WorldPay_Payments_Order_Handler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use WPSC_WorldPay_Payments_Order_Handler, and based on these observations, apply Extract Interface, too.

1
<?php
2
class WPSC_Payment_Gateway_WorldPay extends WPSC_Payment_Gateway {
3
4
	private $endpoints = array(
5
		'sandbox' => 'https://gwapi.demo.securenet.com/api/',
6
		'production' => 'https://gwapi.securenet.com/api/',
7
	);
8
	
9
	private $auth;
10
	private $payment_capture;
11
	private $order_handler;
12
	private $secure_net_id;
13
	private $secure_key;
14
	private $public_key;
15
	private $endpoint;
16
	private $sandbox;
17
18
	
19
20
	/**
21
	 * Constructor of WorldPay Payment Gateway
22
	 *
23
	 * @access public
24
	 * @since 3.9
25
	 */
26
	public function __construct() {
27
28
		parent::__construct();
29
30
		$this->title = __( 'WorldPay Payment Gateway', 'wp-e-commerce' );
31
		$this->supports = array( 'default_credit_card_form', 'tev1' );
32
33
		$this->order_handler	= WPSC_WorldPay_Payments_Order_Handler::get_instance( $this );
34
		
35
		// Define user set variables
36
		$this->secure_net_id	= $this->setting->get( 'secure_net_id' );
37
		$this->secure_key  		= $this->setting->get( 'secure_key' );
38
		$this->public_key  		= $this->setting->get( 'public_key' );
39
		$this->sandbox			= $this->setting->get( 'sandbox_mode' ) == '1' ? true : false;
40
		$this->endpoint			= $this->sandbox ? $this->endpoints['sandbox'] : $this->endpoints['production'];
41
		$this->payment_capture 	= $this->setting->get( 'payment_capture' ) !== null ? $this->setting->get( 'payment_capture' ) : '';
42
		$this->auth				= 'Basic ' . base64_encode( $this->setting->get( 'secure_net_id' ) . ':' . $this->setting->get( 'secure_key' ) );
43
	}
44
45
	/**
46
	 * Settings Form Template
47
	 *
48
	 * @since 3.9
49
	 */
50
	public function setup_form() {
51
?>
52
		<!-- Account Credentials -->
53
		<tr>
54
			<td colspan="2">
55
				<h4><?php _e( 'Account Credentials', 'wp-e-commerce' ); ?></h4>
56
			</td>
57
		</tr>
58
		<tr>
59
			<td>
60
				<label for="wpsc-worldpay-secure-net-id"><?php _e( 'SecureNet ID', 'wp-e-commerce' ); ?></label>
61
			</td>
62
			<td>
63
				<input type="text" name="<?php echo esc_attr( $this->setting->get_field_name( 'secure_net_id' ) ); ?>" value="<?php echo esc_attr( $this->setting->get( 'secure_net_id' ) ); ?>" id="wpsc-worldpay-secure-net-id" />
64
				<br><span class="small description"><?php _e( 'The SecureNet ID can be obtained from the email that you should have received during the sign-up process.', 'wp-e-commerce' ); ?></span>
65
			</td>
66
		</tr>
67
		<tr>
68
			<td>
69
				<label for="wpsc-worldpay-secure-key"><?php _e( 'Secure Key', 'wp-e-commerce' ); ?></label>
70
			</td>
71
			<td>
72
				<input type="text" name="<?php echo esc_attr( $this->setting->get_field_name( 'secure_key' ) ); ?>" value="<?php echo esc_attr( $this->setting->get( 'secure_key' ) ); ?>" id="wpsc-worldpay-secure-key" />
73
				<br><span class="small description"><?php _e( 'You can obtain the Secure Key by signing into the Virtual Terminal with the login credentials that you were emailed to you during the sign-up process. You will then need to navigate to Settings and click on the Obtain Secure Key link.', 'wp-e-commerce' ); ?></span>
74
			</td>
75
		</tr>
76
		<tr>
77
			<td>
78
				<label for="wpsc-worldpay-public-key"><?php _e( 'Public Key', 'wp-e-commerce' ); ?></label>
79
			</td>
80
			<td>
81
				<input type="text" name="<?php echo esc_attr( $this->setting->get_field_name( 'public_key' ) ); ?>" value="<?php echo esc_attr( $this->setting->get( 'public_key' ) ); ?>" id="wpsc-worldpay-public-key" />
82
				<br><span class="small description"><?php _e( 'You can obtain the Public Key by signing into the Virtual Terminal. You will then need to navigate to Settings and click on the Obtain Public Key link.', 'wp-e-commerce' ); ?></span>
83
			</td>
84
		</tr>
85
		<tr>
86
			<td>
87
				<label for="wpsc-worldpay-payment-capture"><?php _e( 'Payment Capture', 'wp-e-commerce' ); ?></label>
88
			</td>
89
			<td>
90
				<select id="wpsc-worldpay-payment-capture" name="<?php echo esc_attr( $this->setting->get_field_name( 'payment_capture' ) ); ?>">
91
					<option value='' <?php selected( '', $this->setting->get( 'payment_capture' ) ); ?>><?php _e( 'Authorize and capture the payment when the order is placed.', 'wp-e-commerce' )?></option>
92
					<option value='authorize' <?php selected( 'authorize', $this->setting->get( 'payment_capture' ) ); ?>><?php _e( 'Authorize the payment when the order is placed.', 'wp-e-commerce' )?></option>
93
				</select>
94
			</td>
95
		</tr>
96
		<tr>
97
			<td>
98
				<label><?php _e( 'Sandbox Mode', 'wp-e-commerce' ); ?></label>
99
			</td>
100
			<td>
101
				<label><input <?php checked( $this->setting->get( 'sandbox_mode' ) ); ?> type="radio" name="<?php echo esc_attr( $this->setting->get_field_name( 'sandbox_mode' ) ); ?>" value="1" /> <?php _e( 'Yes', 'wp-e-commerce' ); ?></label>&nbsp;&nbsp;&nbsp;
102
				<label><input <?php checked( (bool) $this->setting->get( 'sandbox_mode' ), false ); ?> type="radio" name="<?php echo esc_attr( $this->setting->get_field_name( 'sandbox_mode' ) ); ?>" value="0" /> <?php _e( 'No', 'wp-e-commerce' ); ?></label>
103
			</td>
104
		</tr>
105
		<!-- Error Logging -->
106
		<tr>
107
			<td colspan="2">
108
				<h4><?php _e( 'Error Logging', 'wp-e-commerce' ); ?></h4>
109
			</td>
110
		</tr>
111
		<tr>
112
			<td>
113
				<label><?php _e( 'Enable Debugging', 'wp-e-commerce' ); ?></label>
114
			</td>
115
			<td>
116
				<label><input <?php checked( $this->setting->get( 'debugging' ) ); ?> type="radio" name="<?php echo esc_attr( $this->setting->get_field_name( 'debugging' ) ); ?>" value="1" /> <?php _e( 'Yes', 'wp-e-commerce' ); ?></label>&nbsp;&nbsp;&nbsp;
117
				<label><input <?php checked( (bool) $this->setting->get( 'debugging' ), false ); ?> type="radio" name="<?php echo esc_attr( $this->setting->get_field_name( 'debugging' ) ); ?>" value="0" /> <?php _e( 'No', 'wp-e-commerce' ); ?></label>
118
			</td>
119
		</tr>
120
<?php
121
	}
122
123
	/**
124
	 * Add scripts
125
	 */
126
	public function scripts() {
127
128
		$jsfile = $this->sandbox ? 'PayOSDev.js' : 'PayOS.js';
129
		wp_enqueue_script( 'worldpay_payos', WPSC_MERCHANT_V3_SDKS_URL . '/worldpay/assets/js/'.$jsfile, '', WPSC_VERSION );
130
	}
131
132
	public function head_script() {
133
		?>
134
		<script type='text/javascript'>
135
136
			jQuery(document).ready(function($) {
137
				$( ".wpsc_checkout_forms" ).submit(function( event ) {
138
					
139
					event.preventDefault();
140
					
141
					//jQuery( 'input[type="submit"]', this ).prop( { 'disabled': true } );
142
143
					var response = tokenizeCard(
144
						{
145
							"publicKey": '<?php echo $this->public_key; ?>',
146
							"card": {
147
								"number": document.getElementById('card_number').value,
148
								"cvv": document.getElementById('card_code').value,
149
							"expirationDate": document.getElementById('card_expiry_month').value + '/' + document.getElementById('card_expiry_year').value,
150
								"firstName": $( 'input[title="billingfirstname"]' ).val(),
151
								"lastName": $( 'input[title="billinglastname"]' ).val(),
152
								"address": {
153
									"zip": $( 'input[title="billingpostcode"]' ).val()
154
								}
155
							},
156
							"addToVault": false,
157
							"developerApplication": {
158
								"developerId": 10000644,
159
								"version": '1.2'
160
161
							}
162
						}
163
					).done(function (result) {
164
165
						var responseObj = $.parseJSON(JSON.stringify(result));
166
167
						if (responseObj.success) {
168
169
							var form$ = jQuery('.wpsc_checkout_forms');
170
171
							var token = responseObj.token;
172
173
							$("#worldpay_pay_token").val(token);
174
							// and submit
175
							form$.get(0).submit();
176
177
							// do something with responseObj.token
178
						} else {
179
							alert("token was not created");
180
							// do something with responseObj.message
181
182
						}
183
184
					}).fail(function ( response ) {
185
						jQuery( 'input[type="submit"]', this ).prop( { 'disabled': false } );
186
							console.log( response )
187
						// an error occurred
188
					});
189
				});
190
191
			});
192
193
		</script>
194
		<?php
195
	}
196
	
197
	public function te_v1_insert_hidden_field() {
198
		echo '<input type="hidden" id="worldpay_pay_token" name="worldpay_pay_token" value="" />';
199
	}
200
201
	public function init() {
202
203
		add_action( 'wp_enqueue_scripts', array( $this, 'scripts' ) );
204
		add_action( 'wp_head'           , array( $this, 'head_script' ) );
205
206
		add_action( 'wpsc_inside_shopping_cart', array( $this, 'te_v1_insert_hidden_field' ) );
207
		
208
		add_filter( 'wpsc_gateway_checkout_form_worldpay', array( $this, 'payment_fields' ) );
209
		//add_filter( 'wpsc_get_checkout_payment_method_form_args', array( $this, 'te_v2_show_payment_fields' ) );
210
	}
211
212
	public function te_v2_show_payment_fields( $args ) {
213
214
		$default = '<div class="wpsc-form-actions">';
215
		ob_start();
216
217
		$this->payment_fields();
218
		$fields = ob_get_clean();
219
220
		$args['before_form_actions'] = $fields . $default;
221
222
		return $args;
223
	}
224
225
	public function process() {
226
227
		$order = $this->purchase_log;
228
		
229
		$status = $this->payment_capture === '' ? WPSC_Purchase_Log::ACCEPTED_PAYMENT : WPSC_Purchase_Log::ORDER_RECEIVED;
230
		
231
		$order->set( 'processed', $status )->save();
232
		
233
		$card_token = isset( $_POST['worldpay_pay_token'] ) ? sanitize_text_field( $_POST['worldpay_pay_token'] ) : '';
234
	
235
		$this->order_handler->set_purchase_log( $order->get( 'id' ) );
236
		
237
		switch ( $this->payment_capture ) {
238
			case 'authorize' :
239
240
				// Authorize only
241
				$result = $this->authorize_payment( $card_token );
242
243
				if ( $result ) {
244
					// Mark as on-hold
245
					$order->set( 'worldpay-status', __( 'WorldPay order opened. Capture the payment below. Authorized payments must be captured within 7 days.', 'wp-e-commerce' ) )->save();
246
247
				} else {
248
					$order->set( 'processed', WPSC_Purchase_Log::PAYMENT_DECLINED )->save();
249
					$order->set( 'worldpay-status', __( 'Could not authorize WorldPay payment.', 'wp-e-commerce' ) )->save();
250
251
					//$this->handle_declined_transaction( $order );
252
				}
253
254
			break;
255
			default:
256
					
257
				// Capture
258
				$result = $this->capture_payment( $card_token );
259
260
				if ( $result ) {
261
					// Payment complete
262
					$order->set( 'worldpay-status', __( 'WorldPay order completed.  Funds have been authorized and captured.', 'wp-e-commerce' ) );
263
				} else {
264
					$order->set( 'processed', WPSC_Purchase_Log::PAYMENT_DECLINED );
265
					$order->set( 'worldpay-status', __( 'Could not authorize WorldPay payment.', 'wp-e-commerce' ) );
266
267
					//$this->handle_declined_transaction( $order );
268
				}	
269
				
270
			break;
271
		}
272
		
273
		$order->save();
274
		$this->go_to_transaction_results();
275
276
	}
277
	
278
	public function capture_payment( $token ) {
279
280
		if ( $this->purchase_log->get( 'gateway' ) == 'worldpay' ) {
281
			
282
			$order = $this->purchase_log;
283
			
284
			$params = array (
0 ignored issues
show
introduced by
There must be no space between the Array keyword and the opening parenthesis
Loading history...
285
				'amount'	=> $order->get( 'totalprice' ),
286
				'orderId'	=> $order->get( 'id' ),
287
				'invoiceNumber' => $order->get( 'sessionid' ),
288
				"addToVault" => false,
289
				"paymentVaultToken" => array(
290
					"paymentMethodId" => $token,
291
					"publicKey" => $this->public_key
292
				),
293
			);
294
295
			$response = $this->execute( 'Payments/Charge', $params );
296
297
			if ( is_wp_error( $response ) ) {
298
				throw new Exception( $response->get_error_message() );
299
			}
300
			
301
			if ( isset( $response['ResponseBody']->transaction->transactionId ) ) {
302
				$transaction_id = $response['ResponseBody']->transaction->transactionId;
303
				$auth_code = $response['ResponseBody']->transaction->authorizationCode;
304
			} else {
305
				return false;
306
			}
307
			
308
			// Store transaction ID and Auth code in the order
309
			$order->set( 'wp_transactionId', $transaction_id )->save();
310
			$order->set( 'wp_order_status', 'Completed' )->save();
311
			$order->set( 'wp_authcode', $auth_code )->save();
312
			$order->set( 'transactid', $transaction_id )->save();
313
				
314
			return true;
315
		}
316
		
317
		return false;
318
	}
319
320
	public function authorize_payment( $token ) {
321
322
		if ( $this->purchase_log->get( 'gateway' ) == 'worldpay' ) {
323
			
324
			$order = $this->purchase_log;
325
			
326
			$params = array (
0 ignored issues
show
introduced by
There must be no space between the Array keyword and the opening parenthesis
Loading history...
327
				'amount'	=> $order->get( 'totalprice' ),
328
				'orderId'	=> $order->get( 'id' ),
329
				'invoiceNumber' => $order->get( 'sessionid' ),
330
				"addToVault" => false,
331
				"paymentVaultToken" => array(
332
					"paymentMethodId" => $token,
333
					"publicKey" => $this->public_key
334
				),
335
			);
336
337
			$response = $this->execute( 'Payments/Authorize', $params );
338
339
			if ( is_wp_error( $response ) ) {
340
				throw new Exception( $response->get_error_message() );
341
			}
342
			
343
			if ( isset( $response['ResponseBody']->transaction->transactionId ) ) {
344
				$transaction_id = $response['ResponseBody']->transaction->transactionId;
345
				$auth_code = $response['ResponseBody']->transaction->authorizationCode;
346
			} else {
347
				return false;
348
			}
349
			
350
			// Store transaction ID and Auth code in the order
351
			$order->set( 'wp_transactionId', $transaction_id )->save();
352
			$order->set( 'wp_order_status', 'Open' )->save();
353
			$order->set( 'wp_authcode', $auth_code )->save();
354
			$order->set( 'transactid', $transaction_id )->save();
355
							
356
			return true;
357
		}
358
		
359
		return false;
360
	}
361
	
362
	public function execute( $endpoint, $params = array(), $type = 'POST' ) {
363
       
364
	   // where we make the API petition
365
        $endpoint = $this->endpoint . $endpoint;
366
        
367
		if ( ! is_null( $params ) ) {
368
			$params += array(
369
				"developerApplication" => array(
370
					"developerId" => 10000644,
371
					"version" => "1.2"
372
				),
373
				"extendedInformation" => array(
374
					"typeOfGoods" => "PHYSICAL"
375
				),
376
			);			
377
		}
378
			
379
		$data = json_encode( $params );
380
		
381
		$args = array (
0 ignored issues
show
introduced by
There must be no space between the Array keyword and the opening parenthesis
Loading history...
382
			'timeout' => 15,
383
			'headers' => array(
384
				'Authorization' => $this->auth,
385
				'Content-Type' => 'application/json',
386
			),
387
			'sslverify' => false,
388
			'body' => $data,
389
		);
390
		
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 3 empty lines
Loading history...
391
392
  	
393
		$request  = $type == 'GET' ? wp_safe_remote_get( $endpoint, $args ) : wp_safe_remote_post( $endpoint, $args );
394
        $response = wp_remote_retrieve_body( $request );
395
		
396
		if ( ! is_wp_error( $request ) ) {
397
398
			$response_object = array();
399
			$response_object['ResponseBody'] = json_decode( $response );
400
			$response_object['Status']       = wp_remote_retrieve_response_code( $request );
401
402
			$request = $response_object;
403
		}
404
		
405
		return $request;
406
    }
407
408
}
409
410
class WPSC_WorldPay_Payments_Order_Handler {
411
	
412
	private static $instance;
413
	private $log;
414
	private $gateway;
415
	private $doing_ipn = false;
0 ignored issues
show
Unused Code introduced by
The property $doing_ipn is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
416
417
	public function __construct( &$gateway ) {
418
419
		$this->log     = $gateway->purchase_log;
420
		$this->gateway = $gateway;
421
422
		$this->init();
423
	}
424
425
	/**
426
	 * Constructor
427
	 */
428
	public function init() {
429
		add_action( 'wpsc_purchlogitem_metabox_start', array( $this, 'meta_box' ), 8 );
430
		add_action( 'wp_ajax_worldpay_order_action'    , array( $this, 'order_actions' ) );
431
432
	}
433
434
	public static function get_instance( $gateway ) {
435
		if ( is_null( self::$instance ) ) {
436
			self::$instance = new WPSC_WorldPay_Payments_Order_Handler( $gateway );
437
		}
438
439
		return self::$instance;
440
	}
441
442
	public function set_purchase_log( $id ) {
443
		$this->log = new WPSC_Purchase_Log( $id );
444
	}
445
	
446
	/**
447
	 * Perform order actions for amazon
448
	 */
449
	public function order_actions() {
450
		check_ajax_referer( 'wp_order_action', 'security' );
451
452
		$order_id = absint( $_POST['order_id'] );
453
		$id       = isset( $_POST['worldpay_id'] ) ? sanitize_text_field( $_POST['worldpay_id'] ) : '';
454
		$action   = sanitize_title( $_POST['worldpay_action'] );
455
456
		$this->set_purchase_log( $order_id );
457
458
		switch ( $action ) {
459
			case 'capture' :
460
				//Capture an AUTH
461
				$this->capture_payment($id);
462
			break;
463
			
464
			case 'void' :
465
				// void capture or auth before settled
466
				$this->void_payment( $id );
467
			break;
468
			
469
			case 'refund' :
470
				// refund a settled payment
471
				$this->refund_payment( $id );
472
			break;
473
			
474
			case 'void_refund' :
475
				// void a refund request
476
				$this->void_refund( $id );
477
			break;
478
		}
479
480
		echo json_encode( array( 'action' => $action, 'order_id' => $order_id, 'worldpay_id' => $id ) );
481
482
		die();
483
	}
484
	
485
	/**
486
	 * meta_box function.
487
	 *
488
	 * @access public
489
	 * @return void
490
	 */
491
	function meta_box( $log_id ) {
492
		$this->set_purchase_log( $log_id );
493
494
		$gateway = $this->log->get( 'gateway' );
495
496
		if ( $gateway == 'worldpay' ) {
497
			$this->authorization_box();
498
		}
499
	}
500
501
	/**
502
	 * pre_auth_box function.
503
	 *
504
	 * @access public
505
	 * @return void
506
	 */
507
	public function authorization_box() {
508
		
509
		$actions  = array();
510
		$order_id = $this->log->get( 'id' );
511
512
		// Get ids
513
		$wp_transaction_id 	= $this->log->get( 'wp_transactionId' );
514
		$wp_auth_code		= $this->log->get( 'wp_authcode' );
515
		$wp_order_status	= $this->log->get( 'wp_order_status' );
516
		
517
		//Don't change order status if a refund has been requested
518
		$wp_refund_set       = wpsc_get_purchase_meta( $order_id, 'worldpay_refunded', true );
519
		$order_info = $this->refresh_transaction_info( $wp_transaction_id, ! ( bool ) $wp_refund_set );
0 ignored issues
show
introduced by
Cast statements must not contain whitespace; expected "(bool)" but found "( bool )"
Loading history...
520
		?>
521
		
522
		<div class="metabox-holder">
523
			<div id="wpsc-worldpay-payments" class="postbox">
524
				<h3 class='hndle'><?php _e( 'WorldPay Payments' , 'wp-e-commerce' ); ?></h3>
525
				<div class='inside'>
526
					<p><?php
527
							_e( 'Current status: ', 'wp-e-commerce' );
528
							echo wp_kses_data( $this->log->get( 'worldpay-status' ) );
529
						?>
530
					</p>
531
					<p><?php
532
							_e( 'Transaction ID: ', 'wp-e-commerce' );
533
							echo wp_kses_data( $wp_transaction_id );
534
						?>
535
					</p>
536
		<?php
537
		
538
		//Show actions based on order status
539
		switch ( $wp_order_status ) {
540
			case 'Open' :
541
				//Order is only authorized and still not captured/voided
542
				$actions['capture'] = array(
543
					'id' => $wp_transaction_id,
544
					'button' => __( 'Capture funds', 'wp-e-commerce' )
545
				);
546
				
547
				//
548
				if ( ! $order_info['settled'] ) {
549
					//Void
550
					$actions['void'] = array(
551
						'id' => $wp_transaction_id,
552
						'button' => __( 'Void order', 'wp-e-commerce' )
553
					);					
554
				}
555
				
556
				break;
557
			case 'Completed' :
558
				//Order has been captured or its a direct payment
559
				if ( $order_info['settled'] ) {
560
					//Refund
561
					$actions['refund'] = array(
562
						'id' => $wp_transaction_id,
563
						'button' => __( 'Refund order', 'wp-e-commerce' )
564
					);
565
				} else {
566
					//Void
567
					$actions['void'] = array(
568
						'id' => $wp_transaction_id,
569
						'button' => __( 'Void order', 'wp-e-commerce' )
570
					);					
571
				}
572
				
573
			break;
574
			case 'Refunded' :
575
				//Order is settled and a refund has been requested
576
				$wp_refund_id       = wpsc_get_purchase_meta( $order_id, 'worldpay_refund_id', true );
577
				
578
				if ( $wp_refund_id ) {
579
					//Get refund order status to check if its eligible for a void (not settled)
580
					$refund_status = $this->refresh_transaction_info( $wp_refund_id, false );
581
					
582
					if ( ! $refund_status['settled'] ) {
583
						//Show void only if not settled.
584
						$actions['void_refund'] = array(
585
							'id' => $wp_refund_id,
586
							'button' => __( 'Void Refund request', 'wp-e-commerce' )
587
						);						
588
					}
589
				}
590
591
				break;
592
			case 'Voided' :
593
			break;
594
		}			
595
		
596
		if ( ! empty( $actions ) ) {
597
598
			echo '<p class="buttons">';
599
600
			foreach ( $actions as $action_name => $action ) {
601
				echo '<a href="#" class="button" data-action="' . $action_name . '" data-id="' . $action['id'] . '">' . $action['button'] . '</a> ';
602
			}
603
604
			echo '</p>';
605
606
		}		
607
		?>
608
		<script type="text/javascript">
609
		jQuery( document ).ready( function( $ ) {
610
			$('#wpsc-worldpay-payments').on( 'click', 'a.button, a.refresh', function( e ) {
611
				var $this = $( this );
612
				e.preventDefault();
613
614
				var data = {
615
					action: 		'worldpay_order_action',
616
					security: 		'<?php echo wp_create_nonce( "wp_order_action" ); ?>',
617
					order_id: 		'<?php echo $order_id; ?>',
618
					worldpay_action: 	$this.data('action'),
619
					worldpay_id: 		$this.data('id'),
620
					worldpay_refund_amount: jQuery('.worldpay_refund_amount').val(),
621
				};
622
623
				// Ajax action
624
				$.post( ajaxurl, data, function( result ) {
625
						location.reload();
626
					}, 'json' );
627
628
				return false;
629
			});
630
		} );
631
632
		</script>
633
		</div>
634
		</div>
635
		</div>
636
		<?php
637
	}
638
639
    /**
640
     * Get the order status from API
641
     *
642
     * @param  string $transaction_id
643
     */	
644
	public function refresh_transaction_info( $transaction_id, $update = true ) {
645
		
646
		if ( $this->log->get( 'gateway' ) == 'worldpay' ) {
647
			
648
			$response = $this->gateway->execute( 'transactions/'. $transaction_id, null, 'GET' );
649
650
			if ( is_wp_error( $response ) ) {
651
				throw new Exception( $response->get_error_message() );
652
			}
653
			
654
			$response_object = array();
655
			$response_object['trans_type'] 	= $response['ResponseBody']->transactions[0]->transactionType;
656
			$response_object['settled'] 	= isset( $response['ResponseBody']->transactions[0]->settlementData ) ? true : false;
657
658
			//Recheck status and update if required
659
			if ( $update ) {
660
				switch ( $response_object['trans_type'] ) {
661
					case 'AUTH_ONLY' :
662
						$this->log->set( 'wp_order_status', 'Open' )->save();
663
					break;
664
					
665
					case 'VOID' :
666
						$this->log->set( 'wp_order_status', 'Voided' )->save();
667
					break;
668
					
669
					case 'REFUND' :
670
					case 'CREDIT' :
671
						$this->log->set( 'wp_order_status', 'Refunded' )->save();
672
					break;				
673
					
674
					case 'AUTH_CAPTURE' :
675
					case 'PRIOR_AUTH_CAPTURE' :
676
						$this->log->set( 'wp_order_status', 'Completed' )->save();
677
					break;
678
				}				
679
			}
680
681
		return $response_object;
682
		}
683
	}
684
	
685
	
686
    /**
687
     * Void auth/capture
688
     *
689
     * @param  string $transaction_id
690
     */
691
    public function void_payment( $transaction_id ) {
692
693
		if ( $this->log->get( 'gateway' ) == 'worldpay' ) {
694
			
695
			$params = array(
696
				'amount'		=>  $this->log->get( 'totalprice' ),
0 ignored issues
show
introduced by
Expected 1 space after "=>"; 2 found
Loading history...
697
				'transactionId' => $transaction_id,
698
			);
699
			
700
			$response = $this->gateway->execute( 'Payments/Void', $params );
701
702
			if ( is_wp_error( $response ) ) {
703
				throw new Exception( $response->get_error_message() );
704
			}
705
			
706
			$this->log->set( 'wp_order_status', 'Voided' )->save();
707
			$this->log->set( 'worldpay-status', sprintf( __( 'Authorization voided (Auth ID: %s)', 'wp-e-commerce' ), $response['ResponseBody']->transaction->authorizationCode ) )->save();
708
			$this->log->set( 'processed', WPSC_Purchase_Log::INCOMPLETE_SALE )->save();
709
			$this->log->set( 'transactid', $response['ResponseBody']->transaction->transactionId )->save();
710
		}
711
    }
712
	
713
    /**
714
     * Refund payment
715
     *
716
     * @param  string $transaction_id
717
     */
718
    public function refund_payment( $transaction_id ) {
719
720
		if ( $this->log->get( 'gateway' ) == 'worldpay' ) {
721
			
722
			$params = array(
723
				'amount'		=> $this->log->get( 'totalprice' ),
724
				'transactionId' => $transaction_id,
725
				
726
			);
727
			
728
			$response = $this->gateway->execute( 'Payments/Refund', $params );
729
		
730
			if ( is_wp_error( $response ) ) {
731
				throw new Exception( $response->get_error_message() );
732
			}
733
			
734
			wpsc_add_purchase_meta( $this->log->get( 'id' ), 'worldpay_refunded', true );
735
			wpsc_add_purchase_meta( $this->log->get( 'id' ), 'worldpay_refund_id', $response['ResponseBody']->transaction->transactionId );
736
			$this->log->set( 'worldpay-status', sprintf( __( 'Refunded (Transaction ID: %s)', 'wp-e-commerce' ), $response['ResponseBody']->transaction->transactionId ) )->save();
737
			$this->log->set( 'processed', WPSC_Purchase_Log::REFUNDED )->save();
738
			$this->log->set( 'wp_order_status', 'Refunded' )->save();
739
			$this->log->set( 'transactid', $response['ResponseBody']->transaction->transactionId )->save();
740
		}
741
    }
742
	
743
    /**
744
     * Capture authorized payment
745
     *
746
     * @param  string $transaction_id
747
     */
748
    public function capture_payment( $transaction_id ) {
749
750
		if ( $this->log->get( 'gateway' ) == 'worldpay' ) {
751
			
752
			$params = array(
753
				'amount'		=>  $this->log->get( 'totalprice' ),
0 ignored issues
show
introduced by
Expected 1 space after "=>"; 2 found
Loading history...
754
				'transactionId' => $transaction_id,
755
			);
756
			
757
			$response = $this->gateway->execute( 'Payments/Capture', $params );
758
759
			if ( is_wp_error( $response ) ) {
760
				throw new Exception( $response->get_error_message() );
761
			}
762
			
763
			$this->log->set( 'wp_order_status', 'Completed' )->save();
764
			
765
			$this->log->set( 'worldpay-status', sprintf( __( 'Authorization Captured (Auth ID: %s)', 'wp-e-commerce' ), $response['ResponseBody']->transaction->authorizationCode ) )->save();
766
			$this->log->set( 'processed', WPSC_Purchase_Log::ACCEPTED_PAYMENT )->save();
767
			$this->log->set( 'transactid', $response['ResponseBody']->transaction->transactionId )->save();
768
		}
769
    }
770
	
771
    /**
772
     * Void a refund request
773
     *
774
     * @param  string $transaction_id
775
     */
776
    public function void_refund( $transaction_id ) {
777
778
		if ( $this->log->get( 'gateway' ) == 'worldpay' ) {
779
			
780
			$params = array(
781
				'amount'		=>  $this->log->get( 'totalprice' ),
0 ignored issues
show
introduced by
Expected 1 space after "=>"; 2 found
Loading history...
782
				'transactionId' => $transaction_id,
783
			);
784
			
785
			$response = $this->gateway->execute( 'Payments/Void', $params );
786
787
			if ( is_wp_error( $response ) ) {
788
				throw new Exception( $response->get_error_message() );
789
			}
790
			
791
			wpsc_delete_purchase_meta( $this->log->get( 'id' ), 'worldpay_refunded' );
792
			wpsc_delete_purchase_meta( $this->log->get( 'id' ), 'worldpay_refund_id' );
793
			$this->log->set( 'processed', WPSC_Purchase_Log::ACCEPTED_PAYMENT )->save();
794
			$this->log->set( 'wp_order_status', 'Completed' )->save();
795
			$this->log->set( 'worldpay-status', sprintf( __( 'Refund Voided (Transaction ID: %s)', 'wp-e-commerce' ), $response['ResponseBody']->transaction->transactionId ) )->save();
796
			$this->log->set( 'transactid', $response['ResponseBody']->transaction->transactionId )->save();
797
		}
798
    }
799
}