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

WPSC_Payment_Gateway_WorldPay   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 400
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 3

Importance

Changes 17
Bugs 1 Features 1
Metric Value
wmc 29
c 17
b 1
f 1
lcom 3
cbo 3
dl 0
loc 400
rs 10

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 18 4
A setup_form() 0 72 1
A scripts() 0 5 2
A head_script() 0 61 1
A te_v1_insert_hidden_field() 0 3 1
A init() 0 10 1
A te_v2_show_payment_fields() 0 12 1
B process() 0 52 6
B capture_payment() 0 41 4
B authorize_payment() 0 41 4
B execute() 0 43 4
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
	 * Constructor of WorldPay Payment Gateway
20
	 *
21
	 * @access public
22
	 * @since 3.9
23
	 */
24
	public function __construct() {
25
26
		parent::__construct();
27
28
		$this->title    = __( 'WorldPay Payment Gateway', 'wp-e-commerce' );
29
		$this->supports = array( 'default_credit_card_form', 'tev1' );
30
31
		$this->order_handler	= WPSC_WorldPay_Payments_Order_Handler::get_instance( $this );
32
33
		// Define user set variables
34
		$this->secure_net_id	= $this->setting->get( 'secure_net_id' );
35
		$this->secure_key  		= $this->setting->get( 'secure_key' );
36
		$this->public_key  		= $this->setting->get( 'public_key' );
37
		$this->sandbox			= $this->setting->get( 'sandbox_mode' ) == '1' ? true : false;
38
		$this->endpoint			= $this->sandbox ? $this->endpoints['sandbox'] : $this->endpoints['production'];
39
		$this->payment_capture 	= $this->setting->get( 'payment_capture' ) !== null ? $this->setting->get( 'payment_capture' ) : '';
40
		$this->auth				= 'Basic ' . base64_encode( $this->setting->get( 'secure_net_id' ) . ':' . $this->setting->get( 'secure_key' ) );
41
	}
42
43
	/**
44
	 * Settings Form Template
45
	 *
46
	 * @since 3.9
47
	 */
48
	public function setup_form() {
49
?>
50
		<!-- Account Credentials -->
51
		<tr>
52
			<td colspan="2">
53
				<h4><?php _e( 'Account Credentials', 'wp-e-commerce' ); ?></h4>
54
			</td>
55
		</tr>
56
		<tr>
57
			<td>
58
				<label for="wpsc-worldpay-secure-net-id"><?php _e( 'SecureNet ID', 'wp-e-commerce' ); ?></label>
59
			</td>
60
			<td>
61
				<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" />
62
				<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>
63
			</td>
64
		</tr>
65
		<tr>
66
			<td>
67
				<label for="wpsc-worldpay-secure-key"><?php _e( 'Secure Key', 'wp-e-commerce' ); ?></label>
68
			</td>
69
			<td>
70
				<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" />
71
				<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>
72
			</td>
73
		</tr>
74
		<tr>
75
			<td>
76
				<label for="wpsc-worldpay-public-key"><?php _e( 'Public Key', 'wp-e-commerce' ); ?></label>
77
			</td>
78
			<td>
79
				<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" />
80
				<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>
81
			</td>
82
		</tr>
83
		<tr>
84
			<td>
85
				<label for="wpsc-worldpay-payment-capture"><?php _e( 'Payment Capture', 'wp-e-commerce' ); ?></label>
86
			</td>
87
			<td>
88
				<select id="wpsc-worldpay-payment-capture" name="<?php echo esc_attr( $this->setting->get_field_name( 'payment_capture' ) ); ?>">
89
					<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>
90
					<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>
91
				</select>
92
			</td>
93
		</tr>
94
		<tr>
95
			<td>
96
				<label><?php _e( 'Sandbox Mode', 'wp-e-commerce' ); ?></label>
97
			</td>
98
			<td>
99
				<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;
100
				<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>
101
			</td>
102
		</tr>
103
		<!-- Error Logging -->
104
		<tr>
105
			<td colspan="2">
106
				<h4><?php _e( 'Error Logging', 'wp-e-commerce' ); ?></h4>
107
			</td>
108
		</tr>
109
		<tr>
110
			<td>
111
				<label><?php _e( 'Enable Debugging', 'wp-e-commerce' ); ?></label>
112
			</td>
113
			<td>
114
				<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;
115
				<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>
116
			</td>
117
		</tr>
118
<?php
119
	}
