Failed Conditions
Push — develop ( bbd286...0a32cc )
by Reüel
03:35
created

Gateway::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 9
ccs 0
cts 7
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * Gateway
4
 *
5
 * @author    Pronamic <[email protected]>
6
 * @copyright 2005-2019 Pronamic
7
 * @license   GPL-3.0-or-later
8
 * @package   Pronamic\WordPress\Pay\Gateways\Adyen
9
 */
10
11
namespace Pronamic\WordPress\Pay\Gateways\Adyen;
12
13
use Pronamic\WordPress\Pay\Core\Gateway as Core_Gateway;
14
use Pronamic\WordPress\Pay\Core\Statuses as Core_Statuses;
15
use Pronamic\WordPress\Pay\Core\PaymentMethods;
16
use Pronamic\WordPress\Pay\Core\Util;
17
use Pronamic\WordPress\Pay\Payments\Payment;
18
use Pronamic\WordPress\Pay\Plugin;
19
20
/**
21
 * Gateway
22
 *
23
 * @author  Remco Tolsma
24
 * @version 1.0.0
25
 * @since   1.0.0
26
 * @link    https://github.com/adyenpayments/php/blob/master/generatepaymentform.php
27
 */
28
class Gateway extends Core_Gateway {
29
	/**
30
	 * Slug of this gateway.
31
	 *
32
	 * @var string
33
	 */
34
	const SLUG = 'adyen';
35
36
	/**
37
	 * Client.
38
	 *
39
	 * @var Client
40
	 */
41
	protected $client;
42
43
	/**
44
	 * Constructs and initializes an Adyen gateway.
45
	 *
46
	 * @param Config $config Config.
47
	 */
48
	public function __construct( Config $config ) {
49
		parent::__construct( $config );
50
51
		$this->set_method( self::METHOD_HTTP_REDIRECT );
52
		$this->set_slug( self::SLUG );
53
54
		$this->client = new Client( $config->api_key, $config->api_live_url_prefix );
55
		$this->client->set_merchant_account( $config->merchant_account );
56
		$this->client->set_mode( $config->mode );
57
	}
58
59
	/**
60
	 * Get supported payment methods
61
	 *
62
	 * @see Core_Gateway::get_supported_payment_methods()
63
	 */
64
	public function get_supported_payment_methods() {
65
		return array(
66
			PaymentMethods::BANCONTACT,
67
			PaymentMethods::CREDIT_CARD,
68
			PaymentMethods::DIRECT_DEBIT,
69
			PaymentMethods::GIROPAY,
70
			PaymentMethods::IDEAL,
71
			PaymentMethods::MAESTRO,
72
			PaymentMethods::SOFORT,
73
		);
74
	}
75
76
	/**
77
	 * Start.
78
	 *
79
	 * @param Payment $payment Payment.
80
	 *
81
	 * @see Plugin::start()
82
	 */
83
	public function start( Payment $payment ) {
84
		// Payment request.
85
		$request = new PaymentRequest();
86
87
		$request->merchant_account = $this->config->merchant_account;
88
		$request->return_url       = $payment->get_return_url();
89
		$request->reference        = $payment->get_id();
90
		$request->origin_url       = home_url();
91
		$request->sdk_version      = '1.6.3';
92
		$request->channel          = 'Web';
93
94
		// Amount.
95
		$request->currency     = $payment->get_total_amount()->get_currency()->get_alphabetic_code();
96
		$request->amount_value = $payment->get_total_amount()->get_cents(); // @todo Money +get_minor_units().
97
98
		// Payment method. Take leap of faith for unknown payment method types.
99
		$adyen_method = PaymentMethodType::transform( $payment->get_method(), $payment->get_method() );
100
101
		$request->payment_method = array(
102
			'type' => $adyen_method,
103
		);
104
105
		switch ( $payment->get_method() ) {
106
			case PaymentMethods::IDEAL:
107
				$request->payment_method['issuer'] = $payment->get_issuer();
108
109
				break;
110
		}
111
112
		// Country.
113
		$locale = get_locale();
114
115
		if ( null !== $payment->get_customer() ) {
116
			$locale = $payment->get_customer()->get_locale();
117
		}
118
119
		$locale = explode( '_', $locale );
120
121
		$request->country_code = strtoupper( substr( $locale[1], 0, 2 ) );
122
123
		// Shopper.
124
		$request->shopper_statement = $payment->get_description();
125
126
		if ( null !== $payment->get_customer() ) {
127
			$request->shopper_ip               = $payment->get_customer()->get_ip_address();
128
			$request->shopper_gender           = $payment->get_customer()->get_gender();
129
			$request->shopper_locale           = $payment->get_customer()->get_locale();
130
			$request->shopper_reference        = $payment->get_customer()->get_user_id();
131
			$request->shopper_telephone_number = $payment->get_customer()->get_phone();
132
133
			if ( null !== $payment->get_customer()->get_name() ) {
134
				$request->shopper_first_name = $payment->get_customer()->get_name()->get_first_name();
135
				$request->shopper_name_infix = $payment->get_customer()->get_name()->get_middle_name();
136
				$request->shopper_last_name  = $payment->get_customer()->get_name()->get_last_name();
137
			}
138
		}
139
140
		// Create payment or payment session.
141
		switch ( $payment->get_method() ) {
142
			case PaymentMethods::IDEAL:
143
			case PaymentMethods::SOFORT:
144
				// API integration.
145
				$result = $this->client->create_payment( $request );
146
147
				break;
148
			default:
149
				// Web SDK integration.
150
				$allowed_methods = array( $adyen_method );
151
152
				// Add all available payment methods if no payment method is given.
153
				if ( empty( $adyen_method ) ) {
154
					$allowed_methods = array();
155
156
					foreach ( $this->get_available_payment_methods() as $method ) {
157
						$allowed_methods[] = PaymentMethodType::transform( $method );
158
					}
159
				}
160
161
				// Set allowed payment methods.
162
				$request->allowed_payment_methods = $allowed_methods;
163
164
				// Create payment session.
165
				$result = $this->client->create_payment_session( $request );
166
		}
167
168
		if ( ! $result ) {
169
			$this->error = $this->client->get_error();
170
171
			return;
172
		}
173
174
		if ( isset( $result->paymentSession ) ) {
175
			// No cache.
176
			Util::no_cache();
177
178
			$redirect_message = '<div id="pronamic-pay-checkout"></div><div style="clear:both;"></div>';
179
180
			include Plugin::$dirname . '/views/redirect-message.php';
181
182
			?>
183
184
			<script type="text/javascript" src="https://checkoutshopper-test.adyen.com/checkoutshopper/assets/js/sdk/checkoutSDK.1.6.3.min.js"></script>
185
186
			<script type="text/javascript">
187
			// Initiate the Adyen Checkout form.
188
			var checkout = chckt.checkout(
189
				'<?php echo $result->paymentSession; ?>',
190
				'#pronamic-pay-checkout',
191
				{ context: '<?php echo( self::MODE_TEST === $this->config->mode ? 'test' : 'live' ); ?>' }
192
			);
193
194
			// Redirect once payment completes.
195
			chckt.hooks.beforeComplete = function ( node, paymentData ) {
196
				if ( "undefined" !== paymentData.payload ) {
197
					console.log( paymentData );
198
199
					window.location.href = '<?php echo $payment->get_return_url(); ?>&payload=' + encodeURIComponent( paymentData.payload );
200
201
					return false;
202
				}
203
			};
204
			</script>
205
206
			<?php
207
208
			exit;
0 ignored issues
show
Best Practice introduced by
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...
209
		}
210
211
		// Set transaction ID.
212
		if ( isset( $result->pspReference ) ) {
213
			$payment->set_transaction_id( $result->pspReference );
214
		}
215
216
		// Set redirect URL.
217
		if ( isset( $result->redirect->url ) ) {
218
			$payment->set_action_url( $result->redirect->url );
219
		}
220
	}
221
222
	/**
223
	 * Update status of the specified payment.
224
	 *
225
	 * @param Payment $payment Payment.
226
	 *
227
	 * @return void
228
	 */
229
	public function update_status( Payment $payment ) {
230
		// Maybe process stored webhook notification.
231
		$this->maybe_handle_notification( $payment );
232
233
		// Process payload on return.
234
		if ( ! filter_has_var( INPUT_GET, 'payload' ) ) {
235
			return;
236
		}
237
238
		$status = null;
239
240
		$payload = filter_input( INPUT_GET, 'payload', FILTER_SANITIZE_STRING );
241
242
		switch ( $payment->get_method() ) {
243
			case PaymentMethods::IDEAL:
244
			case PaymentMethods::SOFORT:
245
				$result = $this->client->get_payment_details( $payload );
246
247
				break;
248
			default:
249
				$result = $this->client->get_payment_result( $payload );
250
		}
251
252
		if ( $result ) {
253
			$status = Statuses::transform( $result->resultCode );
254
255
			$psp_reference = $result->pspReference;
256
		}
257
258
		// Handle errors.
259
		if ( empty( $status ) ) {
260
			$payment->set_status( Core_Statuses::FAILURE );
261
262
			$this->error = $this->client->get_error();
263
264
			return;
265
		}
266
267
		// Update status.
268
		$payment->set_status( $status );
269
270
		// Update transaction ID.
271
		if ( isset( $psp_reference ) ) {
272
			$payment->set_transaction_id( $psp_reference );
273
		}
274
	}
275
276
	/**
277
	 * Maybe handle notification.
278
	 *
279
	 * @param Payment $payment      Payment.
280
	 */
281
	public function maybe_handle_notification( Payment $payment ) {
282
		$notification = $payment->get_meta( 'adyen_notification' );
283
284
		if ( empty( $notification ) ) {
285
			return;
286
		}
287
288
		$notification = json_decode( $notification );
289
290
		if ( ! is_object( $notification ) ) {
291
			return;
292
		}
293
294
		switch ( $notification->eventCode ) {
295
			case EventCodes::AUTHORIZATION:
296
				$this->handle_authorization_event( $payment, $notification );
297
298
				break;
299
		}
300
301
		$payment->set_meta( 'adyen_notification', null );
302
	}
303
304
	/**
305
	 * Handle authorization event.
306
	 *
307
	 * @param Payment $payment      Payment.
308
	 * @param object  $notification Notification.
309
	 */
310
	public function handle_authorization_event( Payment $payment, $notification ) {
311
		if ( ! is_object( $notification ) ) {
312
			return;
313
		}
314
315
		$success = $notification->success;
316
317
		if ( 'true' === $success ) {
318
			$status = Core_Statuses::SUCCESS;
319
		} else {
320
			$status = Core_Statuses::FAILURE;
321
322
			// Add note.
323
			$note = sprintf(
324
				/* translators: %s: failure reason message */
325
				__( 'Failure reason: %s.', 'pronamic_ideal' ),
326
				esc_html( $notification->reason )
327
			);
328
329
			$payment->add_note( $note );
330
		}
331
332
		$payment->set_status( $status );
333
	}
334
335
	/**
336
	 * Get available payment methods.
337
	 *
338
	 * @see Core_Gateway::get_available_payment_methods()
339
	 */
340
	public function get_available_payment_methods() {
341
		$payment_methods = array();
342
343
		// Get active payment methods for Adyen account.
344
		$methods = $this->client->get_payment_methods();
345
346
		if ( ! $methods ) {
0 ignored issues
show
introduced by
The condition $methods is always false.
Loading history...
347
			$this->error = $this->client->get_error();
348
349
			return $payment_methods;
350
		}
351
352
		// Transform to WordPress payment methods.
353
		foreach ( $methods as $method => $details ) {
354
			$payment_method = PaymentMethodType::transform_gateway_method( $method );
355
356
			if ( $payment_method ) {
357
				$payment_methods[] = $payment_method;
358
			}
359
		}
360
361
		$payment_methods = array_unique( $payment_methods );
362
363
		return $payment_methods;
364
	}
365
366
	/**
367
	 * Get issuers.
368
	 *
369
	 * @see Pronamic_WP_Pay_Gateway::get_issuers()
370
	 */
371
	public function get_issuers() {
372
		$groups = array();
373
374
		$payment_method = PaymentMethodType::transform( PaymentMethods::IDEAL );
375
376
		$result = $this->client->get_issuers( $payment_method );
377
378
		if ( ! $result ) {
0 ignored issues
show
introduced by
The condition $result is always false.
Loading history...
379
			$this->error = $this->client->get_error();
380
381
			return $groups;
382
		}
383
384
		$groups[] = array(
385
			'options' => $result,
386
		);
387
388
		return $groups;
389
	}
390
}
391