Passed
Push — master ( 5c12d3...f60c20 )
by Chris
02:51
created

class-edu-klarnacheckout.php (6 issues)

1
<?php
2
defined( 'ABSPATH' ) || die( 'This plugin must be run within the scope of WordPress.' );
3
4
if ( ! class_exists( 'EDU_KlarnaCheckout' ) ) {
5
	class EDU_KlarnaCheckout extends EDU_Integration {
6
		public function __construct() {
7
			$this->id          = 'eduadmin-klarnacheckout';
8
			$this->displayName = __( 'Klarna Checkout', 'eduadmin-wp-klarna-checkout' );
9
			$this->description = '';
10
			$this->type        = 'payment';
11
12
			$this->init_form_fields();
13
			$this->init_settings();
14
15
			add_action( 'eduadmin-checkpaymentplugins', array( $this, 'intercept_booking' ) );
16
			add_action( 'eduadmin-processbooking', array( $this, 'process_booking' ) );
17
			add_action( 'eduadmin-bookingcompleted', array( $this, 'process_klarnaresponse' ) );
18
			add_action( 'wp_loaded', array( $this, 'process_paymentstatus' ) );
19
20
			add_shortcode( 'eduadmin-klarna-testpage', array( $this, 'test_page' ) );
21
		}
22
23
		/**
24
		 * @param $attributes
25
		 */
26
		public function test_page( $attributes ) {
27
			$attributes = shortcode_atts(
28
				array(
29
					'bookingid'          => 0,
30
					'programmebookingid' => 0,
31
				),
32
				normalize_empty_atts( $attributes ),
33
				'test_page'
34
			);
35
36
			if ( $attributes['bookingid'] > 0 ) {
37
				$event_booking = EDUAPI()->OData->Bookings->GetItem(
0 ignored issues
show
The function EDUAPI was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

37
				$event_booking = /** @scrutinizer ignore-call */ EDUAPI()->OData->Bookings->GetItem(
Loading history...
38
					$attributes['bookingid'],
39
					null,
40
					'Customer($select=CustomerId;),ContactPerson($select=PersonId;),OrderRows',
41
					false
42
				);
43
			} elseif ( $attributes['programmebookingid'] > 0 ) {
44
				$event_booking = EDUAPI()->OData->ProgrammeBookings->GetItem(
45
					$attributes['programmebookingid'],
46
					null,
47
					'Customer($select=CustomerId;),ContactPerson($select=PersonId;),OrderRows',
48
					false
49
				);
50
			}
51
52
			$_customer = EDUAPI()->OData->Customers->GetItem(
53
				$event_booking['Customer']['CustomerId'],
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $event_booking does not seem to be defined for all execution paths leading up to this point.
Loading history...
54
				null,
55
				"BillingInfo",
56
				false
57
			);
58
59
			$_contact = EDUAPI()->OData->Persons->GetItem(
60
				$event_booking['ContactPerson']['PersonId'],
61
				null,
62
				null,
63
				false
64
			);
65
66
			$ebi = new EduAdmin_BookingInfo( $event_booking, $_customer, $_contact );
67
68
			if ( ! empty( EDU()->session['klarna-order-id'] ) && ! empty( $_GET['klarna_order_id'] ) && EDU()->session['klarna-order-id'] === $_GET['klarna_order_id'] ) {
69
				do_action( 'eduadmin-bookingcompleted', $ebi );
70
			} else {
71
				do_action( 'eduadmin-processbooking', $ebi );
72
			}
73
		}
74
75
		/**
76
		 * @param EduAdmin_BookingInfo|null $ebi
77
		 */
78
		public function intercept_booking( $ebi = null ) {
79
			if ( 'no' === $this->get_option( 'enabled', 'no' ) ) {
80
				return;
81
			}
82
83
			if ( ! empty( $_POST['act'] ) && ( 'bookCourse' === $_POST['act'] || 'bookProgramme' === $_POST['act'] ) ) {
84
				$ebi->NoRedirect = true;
85
			}
86
		}
87
88
		/**
89
		 * @param EduAdmin_BookingInfo|null $ebi
90
		 */
91
		public function process_booking( $ebi = null ) {
92
			if ( 'no' === $this->get_option( 'enabled', 'no' ) ) {
93
				return;
94
			}
95
96
			$ebi->NoRedirect = true;
97
98
			if ( empty( $_GET['klarna_order_id'] ) || empty( EDU()->session['klarna-order-id'] ) ) {
99
				$checkout = $this->create_checkout( $ebi );
100
101
				$snippet = $checkout['gui']['snippet'];
102
				echo "<div>{$snippet}</div>";
103
			}
104
		}
105
106
		public function process_klarnaresponse() {
107
			if ( 'no' === $this->get_option( 'enabled', 'no' ) ) {
108
				return;
109
			}
110
			$checkout_url  = ! checked( $this->get_option( 'test_mode', 'no' ), '1', false ) ? Klarna_Checkout_Connector::BASE_URL : Klarna_Checkout_Connector::BASE_TEST_URL;
111
			$shared_secret = $this->get_option( 'shared_secret', '' );
112
113
			if ( ! empty( $_GET['klarna_order_id'] ) && ! empty( EDU()->session['klarna-order-id'] ) && EDU()->session['klarna-order-id'] === $_GET['klarna_order_id'] ) {
114
				try {
115
					$connector = Klarna_Checkout_Connector::create(
116
						$shared_secret,
117
						$checkout_url
118
					);
119
120
					$order_id = EDU()->session['klarna-order-id'];
121
122
					$order = new Klarna_Checkout_Order( $connector, $order_id );
123
124
					$order->fetch();
125
126
					$snippet = $order['gui']['snippet'];
127
					echo "<div>{$snippet}</div>";
128
					EDU()->session['klarna-order-id'] = null;
129
130
				} catch ( Klarna_Checkout_ApiErrorException $ex ) {
131
					EDU()->write_debug( $ex->getMessage() );
132
					EDU()->write_debug( $ex->getPayload() );
133
				}
134
			}
135
		}
136
137
		public function init_form_fields() {
138
			$this->setting_fields = array(
139
				'enabled'       => array(
140
					'title'       => __( 'Enabled', 'edauadmin-wp-klarna-checkout' ),
141
					'type'        => 'checkbox',
142
					'description' => __( 'Enables/Disabled the integration with Klarna Checkout', 'eduadmin-wp-klarna-checkout' ),
143
					'default'     => 'no',
144
				),
145
				'eid'           => array(
146
					'title'       => __( 'EID', 'eduadmin-wp-klarna-checkout' ),
147
					'type'        => 'text',
148
					'description' => __( 'The EID to connect to Klarna Checkout v2', 'eduadmin-wp-klarna-checkout' ),
149
					'default'     => '',
150
				),
151
				'shared_secret' => array(
152
					'title'       => __( 'Shared secret', 'eduadmin-wp-klarna-checkout' ),
153
					'type'        => 'password',
154
					'description' => __( 'The shared secret to connect to Klarna Checkout v2', 'eduadmin-wp-klarna-checkout' ),
155
					'default'     => '',
156
				),
157
				'termsurl'      => array(
158
					'title'       => __( 'Terms and Conditions URL', 'eduadmin-wp-klarna-checkout' ),
159
					'type'        => 'text',
160
					'description' => __( 'This URL is required for Klarna Checkout', 'eduadmin-wp-klarna-checkout' ),
161
					'default'     => '',
162
				),
163
				'test_mode'     => array(
164
					'title'       => __( 'Test mode', 'eduadmin-wp-klarna-checkout' ),
165
					'type'        => 'checkbox',
166
					'description' => __( 'Enables test mode, so you can test the integration', 'eduadmin-wp-klarna-checkout' ),
167
					'default'     => 'no',
168
				),
169
			);
170
		}
171
172
		/**
173
		 * @param EduAdmin_BookingInfo|null $ebi
174
		 *
175
		 * @return Klarna_Checkout_Order|null
176
		 */
177
		public function create_checkout( $ebi = null ) {
178
179
			$checkout_url  = ! checked( $this->get_option( 'test_mode', 'no' ), '1', false ) ? Klarna_Checkout_Connector::BASE_URL : Klarna_Checkout_Connector::BASE_TEST_URL;
180
			$shared_secret = $this->get_option( 'shared_secret', '' );
181
182
			$create = array();
183
184
			$organization     = EDUAPIHelper()->GetOrganization();
185
			$purchase_country = $organization["CountryCode"];
186
187
			if ( ! empty( $ebi->Customer["CountryCode"] ) ) {
188
				$purchase_country = $ebi->Customer["CountryCode"];
189
190
				if ( ! empty( $ebi->Customer["BillingInfo"]["CountryCode"] ) ) {
191
					$purchase_country = $ebi->Customer["BillingInfo"]["CountryCode"];
192
				}
193
			}
194
195
			$create['locale']            = strtolower( str_replace( '_', '-', get_locale() ) );
196
			$create['purchase_country']  = $purchase_country;
197
			$create['purchase_currency'] = get_option( 'eduadmin-currency', 'SEK' );
198
199
			$merchant              = array();
200
			$merchant['id']        = $this->get_option( 'eid', '' );
201
			$merchant['terms_uri'] = $this->get_option( 'termsurl', '' );
202
203
			$current_url = esc_url( "{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}" );
204
205
			$booking_id           = 0;
206
			$programme_booking_id = 0;
207
208
			$reference_id = 0;
209
210
			$_event = null;
211
212
			if ( ! empty( $ebi->EventBooking['BookingId'] ) ) {
213
				$booking_id   = intval( $ebi->EventBooking['BookingId'] );
214
				$reference_id = $booking_id;
215
216
				$_event = EDUAPI()->OData->Events->GetItem( $ebi->EventBooking['EventId'] );
0 ignored issues
show
The function EDUAPI was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

216
				$_event = /** @scrutinizer ignore-call */ EDUAPI()->OData->Events->GetItem( $ebi->EventBooking['EventId'] );
Loading history...
217
			}
218
219
			if ( ! empty( $ebi->EventBooking['ProgrammeBookingId'] ) ) {
220
				$programme_booking_id = intval( $ebi->EventBooking['ProgrammeBookingId'] );
221
				$reference_id         = $programme_booking_id;
222
223
				$_event = EDUAPI()->OData->ProgrammeStarts->GetItem( $ebi->EventBooking['ProgrammeStartId'] );
224
			}
225
226
			$rowExtraInfo = "";
227
228
			if ( null != $_event ) {
229
				if ( ! empty( $_event['City'] ) ) {
230
					$rowExtraInfo .= ';' . $_event['City'];
231
				}
232
233
				if ( ! empty( $_event['StartDate'] ) ) {
234
					$rowExtraInfo .= ';' . date( "Y-m-d", strtotime( $_event['StartDate'] ) );
235
				}
236
237
				if ( ! empty( $_event['EndDate'] ) ) {
238
					$rowExtraInfo .= ';' . date( "Y-m-d", strtotime( $_event['EndDate'] ) );
239
				}
240
			}
241
242
			$confirmation_url = add_query_arg(
243
				array(
244
					'klarna_order_id'      => '{checkout.order.id}',
245
					'booking_id'           => $booking_id,
246
					'programme_booking_id' => $programme_booking_id,
247
					'edu-valid-form'       => wp_create_nonce( 'edu-booking-confirm' ),
248
					'act'                  => 'paymentCompleted',
249
					'edu-thankyou'         => $reference_id
250
				),
251
				$current_url
252
			);
253
254
			$push_url = add_query_arg(
255
				array(
256
					'klarna_order_id'      => '{checkout.order.id}',
257
					'booking_id'           => $booking_id,
258
					'programme_booking_id' => $programme_booking_id,
259
					'status'               => 'push',
260
				),
261
				$current_url
262
			);
263
264
			$merchant['checkout_uri']     = $current_url;
265
			$merchant['confirmation_uri'] = $confirmation_url;
266
			$merchant['push_uri']         = $push_url;
267
268
			$create['merchant'] = $merchant;
269
270
			$create['merchant_reference']             = array();
271
			$create['merchant_reference']['orderid1'] = $reference_id;
272
			$create['merchant_reference']['orderid2'] = $reference_id;
273
274
			$create['cart']          = array();
275
			$create['cart']['items'] = array();
276
277
			foreach ( $ebi->EventBooking['OrderRows'] as $order_row ) {
278
				$cart_item = array();
279
280
				$cart_item['reference'] = $order_row['ItemNumber'];
281
				$cart_item['name']      = $order_row['Description'] . $rowExtraInfo;
282
				$cart_item['quantity']  = intval( $order_row['Quantity'] );
283
284
				if ( ! $order_row['PriceIncVat'] ) {
285
					$price_per_unit = $order_row['PricePerUnit'] * ( 1 + ( $order_row['VatPercent'] / 100 ) ) * 100;
286
				} else {
287
					$price_per_unit = $order_row['PricePerUnit'] * 100;
288
				}
289
290
				$cart_item['unit_price']    = $price_per_unit;
291
				$cart_item['tax_rate']      = intval( $order_row['VatPercent'] * 100 );
292
				$cart_item['discount_rate'] = intval( $order_row['DiscountPercent'] * 100 );
293
294
				$create['cart']['items'][] = $cart_item;
295
			}
296
297
			try {
298
				$connector = Klarna_Checkout_Connector::create(
299
					$shared_secret,
300
					$checkout_url
301
				);
302
303
				$order = new Klarna_Checkout_Order( $connector );
304
				$order->create( $create );
305
306
				$order->fetch();
307
308
				$order_id                         = $order['id'];
309
				EDU()->session['klarna-order-id'] = $order_id;
310
311
				return $order;
312
			} catch ( Klarna_Checkout_ApiErrorException $ex ) {
313
				EDU()->write_debug( $ex->getMessage() );
314
				EDU()->write_debug( $ex->getPayload() );
315
316
				return null;
317
			}
318
		}
319
320
		public function process_paymentstatus() {
321
			if ( ! empty( $_GET['klarna_order_id'] ) && ! empty( $_GET['status'] ) ) {
322
				$checkout_url  = ! checked( $this->get_option( 'test_mode', 'no' ), '1', false ) ? Klarna_Checkout_Connector::BASE_URL : Klarna_Checkout_Connector::BASE_TEST_URL;
323
				$shared_secret = $this->get_option( 'shared_secret', '' );
324
325
				try {
326
					$connector = Klarna_Checkout_Connector::create(
327
						$shared_secret,
328
						$checkout_url
329
					);
330
331
					$order_id = $_GET['klarna_order_id'];
332
333
					$order = new Klarna_Checkout_Order( $connector, $order_id );
334
335
					$order->fetch();
336
337
					$booking_id           = intval( $_GET['booking_id'] );
338
					$programme_booking_id = intval( $_GET['programme_booking_id'] );
339
340
341
					if ( 'checkout_complete' === $order['status'] ) {
342
343
						$patch_booking       = new stdClass();
344
						$patch_booking->Paid = true;
345
346
						// We're setting this as a Card Payment, so that our service in the background will remove it if it doesn't get paid in time (15 minute slot)
347
						$patch_booking->PaymentMethodId = 2;
348
349
						if ( $booking_id > 0 ) {
350
							EDUAPI()->REST->Booking->PatchBooking(
0 ignored issues
show
The function EDUAPI was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

350
							/** @scrutinizer ignore-call */ 
351
       EDUAPI()->REST->Booking->PatchBooking(
Loading history...
351
								$booking_id,
352
								$patch_booking
353
							);
354
						}
355
356
						if ( $programme_booking_id > 0 ) {
357
							EDUAPI()->REST->ProgrammeBooking->PatchBooking(
358
								$programme_booking_id,
359
								$patch_booking
360
							);
361
						}
362
363
						$update           = array();
364
						$update['status'] = 'created';
365
						$order->update( $update );
366
					}
367
					exit( 0 );
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
368
				} catch ( Klarna_Checkout_ApiErrorException $ex ) {
369
					EDU()->write_debug( $ex->getMessage() );
370
					EDU()->write_debug( $ex->getPayload() );
371
					exit( 1 );
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
372
				}
373
			}
374
		}
375
	}
376
}
377