120
121
	/**
122
	 * Add scripts
123
	 */
124
	public function scripts() {
125
126
		$js = $this->sandbox ? 'PayOSDev.js' : 'PayOS.js';
127
		wp_enqueue_script( 'worldpay_payos', WPSC_MERCHANT_V3_SDKS_URL . '/worldpay/assets/js/' . $js, '', WPSC_VERSION );
128
	}
129
130
	public function head_script() {
131
		?>
132
		<script type='text/javascript'>
133
134
			jQuery( document ).ready( function( $ ) {
135
				$( '.wpsc_checkout_forms' ).submit( function( e ) {
136
137
					e.preventDefault();
138
139
					var response = tokenizeCard(
140
						{
141
							"publicKey": '<?php echo $this->public_key; ?>',
142
							"card": {
143
								"number" : document.getElementById( 'card_number' ).value,
144
								"cvv"    : document.getElementById( 'card_code' ).value,
145
							"expirationDate" : document.getElementById( 'card_expiry_month' ).value + '/' + document.getElementById( 'card_expiry_year' ).value,
146
								"firstName" : $( 'input[title="billingfirstname"]' ).val(),
147
								"lastName"  : $( 'input[title="billinglastname"]' ).val(),
148
								"address"   : {
149
									"zip" : $( 'input[title="billingpostcode"]' ).val()
150
								}
151
							},
152
							"addToVault" : false,
153
							"developerApplication" : {
154
								"developerId" : 10000644,
155
								"version" : '1.2'
156
157
							}
158
						}
159
					).done( function( result ) {
160
161
						var responseObj = $.parseJSON( JSON.stringify( result ) );
162
163
						if ( responseObj.success ) {
164
165
							var $form = $( '.wpsc_checkout_forms' );
166
167
							var token = responseObj.token;
168
169
							$( "#worldpay_pay_token" ).val( token );
170
							// and submit
171
							$form.get(0).submit();
172
173
							// do something with responseObj.token
174
						} else {
175
							alert("token was not created");
176
							// do something with responseObj.message
177
178
						}
179
180
					}).fail(function ( response ) {
181
						$( 'input[type="submit"]', this ).prop( { 'disabled': false } );
182
						console.log( response );
183
					});
184
				});
185
186
			});
187
188
		</script>
189
		<?php
190
	}
191
192
	public function te_v1_insert_hidden_field() {
193
		echo '<input type="hidden" id="worldpay_pay_token" name="worldpay_pay_token" value="" />';
194
	}
195
196
	public function init() {
197
198
		add_action( 'wp_enqueue_scripts', array( $this, 'scripts' ) );
199
		add_action( 'wp_head'           , array( $this, 'head_script' ) );
200
201
		add_action( 'wpsc_inside_shopping_cart', array( $this, 'te_v1_insert_hidden_field' ) );
202
203
		add_filter( 'wpsc_gateway_checkout_form_worldpay', array( $this, 'payment_fields' ) );
204
		//add_filter( 'wpsc_get_checkout_payment_method_form_args', array( $this, 'te_v2_show_payment_fields' ) );
205
	}
206
207
	public function te_v2_show_payment_fields( $args ) {
208
209
		$default = '<div class="wpsc-form-actions">';
210
		ob_start();
211
212
		$this->payment_fields();
213
		$fields = ob_get_clean();
214
215
		$args['before_form_actions'] = $fields . $default;
216
217
		return $args;
218
	}
