Completed
Push — master ( 9b8bae...4c9433 )
by
unknown
05:21
created

WPSC_Payment_Gateway_WorldPay::load()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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