Completed
Push — master ( 764d24...7cd13b )
by Chris
01:37
created

class/class-edu-sveawebpay.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
defined( 'ABSPATH' ) or die( 'This plugin must be run within the scope of WordPress.' );
3
4
require_once( __DIR__ . '/class-edu-sveawebpay-config.php' );
5
6
use Svea\WebPay\WebPay;
7
use Svea\WebPay\WebPayItem;
8
9
if ( ! class_exists( 'EDU_SveaWebPay' ) ):
10
11
	/**
12
	 * EDU_SveaWebPay integrates EduAdmin-WordPress plugin with SveaWebPay as payment gateway
13
	 */
14
	class EDU_SveaWebPay extends EDU_Integration {
15
		/**
16
		 * Constructor
17
		 */
18
		public function __construct() {
19
			$this->id          = 'eduadmin-sveawebpay';
20
			$this->displayName = __( 'Svea Webpay (Checkout)', 'eduadmin-sveawebpay' );
21
			$this->description = '';
22
			$this->type        = 'payment';
23
24
			$this->init_form_fields();
25
			$this->init_settings();
26
27
			add_action( 'eduadmin-checkpaymentplugins', array( $this, 'intercept_booking' ) );
28
			add_action( 'eduadmin-processbooking', array( $this, 'process_booking' ) );
29
			add_action( 'eduadmin-bookingcompleted', array( $this, 'process_svearesponse' ) );
30
			add_action( 'wp_loaded', array( $this, 'process_paymentstatus' ) );
31
32
			add_shortcode( 'eduadmin-svea-testpage', array( $this, 'test_page' ) );
33
		}
34
35
		/**
36
		 * @param $attributes
37
		 */
38
		public function test_page( $attributes ) {
39
			$attributes = shortcode_atts(
40
				array(
41
					'bookingid'          => 0,
42
					'programmebookingid' => 0,
43
				),
44
				normalize_empty_atts( $attributes ),
45
				'test_page'
46
			);
47
48
			if ( $attributes['bookingid'] > 0 ) {
49
				$event_booking = EDUAPI()->OData->Bookings->GetItem(
50
					$attributes['bookingid'],
51
					null,
52
					'Customer($select=CustomerId;),ContactPerson($select=PersonId;),OrderRows',
53
					false
54
				);
55
			} elseif ( $attributes['programmebookingid'] > 0 ) {
56
				$event_booking = EDUAPI()->OData->ProgrammeBookings->GetItem(
57
					$attributes['programmebookingid'],
58
					null,
59
					'Customer($select=CustomerId;),ContactPerson($select=PersonId;),OrderRows',
60
					false
61
				);
62
			}
63
64
			$_customer = EDUAPI()->OData->Customers->GetItem(
65
				$event_booking['Customer']['CustomerId'],
66
				null,
67
				"BillingInfo",
68
				false
69
			);
70
71
			$_contact = EDUAPI()->OData->Persons->GetItem(
72
				$event_booking['ContactPerson']['PersonId'],
73
				null,
74
				null,
75
				false
76
			);
77
78
			$ebi = new EduAdmin_BookingInfo( $event_booking, $_customer, $_contact );
79
80
			if ( ! empty( EDU()->session['svea-order-id'] ) && ! empty( $_GET['svea_order_id'] ) && EDU()->session['svea-order-id'] === $_GET['svea_order_id'] ) {
81
				do_action( 'eduadmin-bookingcompleted', $ebi );
82
			} else {
83
				do_action( 'eduadmin-processbooking', $ebi );
84
			}
85
		}
86
87
88
		/**
89
		 * @param EduAdmin_BookingInfo|null $ebi
90
		 */
91
		public function intercept_booking( $ebi = null ) {
92
			if ( 'no' === $this->get_option( 'enabled', 'no' ) ) {
93
				return;
94
			}
95
96
			if ( ! empty( $_POST['act'] ) && ( 'bookCourse' === $_POST['act'] || 'bookProgramme' === $_POST['act'] ) ) {
97
				$ebi->NoRedirect = true;
98
			}
99
		}
100
101
		/**
102
		 * Initializes the settingsfields
103
		 */
104
		public function init_form_fields() {
105
			$this->setting_fields = array(
106
				'enabled'         => array(
107
					'title'       => __( 'Enabled', 'eduadmin-sveawebpay' ),
108
					'type'        => 'checkbox',
109
					'description' => __( 'Enables/Disables the integration with Svea WebPay', 'eduadmin-sveawebpay' ),
110
					'default'     => 'no',
111
				),
112
				'testrun'         => array(
113
					'title'       => __( 'Sandbox mode', 'eduadmin-sveawebpay' ),
114
					'type'        => 'checkbox',
115
					'description' => __( 'Activate sandbox mode', 'eduadmin-sveawebpay' ),
116
					'default'     => 'no',
117
				),
118
				'merchant_key'    => array(
119
					'title'       => __( 'Merchant key', 'eduadmin-sveawebpay' ),
120
					'type'        => 'text',
121
					'description' => __( 'Please enter your merchant key from Svea WebPay.', 'eduadmin-sveawebpay' ),
122
					'placeholder' => __( 'Merchant key', 'eduadmin-sveawebpay' ),
123
				),
124
				'merchant_secret' => array(
125
					'title'       => __( 'Merchant secret', 'eduadmin-sveawebpay' ),
126
					'type'        => 'password',
127
					'description' => __( 'Please enter your merchant secret from Svea WebPay', 'eduadmin-sveawebpay' ),
128
					'placeholder' => __( 'Merchant secret', 'eduadmin-sveawebpay' ),
129
				),
130
			);
131
		}
132
133
		/**
134
		 *
135
		 */
136
		public function process_svearesponse() {
137
			if ( 'no' === $this->get_option( 'enabled', 'no' ) ) {
138
				return;
139
			}
140
141 View Code Duplication
			if ( isset( $_REQUEST['edu-thankyou'] ) && isset( $_REQUEST['svea'] ) ) {
142
				$booking_id           = intval( $_GET['booking_id'] );
143
				$programme_booking_id = intval( $_GET['programme_booking_id'] );
144
145
				$deleted = $this->update_booking( intval( EDU()->session['svea-order-id'] ), $booking_id, $programme_booking_id );
146
147
				EDU()->session['svea-order-id'] = null;
148
149
				if ( $deleted ) {
150
					$this->handle_cancelled_payment();
151
				}
152
			}
153
		}
154
155
		/**
156
		 * @param $ebi EduAdmin_BookingInfo|null $bookingInfo
157
		 */
158
		public function process_booking( $ebi = null ) {
159
			if ( 'no' === $this->get_option( 'enabled', 'no' ) ) {
160
				return;
161
			}
162
163
			$ebi->NoRedirect = true;
164
165
			if ( empty( $_GET['svea_order_id'] ) || empty( EDU()->session['svea-order-id'] ) ) {
166
				$checkout = $this->create_checkout( $ebi );
167
168
				$snippet = $checkout['Gui']['Snippet'];
169
				echo "<div>{$snippet}</div>";
170
			}
171
		}
172
173
		/**
174
		 * @param $ebi EduAdmin_BookingInfo|null
175
		 *
176
		 * @returns array
177
		 */
178
		public function create_checkout( $ebi ) {
179
			$countries = EDUAPI()->OData->Countries->Search()['value'];
180
181
			$selectedCountry = 'SE';
182
			$selectedLocale  = 'sv-SE';
183
184
			$invoiceCountry = $ebi->Customer['BillingInfo']['Country'];
185
			if ( empty( $invoiceCountry ) ) {
186
				$invoiceCountry = $ebi->Customer['Country'];
187
			}
188
189
			foreach ( $countries as $country ) {
190
				if ( $invoiceCountry == $country['CountryName'] ) {
191
					$selectedCountry = $country['CountryCode'];
192
					if ( ! empty( $country['CultureName'] ) ) {
193
						$selectedLocale = $country['CultureName'];
194
					}
195
					break;
196
				}
197
			}
198
199
			$booking_id           = 0;
200
			$programme_booking_id = 0;
201
202
			$reference_id = 0;
203
204
			$_event = null;
0 ignored issues
show
$_event is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
205
206
			$eventName = '';
207
208 View Code Duplication
			if ( ! empty( $ebi->EventBooking['BookingId'] ) ) {
209
				$booking_id   = intval( $ebi->EventBooking['BookingId'] );
210
				$reference_id = $booking_id;
211
212
				$_event = EDUAPI()->OData->Events->GetItem( $ebi->EventBooking['EventId'], null );
213
214
				$eventName = $_event['EventName'];
215
			}
216
217 View Code Duplication
			if ( ! empty( $ebi->EventBooking['ProgrammeBookingId'] ) ) {
218
				$programme_booking_id = intval( $ebi->EventBooking['ProgrammeBookingId'] );
219
				$reference_id         = $programme_booking_id;
220
221
				$_event = EDUAPI()->OData->ProgrammeStarts->GetItem( $ebi->EventBooking['ProgrammeStartId'] );
222
223
				$eventName = $_event['ProgrammeStartName'];
224
			}
225
226
			$currency = EDU()->get_option( 'eduadmin-currency', 'SEK' );
227
228 View Code Duplication
			if ( 'no' !== $this->get_option( 'testrun', 'no' ) ) {
229
				$wpConfig = new EduSveaWebPayTestConfig( $this );
230
			} else {
231
				$wpConfig = new EduSveaWebPayProductionConfig( $this );
232
			}
233
234
			$wpOrder = WebPay::checkout( $wpConfig );
235
236
			$orderRow = WebPayItem::orderRow();
237
			$orderRow->setName( substr( $eventName, 0, 40 ) );
238
			$orderRow->setQuantity( 1 );
239
240
			$vatPercent = ( $ebi->EventBooking['VatSum'] / $ebi->EventBooking['TotalPriceExVat'] ) * 100;
241
			$orderRow->setVatPercent( $vatPercent );
242
			$orderRow->setAmountIncVat( (float) $ebi->EventBooking['TotalPriceIncVat'] );
243
244
			$customer = WebPayItem::companyCustomer();
245
246
			$customerName  = ! empty( $ebi->Customer['BillingInfo']['InvoiceName'] ) ? $ebi->Customer['BillingInfo']['InvoiceName'] : $ebi->Customer['CustomerName'];
247
			$streetAddress = ! empty( $ebi->Customer['BillingInfo']['Address'] ) ? $ebi->Customer['BillingInfo']['Address'] : $ebi->Customer['Address'];
248
			$zipCode       = ! empty( $ebi->Customer['BillingInfo']['Zip'] ) ? $ebi->Customer['BillingInfo']['Zip'] : $ebi->Customer['Zip'];
249
			$city          = $ebi->Customer['BillingInfo']['City'] ? $ebi->Customer['BillingInfo']['City'] : $ebi->Customer['City'];
250
			$phone         = $ebi->Customer['Phone'];
251
			$email         = ! empty( $ebi->Customer['BillingInfo']['Email'] ) ? $ebi->Customer['BillingInfo']['Email'] : $ebi->Customer['Email'];
252
253
			$customer->setCompanyName( $customerName );
254
			$customer->setStreetAddress( $streetAddress );
255
			$customer->setZipCode( $zipCode );
256
			$customer->setLocality( $city );
257
258
			if ( ! empty( $phone ) ) {
259
				$customer->setPhoneNumber( $phone );
260
				$phonePreset = WebPayItem::presetValue()
261
				                         ->setTypeName( \Svea\WebPay\Checkout\Model\PresetValue::PHONE_NUMBER )
262
				                         ->setValue( $phone )
263
				                         ->setIsReadonly( false );
264
				$wpOrder->addPresetValue( $phonePreset );
265
			}
266
			$customer->setEmail( $email );
267
268
			$zipPreset = WebPayItem::presetValue()
269
			                       ->setTypeName( \Svea\WebPay\Checkout\Model\PresetValue::POSTAL_CODE )
270
			                       ->setValue( $zipCode )
271
			                       ->setIsReadonly( false );
272
			$wpOrder->addPresetValue( $zipPreset );
273
274
			$emailPreset = WebPayItem::presetValue()
275
			                         ->setTypeName( \Svea\WebPay\Checkout\Model\PresetValue::EMAIL_ADDRESS )
276
			                         ->setValue( $email )
277
			                         ->setIsReadonly( false );
278
			$wpOrder->addPresetValue( $emailPreset );
279
280
			$current_url = esc_url( "{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}" );
281
282
			$defaultThankYou = add_query_arg(
283
				array(
284
					'edu-thankyou'         => $reference_id,
285
					'svea'                 => '1',
286
					'booking_id'           => $booking_id,
287
					'programme_booking_id' => $programme_booking_id,
288
					'edu-valid-form'       => wp_create_nonce( 'edu-booking-confirm' ),
289
					'act'                  => 'paymentCompleted',
290
				),
291
				@get_page_link( get_option( 'eduadmin-thankYouPage', '/' ) )
292
			);
293
294
			$defaultCancel = add_query_arg(
295
				array(
296
					'edu-thankyou'         => $reference_id,
297
					'svea'                 => '1',
298
					'booking_id'           => $booking_id,
299
					'programme_booking_id' => $programme_booking_id,
300
					'status'               => 'cancel'
301
				),
302
				$current_url
303
			);
304
305
			$defaultPushUrl = add_query_arg(
306
				array(
307
					'edu-thankyou'         => $reference_id,
308
					'svea'                 => '1',
309
					'booking_id'           => $booking_id,
310
					'programme_booking_id' => $programme_booking_id,
311
					'svea_order_id'        => '{checkout.order.uri}',
312
					'status'               => 'push'
313
				),
314
				$current_url
315
			);
316
317
			$defaultTermsUrl = get_option( 'eduadmin-bookingTermsLink' );
318
319
			$wpBuild = $wpOrder
320
				->setCurrency( $currency )
321
				->setCountryCode( $selectedCountry )
322
				->setClientOrderNumber( $reference_id )
323
				->addOrderRow( $orderRow )
324
				->setLocale( $selectedLocale )
325
				->setTermsUri( $defaultTermsUrl )
326
				->setConfirmationUri( $defaultThankYou )
327
				->setPushUri( $defaultPushUrl )
328
				->setCheckoutUri( $defaultCancel ); // We have no "checkout"-url.. So we just cancel the booking instead.
329
			$wpForm  = $wpBuild->createOrder();
330
331
			EDU()->session['svea-order-id'] = $wpForm['OrderId'];
332
333
			return $wpForm;
334
		}
335
336
		public function process_paymentstatus() {
337
			if ( ! empty( $_GET['svea_order_id'] ) && intval( $_GET['svea_order_id'] ) != 0 && ! empty( $_GET['status'] ) ) {
338
339
				$booking_id           = intval( $_GET['booking_id'] );
340
				$programme_booking_id = intval( $_GET['programme_booking_id'] );
341
342
				$this->update_booking( intval( $_GET['svea_order_id'] ), $booking_id, $programme_booking_id );
343
344
				exit( 0 );
345
			}
346
347 View Code Duplication
			if ( isset( $_REQUEST['edu-thankyou'] ) && isset( $_REQUEST['svea'] ) && ! empty( $_GET['status'] ) ) {
348
				$booking_id           = intval( $_GET['booking_id'] );
349
				$programme_booking_id = intval( $_GET['programme_booking_id'] );
350
351
				$deleted = $this->update_booking( intval( EDU()->session['svea-order-id'] ), $booking_id, $programme_booking_id );
352
353
				EDU()->session['svea-order-id'] = null;
354
355
				if ( $deleted ) {
356
					$this->handle_cancelled_payment();
357
				}
358
			}
359
		}
360
361
		private function handle_cancelled_payment() {
362
			@wp_redirect( get_home_url() );
363
			wp_add_inline_script( 'edu-svea-redirecthome', "location.href = '" . esc_js( get_home_url() ) . "';" );
364
			wp_enqueue_script( 'edu-svea-redirecthome', false, array( 'jquery' ) );
365
			exit( 0 );
366
		}
367
368
		/**
369
		 * @param $order_id numeric SVEA WebPay OrderId
370
		 * @param $booking_id
371
		 * @param $programme_booking_id
372
		 *
373
		 * @return bool If the booking was deleted, due to cancellation
374
		 * @throws \Svea\WebPay\BuildOrder\Validator\ValidationException
375
		 */
376
		private function update_booking( $order_id, $booking_id, $programme_booking_id ) {
377 View Code Duplication
			if ( 'no' !== $this->get_option( 'testrun', 'no' ) ) {
378
				$wpConfig = new EduSveaWebPayTestConfig( $this );
379
			} else {
380
				$wpConfig = new EduSveaWebPayProductionConfig( $this );
381
			}
382
383
			$wpOrder = WebPay::checkout( $wpConfig );
384
			$wpOrder->setCheckoutOrderId( $order_id );
385
386
			$order = $wpOrder->getOrder();
387
388
			$delete_booking = false;
389
390
			$patch_booking                  = new stdClass();
391
			$patch_booking->PaymentMethodId = 2;
392
393
			if ( 'Cancelled' === $order['Status'] ) {
394
				$patch_booking->Paid = false;
395
				$delete_booking      = true;
396
			} else if ( 'Final' === $order['Status'] ) {
397
				$patch_booking->Paid = true;
398
			} else if ( 'Created' === $order['Status'] ) {
399
				$patch_booking->Paid = false;
400
			}
401
402
			if ( isset( $_GET['status'] ) && 'cancel' === $_GET['status'] ) {
403
				$patch_booking->Paid = false;
404
				$delete_booking      = true;
405
			}
406
407
			if ( $booking_id > 0 ) {
408
				EDUAPI()->REST->Booking->PatchBooking(
409
					$booking_id,
410
					$patch_booking
411
				);
412
413
				if ( $delete_booking ) {
414
					EDUAPI()->REST->Booking->DeleteBooking( $booking_id );
415
				}
416
			}
417
418
			if ( $programme_booking_id > 0 ) {
419
420
				EDUAPI()->REST->ProgrammeBooking->PatchBooking(
421
					$programme_booking_id,
422
					$patch_booking
423
				);
424
425
				if ( $delete_booking ) {
426
					EDUAPI()->REST->ProgrammeBooking->DeleteBooking( $programme_booking_id );
427
				}
428
			}
429
430
			return $delete_booking;
431
		}
432
	}
433
434
endif;
435