219
220
	public function process() {
221
222
		$order = $this->purchase_log;
223
224
		$status = $this->payment_capture === '' ? WPSC_Purchase_Log::ACCEPTED_PAYMENT : WPSC_Purchase_Log::ORDER_RECEIVED;
225
226
		$order->set( 'processed', $status )->save();
227
228
		$card_token = isset( $_POST['worldpay_pay_token'] ) ? sanitize_text_field( $_POST['worldpay_pay_token'] ) : '';
229
230
		$this->order_handler->set_purchase_log( $order->get( 'id' ) );
231
232
		switch ( $this->payment_capture ) {
233
			case 'authorize' :
234
235
				// Authorize only
236
				$result = $this->authorize_payment( $card_token );
237
238
				if ( $result ) {
239
					// Mark as on-hold
240
					$order->set( 'worldpay-status', __( 'WorldPay order opened. Capture the payment below. Authorized payments must be captured within 7 days.', 'wp-e-commerce' ) )->save();
241
242
				} else {
243
					$order->set( 'processed', WPSC_Purchase_Log::PAYMENT_DECLINED )->save();
244
					$order->set( 'worldpay-status', __( 'Could not authorize WorldPay payment.', 'wp-e-commerce' ) )->save();
245
246
					//$this->handle_declined_transaction( $order );
247
				}
248
249
			break;
250
			default:
251
252
				// Capture
253
				$result = $this->capture_payment( $card_token );
254
255
				if ( $result ) {
256
					// Payment complete
257
					$order->set( 'worldpay-status', __( 'WorldPay order completed.  Funds have been authorized and captured.', 'wp-e-commerce' ) );
258
				} else {
259
					$order->set( 'processed', WPSC_Purchase_Log::PAYMENT_DECLINED );
260
					$order->set( 'worldpay-status', __( 'Could not authorize WorldPay payment.', 'wp-e-commerce' ) );
261
262
					//$this->handle_declined_transaction( $order );
263
				}
264
265
			break;
266
		}
267
268
		$order->save();
269
		$this->go_to_transaction_results();
270
271
	}
272
273
	public function capture_payment( $token ) {
274
275
		if ( $this->purchase_log->get( 'gateway' ) == 'worldpay' ) {
276
277
			$order = $this->purchase_log;
278
279
			$params = array(
280
				'amount'	        => $order->get( 'totalprice' ),
281
				'orderId'	        => $order->get( 'id' ),
282
				'invoiceNumber'     => $order->get( 'sessionid' ),
283
				"addToVault"        => false,
284
				"paymentVaultToken" => array(
285
					"paymentMethodId" => $token,
286
					"publicKey"       => $this->public_key
287
				),
288
			);
289
290
			$response = $this->execute( 'Payments/Charge', $params );
291
292
			if ( is_wp_error( $response ) ) {
293
				throw new Exception( $response->get_error_message() );
294
			}
295
296
			if ( isset( $response['ResponseBody']->transaction->transactionId ) ) {
297
				$transaction_id = $response['ResponseBody']->transaction->transactionId;
298
				$auth_code = $response['ResponseBody']->transaction->authorizationCode;
299
			} else {
300
				return false;
301
			}
302
303
			// Store transaction ID and Auth code in the order
304
			$order->set( 'wp_transactionId', $transaction_id )->save();
305
			$order->set( 'wp_order_status', 'Completed' )->save();
306
			$order->set( 'wp_authcode', $auth_code )->save();
307
			$order->set( 'transactid', $transaction_id )->save();
308
309
			return true;
310
		}
311
312
		return false;
313
	}
314
315
	public function authorize_payment( $token ) {
316
317
		if ( $this->purchase_log->get( 'gateway' ) == 'worldpay' ) {
318
319
			$order = $this->purchase_log;
320
321
			$params = array(
322
				'amount'	        => $order->get( 'totalprice' ),
323
				'orderId'	        => $order->get( 'id' ),
324
				'invoiceNumber'     => $order->get( 'sessionid' ),
325
				"addToVault"        => false,
326
				"paymentVaultToken" => array(
327
					"paymentMethodId" => $token,
328
					"publicKey"       => $this->public_key
329
				),
330
			);
331
332
			$response = $this->execute( 'Payments/Authorize', $params );
333
334
			if ( is_wp_error( $response ) ) {
335
				throw new Exception( $response->get_error_message() );
336
			}
337
338
			if ( isset( $response['ResponseBody']->transaction->transactionId ) ) {
339
				$transaction_id = $response['ResponseBody']->transaction->transactionId;
340
				$auth_code = $response['ResponseBody']->transaction->authorizationCode;
341
			} else {
342
				return false;
343
			}
344
345
			// Store transaction ID and Auth code in the order
346
			$order->set( 'wp_transactionId', $transaction_id )->save();
347
			$order->set( 'wp_order_status', 'Open' )->save();
348
			$order->set( 'wp_authcode', $auth_code )->save();
349
			$order->set( 'transactid', $transaction_id )->save();
350
351
			return true;
352
		}
353
354
		return false;
355
	}
356
357
	public function execute( $endpoint, $params = array(), $type = 'POST' ) {
358
359
	   // where we make the API petition
360
        $endpoint = $this->endpoint . $endpoint;
361
362
		if ( ! is_null( $params ) ) {
363
			$params += array(
364
				"developerApplication" => array(
365
					"developerId" => 10000644,
366
					"version"     => "1.2"
367
				),
368
				"extendedInformation" => array(
369
					"typeOfGoods" => "PHYSICAL"
370
				),
371
			);
372
		}
373
374
		$data = json_encode( $params );
375
376
		$args = array(
377
			'timeout' => 15,
378
			'headers' => array(
379
				'Authorization' => $this->auth,
380
				'Content-Type'  => 'application/json',
381
			),
382
			'sslverify' => false,
383
			'body'      => $data,
384
		);
385
386
		$request  = $type == 'GET' ? wp_safe_remote_get( $endpoint, $args ) : wp_safe_remote_post( $endpoint, $args );
387
        $response = wp_remote_retrieve_body( $request );
388
389
		if ( ! is_wp_error( $request ) ) {
390
391
			$response_object = array();
392
			$response_object['ResponseBody'] = json_decode( $response );
393
			$response_object['Status']       = wp_remote_retrieve_response_code( $request );
394
395
			$request = $response_object;
396
		}
397
398
		return $request;
399
    }
400
401
}
402
403
class WPSC_WorldPay_Payments_Order_Handler {
404
405
	private static $instance;
406
	private $log;
407
	private $gateway;
408
409
	public function __construct( &$gateway ) {
410
411
		$this->log     = $gateway->purchase_log;
412
		$this->gateway = $gateway;
413
414
		$this->init();
415
	}
416
417
	/**
418
	 * Constructor
419
	 */
420
	public function init() {
421
		add_action( 'wpsc_purchlogitem_metabox_start', array( $this, 'meta_box' ), 8 );
422
		add_action( 'wp_ajax_worldpay_order_action'  , array( $this, 'order_actions' ) );
423
424
	}
425
426
	public static function get_instance( $gateway ) {
427
		if ( is_null( self::$instance ) ) {
428
			self::$instance = new WPSC_WorldPay_Payments_Order_Handler( $gateway );
429
		}
430
431
		return self::$instance;
432
	}
433
434
	public function set_purchase_log( $id ) {
435
		$this->log = new WPSC_Purchase_Log( $id );
436
	}
437
438
	/**
439
	 * Perform order actions for amazon
440
	 */
441
	public function order_actions() {
442
		check_ajax_referer( 'wp_order_action', 'security' );
443
444
		$order_id = absint( $_POST['order_id'] );
445
		$id       = isset( $_POST['worldpay_id'] ) ? sanitize_text_field( $_POST['worldpay_id'] ) : '';
446
		$action   = sanitize_title( $_POST['worldpay_action'] );
447
448
		$this->set_purchase_log( $order_id );
449
450
		switch ( $action ) {
451
			case 'capture' :
452
				//Capture an AUTH
453
				$this->capture_payment( $id );
454
			break;
455
456
			case 'void' :
457
				// void capture or auth before settled
458
				$this->void_payment( $id );
459
			break;
460
461
			case 'refund' :
462
				// refund a settled payment
463
				$this->refund_payment( $id );
464
			break;
465
466
			case 'void_refund' :
467
				// void a refund request
468
				$this->void_refund( $id );
469
			break;
470
		}
471
472
		echo json_encode( array( 'action' => $action, 'order_id' => $order_id, 'worldpay_id' => $id ) );
473
474
		die();
475
	}
476
477
	/**
478
	 * meta_box function.
479
	 *
480
	 * @access public
481
	 * @return void
482
	 */
483
	function meta_box( $log_id ) {
484
		$this->set_purchase_log( $log_id );
485
486
		$gateway = $this->log->get( 'gateway' );
487
488
		if ( $gateway == 'worldpay' ) {
489
			$this->authorization_box();
490
		}
491
	}
492
493
	/**
494
	 * pre_auth_box function.
495
	 *
496
	 * @access public
497
	 * @return void
498
	 */
499
	public function authorization_box() {
500
501
		$actions  = array();
502
		$order_id = $this->log->get( 'id' );
503
504
		// Get ids
505
		$wp_transaction_id 	= $this->log->get( 'wp_transactionId' );
506
		$wp_auth_code		= $this->log->get( 'wp_authcode' );
507
		$wp_order_status	= $this->log->get( 'wp_order_status' );
508
509
		//Don't change order status if a refund has been requested
510
		$wp_refund_set       = wpsc_get_purchase_meta( $order_id, 'worldpay_refunded', true );
511
		$order_info = $this->refresh_transaction_info( $wp_transaction_id, ! (bool) $wp_refund_set );
512
		?>
513
514
		<div class="metabox-holder">
515
			<div id="wpsc-worldpay-payments" class="postbox">
516
				<h3 class='hndle'><?php _e( 'WorldPay Payments' , 'wp-e-commerce' ); ?></h3>
517
				<div class='inside'>
518
					<p><?php
519
							_e( 'Current status: ', 'wp-e-commerce' );
520
							echo wp_kses_data( $this->log->get( 'worldpay-status' ) );
521
						?>
522
					</p>
523
					<p><?php
524
							_e( 'Transaction ID: ', 'wp-e-commerce' );
525
							echo wp_kses_data( $wp_transaction_id );
526
						?>
527
					</p>
528
		<?php
529
530
		//Show actions based on order status
531
		switch ( $wp_order_status ) {
532
			case 'Open' :
533
				//Order is only authorized and still not captured/voided
534
				$actions['capture'] = array(
535
					'id'     => $wp_transaction_id,
536
					'button' => __( 'Capture funds', 'wp-e-commerce' )
537
				);
538
539
				//
540
				if ( ! $order_info['settled'] ) {
541
					//Void
542
					$actions['void'] = array(
543
						'id'     => $wp_transaction_id,
544
						'button' => __( 'Void order', 'wp-e-commerce' )
545
					);
546
				}
547
548
				break;
549
			case 'Completed' :
550
				//Order has been captured or its a direct payment
551
				if ( $order_info['settled'] ) {
552
					//Refund
553
					$actions['refund'] = array(
554
						'id'     => $wp_transaction_id,
555
						'button' => __( 'Refund order', 'wp-e-commerce' )
556
					);
557
				} else {
558
					//Void
559
					$actions['void'] = array(
560
						'id'     => $wp_transaction_id,
561
						'button' => __( 'Void order', 'wp-e-commerce' )
562
					);
563
				}
564
565
			break;
566
			case 'Refunded' :
567
				//Order is settled and a refund has been requested
568
				$wp_refund_id       = wpsc_get_purchase_meta( $order_id, 'worldpay_refund_id', true );
569
570
				if ( $wp_refund_id ) {
571
					//Get refund order status to check if its eligible for a void (not settled)
572
					$refund_status = $this->refresh_transaction_info( $wp_refund_id, false );
573
574
					if ( ! $refund_status['settled'] ) {
575
						//Show void only if not settled.
576
						$actions['void_refund'] = array(
577
							'id'     => $wp_refund_id,
578
							'button' => __( 'Void Refund request', 'wp-e-commerce' )
579
						);
580
					}
581
				}
582
583
				break;
584
			case 'Voided' :
585
			break;
586
		}
587
588
		if ( ! empty( $actions ) ) {
589
590
			echo '<p class="buttons">';
591
592
			foreach ( $actions as $action_name => $action ) {
593
				echo '<a href="#" class="button" data-action="' . $action_name . '" data-id="' . $action['id'] . '">' . $action['button'] . '</a> ';
594
			}
595
596
			echo '</p>';
597
598
		}
599
		?>
600
		<script type="text/javascript">
601
		jQuery( document ).ready( function( $ ) {
602
			$('#wpsc-worldpay-payments').on( 'click', 'a.button, a.refresh', function( e ) {
603
				var $this = $( this );
604
				e.preventDefault();
605
606
				var data = {
607
					action: 		'worldpay_order_action',
608
					security: 		'<?php echo wp_create_nonce( "wp_order_action" ); ?>',
609
					order_id: 		'<?php echo $order_id; ?>',
610
					worldpay_action: 	$this.data('action'),
611
					worldpay_id: 		$this.data('id'),
612
					worldpay_refund_amount: $('.worldpay_refund_amount').val(),
613
				};
614
615
				// Ajax action
616
				$.post( ajaxurl, data, function( result ) {
617
						location.reload();
618
					}, 'json' );
619
620
				return false;
621
			});
622
		} );
623
624
		</script>
625
		</div>
626
		</div>
627
		</div>
628
		<?php
629
	}
630
631
    /**
632
     * Get the order status from API
633
     *
634
     * @param  string $transaction_id
635
     */
636
	public function refresh_transaction_info( $transaction_id, $update = true ) {
637
638
		if ( $this->log->get( 'gateway' ) == 'worldpay' ) {
639
640
			$response = $this->gateway->execute( 'transactions/'. $transaction_id, null, 'GET' );
641
642
			if ( is_wp_error( $response ) ) {
643
				throw new Exception( $response->get_error_message() );
644
			}
645
646
			$response_object = array();
647
			$response_object['trans_type'] 	= $response['ResponseBody']->transactions[0]->transactionType;
648
			$response_object['settled'] 	= isset( $response['ResponseBody']->transactions[0]->settlementData );
649
650
			//Recheck status and update if required
651
			if ( $update ) {
652
				switch ( $response_object['trans_type'] ) {
653
					case 'AUTH_ONLY' :
654
						$this->log->set( 'wp_order_status', 'Open' )->save();
655
					break;
656
657
					case 'VOID' :
658
						$this->log->set( 'wp_order_status', 'Voided' )->save();
659
					break;
660
661
					case 'REFUND' :
662
					case 'CREDIT' :
663
						$this->log->set( 'wp_order_status', 'Refunded' )->save();
664
					break;
665
666
					case 'AUTH_CAPTURE' :
667
					case 'PRIOR_AUTH_CAPTURE' :
668
						$this->log->set( 'wp_order_status', 'Completed' )->save();
669
					break;
670
				}
671
			}
672
673
		return $response_object;
674
		}
675
	}
676
677
678
    /**
679
     * Void auth/capture
680
     *
681
     * @param  string $transaction_id
682
     */
683
    public function void_payment( $transaction_id ) {
684
685
		if ( $this->log->get( 'gateway' ) == 'worldpay' ) {
686
687
			$params = array(
688
				'amount'		=> $this->log->get( 'totalprice' ),
689
				'transactionId' => $transaction_id,
690
			);
691
692
			$response = $this->gateway->execute( 'Payments/Void', $params );
693
694
			if ( is_wp_error( $response ) ) {
695
				throw new Exception( $response->get_error_message() );
696
			}
697
698
			$this->log->set( 'wp_order_status', 'Voided' )->save();
699
			$this->log->set( 'worldpay-status', sprintf( __( 'Authorization voided (Auth ID: %s)', 'wp-e-commerce' ), $response['ResponseBody']->transaction->authorizationCode ) )->save();
700
			$this->log->set( 'processed', WPSC_Purchase_Log::INCOMPLETE_SALE )->save();
701
			$this->log->set( 'transactid', $response['ResponseBody']->transaction->transactionId )->save();
702
		}
703
    }
704
705
    /**
706
     * Refund payment
707
     *
708
     * @param  string $transaction_id
709
     */
710
    public function refund_payment( $transaction_id ) {
711
712
		if ( $this->log->get( 'gateway' ) == 'worldpay' ) {
713
714
			$params = array(
715
				'amount'		=> $this->log->get( 'totalprice' ),
716
				'transactionId' => $transaction_id,
717
718
			);
719
720
			$response = $this->gateway->execute( 'Payments/Refund', $params );
721
722
			if ( is_wp_error( $response ) ) {
723
				throw new Exception( $response->get_error_message() );
724
			}
725
726
			wpsc_add_purchase_meta( $this->log->get( 'id' ), 'worldpay_refunded', true );
727
			wpsc_add_purchase_meta( $this->log->get( 'id' ), 'worldpay_refund_id', $response['ResponseBody']->transaction->transactionId );
728
			$this->log->set( 'worldpay-status', sprintf( __( 'Refunded (Transaction ID: %s)', 'wp-e-commerce' ), $response['ResponseBody']->transaction->transactionId ) )->save();
729
			$this->log->set( 'processed', WPSC_Purchase_Log::REFUNDED )->save();
730
			$this->log->set( 'wp_order_status', 'Refunded' )->save();
731
			$this->log->set( 'transactid', $response['ResponseBody']->transaction->transactionId )->save();
732
		}
733
    }
734
735
    /**
736
     * Capture authorized payment
737
     *
738
     * @param  string $transaction_id
739
     */
740
    public function capture_payment( $transaction_id ) {
741
742
		if ( $this->log->get( 'gateway' ) == 'worldpay' ) {
743
744
			$params = array(
745
				'amount'		=> $this->log->get( 'totalprice' ),
746
				'transactionId' => $transaction_id,
747
			);
748
749
			$response = $this->gateway->execute( 'Payments/Capture', $params );
750
751
			if ( is_wp_error( $response ) ) {
752
				throw new Exception( $response->get_error_message() );
753
			}
754
755
			$this->log->set( 'wp_order_status', 'Completed' )->save();
756
757
			$this->log->set( 'worldpay-status', sprintf( __( 'Authorization Captured (Auth ID: %s)', 'wp-e-commerce' ), $response['ResponseBody']->transaction->authorizationCode ) )->save();
758
			$this->log->set( 'processed', WPSC_Purchase_Log::ACCEPTED_PAYMENT )->save();
759
			$this->log->set( 'transactid', $response['ResponseBody']->transaction->transactionId )->save();
760
		}
761
    }
762
763
    /**
764
     * Void a refund request
765
     *
766
     * @param  string $transaction_id
767
     */
768
    public function void_refund( $transaction_id ) {
769
770
		if ( $this->log->get( 'gateway' ) == 'worldpay' ) {
771
772
			$params = array(
773
				'amount'		=> $this->log->get( 'totalprice' ),
774
				'transactionId' => $transaction_id,
775
			);
776
777
			$response = $this->gateway->execute( 'Payments/Void', $params );
778
779
			if ( is_wp_error( $response ) ) {
780
				throw new Exception( $response->get_error_message() );
781
			}
782
783
			wpsc_delete_purchase_meta( $this->log->get( 'id' ), 'worldpay_refunded' );
784
			wpsc_delete_purchase_meta( $this->log->get( 'id' ), 'worldpay_refund_id' );
785
			$this->log->set( 'processed', WPSC_Purchase_Log::ACCEPTED_PAYMENT )->save();
786
			$this->log->set( 'wp_order_status', 'Completed' )->save();
787
			$this->log->set( 'worldpay-status', sprintf( __( 'Refund Voided (Transaction ID: %s)', 'wp-e-commerce' ), $response['ResponseBody']->transaction->transactionId ) )->save();
788
			$this->log->set( 'transactid', $response['ResponseBody']->transaction->transactionId )->save();
789
		}
790
    }
791
}
792