Completed
Push — master ( b67a38...c6217a )
by Aimeos
15:25
created

PayPalExpress::getOrderDetails()   D

Complexity

Conditions 8
Paths 1200

Size

Total Lines 87
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 56
nc 1200
nop 1
dl 0
loc 87
rs 4.4224
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Metaways Infosystems GmbH, 2012
6
 * @copyright Aimeos (aimeos.org), 2015-2016
7
 * @package MShop
8
 * @subpackage Service
9
 */
10
11
12
namespace Aimeos\MShop\Service\Provider\Payment;
13
14
15
/**
16
 * Payment provider for paypal express orders.
17
 *
18
 * @package MShop
19
 * @subpackage Service
20
 */
21
class PayPalExpress
22
	extends \Aimeos\MShop\Service\Provider\Payment\Base
0 ignored issues
show
Coding Style introduced by
Expected 0 spaces between "Base" and comma; 1 found
Loading history...
23
	implements \Aimeos\MShop\Service\Provider\Payment\Iface
24
{
25
	private $apiendpoint;
26
27
	private $beConfig = array(
28
		'paypalexpress.ApiUsername' => array(
29
			'code' => 'paypalexpress.ApiUsername',
30
			'internalcode'=> 'paypalexpress.ApiUsername',
31
			'label'=> 'Username',
32
			'type'=> 'string',
33
			'internaltype'=> 'string',
34
			'default'=> '',
35
			'required'=> true,
36
		),
37
		'paypalexpress.AccountEmail' => array(
38
			'code' => 'paypalexpress.AccountEmail',
39
			'internalcode'=> 'paypalexpress.AccountEmail',
40
			'label'=> 'Registered e-mail address of the shop owner in PayPal',
41
			'type'=> 'string',
42
			'internaltype'=> 'string',
43
			'default'=> '',
44
			'required'=> true,
45
		),
46
		'paypalexpress.ApiPassword' => array(
47
			'code' => 'paypalexpress.ApiPassword',
48
			'internalcode'=> 'paypalexpress.ApiPassword',
49
			'label'=> 'Password',
50
			'type'=> 'string',
51
			'internaltype'=> 'string',
52
			'default'=> '',
53
			'required'=> true,
54
		),
55
		'paypalexpress.ApiSignature' => array(
56
			'code' => 'paypalexpress.ApiSignature',
57
			'internalcode'=> 'paypalexpress.ApiSignature',
58
			'label'=> 'Signature',
59
			'type'=> 'string',
60
			'internaltype'=> 'string',
61
			'default'=> '',
62
			'required'=> true,
63
		),
64
		'paypalexpress.ApiEndpoint' => array(
65
			'code' => 'paypalexpress.ApiEndpoint',
66
			'internalcode'=> 'paypalexpress.ApiEndpoint',
67
			'label'=> 'APIEndpoint',
68
			'type'=> 'string',
69
			'internaltype'=> 'string',
70
			'default'=> 'https://api-3t.paypal.com/nvp',
71
			'required'=> false,
72
		),
73
		'paypalexpress.PaypalUrl' => array(
74
			'code' => 'paypalexpress.PaypalUrl',
75
			'internalcode'=> 'paypalexpress.PaypalUrl',
76
			'label'=> 'PaypalUrl',
77
			'type'=> 'string',
78
			'internaltype'=> 'string',
79
			'default'=> 'https://www.paypal.com/webscr&cmd=_express-checkout&useraction=commit&token=%1$s',
80
			'required'=> false,
81
		),
82
		'paypalexpress.PaymentAction' => array(
83
			'code' => 'paypalexpress.PaymentAction',
84
			'internalcode'=> 'paypalexpress.PaymentAction',
85
			'label'=> 'PaymentAction',
86
			'type'=> 'string',
87
			'internaltype'=> 'string',
88
			'default'=> 'Sale',
89
			'required'=> false,
90
		),
91
		'paypalexpress.LandingPage' => array(
92
			'code' => 'paypalexpress.LandingPage',
93
			'internalcode'=> 'paypalexpress.LandingPage',
94
			'label'=> 'Landing page',
95
			'type'=> 'string',
96
			'internaltype'=> 'string',
97
			'default'=> 'Login',
98
			'required'=> false,
99
		),
100
		'paypalexpress.FundingSource' => array(
101
			'code' => 'paypalexpress.FundingSource',
102
			'internalcode'=> 'paypalexpress.FundingSource',
103
			'label'=> 'Funding source',
104
			'type'=> 'string',
105
			'internaltype'=> 'string',
106
			'default'=> 'CreditCard',
107
			'required'=> false,
108
		),
109
		'paypalexpress.AddrOverride' => array(
110
			'code' => 'paypalexpress.AddrOverride',
111
			'internalcode'=> 'paypalexpress.AddrOverride',
112
			'label'=> 'Customer can change address',
113
			'type'=> 'integer',
114
			'internaltype'=> 'integer',
115
			'default'=> 0,
116
			'required'=> false,
117
		),
118
		'paypalexpress.NoShipping' => array(
119
			'code' => 'paypalexpress.NoShipping',
120
			'internalcode'=> 'paypalexpress.NoShipping',
121
			'label'=> 'Don\'t display shipping address',
122
			'type'=> 'integer',
123
			'internaltype'=> 'integer',
124
			'default'=> 1,
125
			'required'=> false,
126
		),
127
		'paypalexpress.url-validate' => array(
128
			'code' => 'paypalexpress.url-validate',
129
			'internalcode'=> 'paypalexpress.url-validate',
130
			'label'=> 'Validation URL',
131
			'type'=> 'string',
132
			'internaltype'=> 'string',
133
			'default'=> 'https://www.paypal.com/webscr&cmd=_notify-validate',
134
			'required'=> false,
135
		),
136
	);
137
138
139
	/**
140
	 * Initializes the provider object.
141
	 *
142
	 * @param \Aimeos\MShop\Context\Item\Iface $context Context object
143
	 * @param \Aimeos\MShop\Service\Item\Iface $serviceItem Service item with configuration
144
	 * @throws \Aimeos\MShop\Service\Exception If one of the required configuration values isn't available
145
	 */
146
	public function __construct( \Aimeos\MShop\Context\Item\Iface $context, \Aimeos\MShop\Service\Item\Iface $serviceItem )
147
	{
148
		parent::__construct( $context, $serviceItem );
149
150
		$configParameters = array(
151
			'paypalexpress.AccountEmail',
152
			'paypalexpress.ApiUsername',
153
			'paypalexpress.ApiPassword',
154
			'paypalexpress.ApiSignature',
155
		);
156
157
		$config = $serviceItem->getConfig();
158
159
		foreach( $configParameters as $param )
160
		{
161
			if( !isset( $config[$param] ) ) {
162
				throw new \Aimeos\MShop\Service\Exception( sprintf( 'Configuration for "%1$s" is missing', $param ) );
163
			}
164
		}
165
166
		$default = 'https://api-3t.paypal.com/nvp';
167
		$this->apiendpoint = $this->getConfigValue( array( 'paypalexpress.ApiEndpoint' ), $default );
168
	}
169
170
171
	/**
172
	 * Returns the configuration attribute definitions of the provider to generate a list of available fields and
173
	 * rules for the value of each field in the administration interface.
174
	 *
175
	 * @return array List of attribute definitions implementing \Aimeos\MW\Common\Critera\Attribute\Iface
176
	 */
177
	public function getConfigBE()
178
	{
179
		$list = parent::getConfigBE();
180
181
		foreach( $this->beConfig as $key => $config ) {
182
			$list[$key] = new \Aimeos\MW\Criteria\Attribute\Standard( $config );
183
		}
184
185
		return $list;
186
	}
187
188
189
	/**
190
	 * Checks the backend configuration attributes for validity.
191
	 *
192
	 * @param array $attributes Attributes added by the shop owner in the administraton interface
193
	 * @return array An array with the attribute keys as key and an error message as values for all attributes that are
194
	 * 	known by the provider but aren't valid
195
	 */
196
	public function checkConfigBE( array $attributes )
197
	{
198
		$errors = parent::checkConfigBE( $attributes );
199
200
		return array_merge( $errors, $this->checkConfig( $this->beConfig, $attributes ) );
201
	}
202
203
204
	/**
205
	 * Tries to get an authorization or captures the money immediately for the given order if capturing the money
206
	 * separately isn't supported or not configured by the shop owner.
207
	 *
208
	 * @param \Aimeos\MShop\Order\Item\Iface $order Order invoice object
209
	 * @param array $params Request parameter if available
210
	 * @return \Aimeos\MShop\Common\Item\Helper\Form\Standard Form object with URL, action and parameters to redirect to
211
	 * 	(e.g. to an external server of the payment provider or to a local success page)
212
	 */
213
	public function process( \Aimeos\MShop\Order\Item\Iface $order, array $params = array() )
214
	{
215
		$orderid = $order->getId();
216
		$orderBaseItem = $this->getOrderBase( $order->getBaseId(), \Aimeos\MShop\Order\Manager\Base\Base::PARTS_ALL );
217
218
		$values = $this->getOrderDetails( $orderBaseItem );
219
		$values['METHOD'] = 'SetExpressCheckout';
220
		$values['PAYMENTREQUEST_0_INVNUM'] = $orderid;
221
		$values['RETURNURL'] = $this->getConfigValue( array( 'payment.url-success' ) );
222
		$values['CANCELURL'] = $this->getConfigValue( array( 'payment.url-cancel', 'payment.url-success' ) );
223
		$values['USERSELECTEDFUNDINGSOURCE'] = $this->getConfigValue( array( 'paypalexpress.FundingSource' ), 'CreditCard' );
224
		$values['LANDINGPAGE'] = $this->getConfigValue( array( 'paypalexpress.LandingPage' ), 'Login' );
225
226
		$urlQuery = http_build_query( $values, '', '&' );
227
		$response = $this->getCommunication()->transmit( $this->apiendpoint, 'POST', $urlQuery );
228
		$rvals = $this->checkResponse( $orderid, $response, __METHOD__ );
229
230
		$default = 'https://www.paypal.com/webscr&cmd=_express-checkout&useraction=commit&token=%1$s';
231
		$paypalUrl = sprintf( $this->getConfigValue( array( 'paypalexpress.PaypalUrl' ), $default ), $rvals['TOKEN'] );
232
233
		$type = \Aimeos\MShop\Order\Item\Base\Service\Base::TYPE_PAYMENT;
234
		$this->setAttributes( $orderBaseItem->getService( $type ), array( 'TOKEN' => $rvals['TOKEN'] ), 'payment/paypal' );
235
		$this->saveOrderBase( $orderBaseItem );
236
237
		return new \Aimeos\MShop\Common\Item\Helper\Form\Standard( $paypalUrl, 'POST', array() );
238
	}
239
240
241
	/**
242
	 * Queries for status updates for the given order if supported.
243
	 *
244
	 * @param \Aimeos\MShop\Order\Item\Iface $order Order invoice object
245
	 */
246
	public function query( \Aimeos\MShop\Order\Item\Iface $order )
247
	{
248
		if( ( $tid = $this->getOrderServiceItem( $order->getBaseId() )->getAttribute( 'TRANSACTIONID', 'payment/paypal' ) ) === null )
249
		{
250
			$msg = sprintf( 'PayPal Express: Payment transaction ID for order ID "%1$s" not available', $order->getId() );
251
			throw new \Aimeos\MShop\Service\Exception( $msg );
252
		}
253
254
		$values = $this->getAuthParameter();
255
		$values['METHOD'] = 'GetTransactionDetails';
256
		$values['TRANSACTIONID'] = $tid;
257
258
		$urlQuery = http_build_query( $values, '', '&' );
259
		$response = $this->getCommunication()->transmit( $this->apiendpoint, 'POST', $urlQuery );
260
		$rvals = $this->checkResponse( $order->getId(), $response, __METHOD__ );
261
262
		$this->setPaymentStatus( $order, $rvals );
263
		$this->saveOrder( $order );
264
	}
265
266
267
	/**
268
	 * Captures the money later on request for the given order if supported.
269
	 *
270
	 * @param \Aimeos\MShop\Order\Item\Iface $order Order invoice object
271
	 */
272
	public function capture( \Aimeos\MShop\Order\Item\Iface $order )
273
	{
274
		$baseid = $order->getBaseId();
275
		$baseItem = $this->getOrderBase( $baseid );
276
		$serviceItem = $baseItem->getService( \Aimeos\MShop\Order\Item\Base\Service\Base::TYPE_PAYMENT );
277
278
		if( ( $tid = $serviceItem->getAttribute( 'TRANSACTIONID', 'payment/paypal' ) ) === null )
279
		{
280
			$msg = sprintf( 'PayPal Express: Payment transaction ID for order ID "%1$s" not available', $order->getId() );
281
			throw new \Aimeos\MShop\Service\Exception( $msg );
282
		}
283
284
		$price = $baseItem->getPrice();
285
286
		$values = $this->getAuthParameter();
287
		$values['METHOD'] = 'DoCapture';
288
		$values['COMPLETETYPE'] = 'Complete';
289
		$values['AUTHORIZATIONID'] = $tid;
290
		$values['INVNUM'] = $order->getId();
291
		$values['CURRENCYCODE'] = $price->getCurrencyId();
292
		$values['AMT'] = $this->getAmount( $price );
293
294
		$urlQuery = http_build_query( $values, '', '&' );
295
		$response = $this->getCommunication()->transmit( $this->apiendpoint, 'POST', $urlQuery );
296
		$rvals = $this->checkResponse( $order->getId(), $response, __METHOD__ );
297
298
		$this->setPaymentStatus( $order, $rvals );
299
300
		$attributes = array();
301
		if( isset( $rvals['PARENTTRANSACTIONID'] ) ) {
302
			$attributes['PARENTTRANSACTIONID'] = $rvals['PARENTTRANSACTIONID'];
303
		}
304
305
		//updates the transaction id
306
		$attributes['TRANSACTIONID'] = $rvals['TRANSACTIONID'];
307
		$this->setAttributes( $serviceItem, $attributes, 'payment/paypal' );
308
309
		$this->saveOrderBase( $baseItem );
310
		$this->saveOrder( $order );
311
	}
312
313
314
	/**
315
	 * Refunds the money for the given order if supported.
316
	 *
317
	 * @param \Aimeos\MShop\Order\Item\Iface $order Order invoice object
318
	 */
319
	public function refund( \Aimeos\MShop\Order\Item\Iface $order )
320
	{
321
		$baseItem = $this->getOrderBase( $order->getBaseId() );
322
		$serviceItem = $baseItem->getService( \Aimeos\MShop\Order\Item\Base\Service\Base::TYPE_PAYMENT );
323
324
		if( ( $tid = $serviceItem->getAttribute( 'TRANSACTIONID', 'payment/paypal' ) ) === null )
325
		{
326
			$msg = sprintf( 'PayPal Express: Payment transaction ID for order ID "%1$s" not available', $order->getId() );
327
			throw new \Aimeos\MShop\Service\Exception( $msg );
328
		}
329
330
		$values = $this->getAuthParameter();
331
		$values['METHOD'] = 'RefundTransaction';
332
		$values['REFUNDSOURCE'] = 'instant';
333
		$values['REFUNDTYPE'] = 'Full';
334
		$values['TRANSACTIONID'] = $tid;
335
		$values['INVOICEID'] = $order->getId();
336
337
		$urlQuery = http_build_query( $values, '', '&' );
338
		$response = $this->getCommunication()->transmit( $this->apiendpoint, 'POST', $urlQuery );
339
		$rvals = $this->checkResponse( $order->getId(), $response, __METHOD__ );
340
341
		$attributes = array( 'REFUNDTRANSACTIONID' => $rvals['REFUNDTRANSACTIONID'] );
342
		$this->setAttributes( $serviceItem, $attributes, 'payment/paypal' );
343
		$this->saveOrderBase( $baseItem );
344
345
		$order->setPaymentStatus( \Aimeos\MShop\Order\Item\Base::PAY_REFUND );
346
		$this->saveOrder( $order );
347
	}
348
349
350
	/**
351
	 * Cancels the authorization for the given order if supported.
352
	 *
353
	 * @param \Aimeos\MShop\Order\Item\Iface $order Order invoice object
354
	 */
355
	public function cancel( \Aimeos\MShop\Order\Item\Iface $order )
356
	{
357
		if( ( $tid = $this->getOrderServiceItem( $order->getBaseId() )->getAttribute( 'TRANSACTIONID', 'payment/paypal' ) ) === null )
358
		{
359
			$msg = sprintf( 'PayPal Express: Payment transaction ID for order ID "%1$s" not available', $order->getId() );
360
			throw new \Aimeos\MShop\Service\Exception( $msg );
361
		}
362
363
		$values = $this->getAuthParameter();
364
		$values['METHOD'] = 'DoVoid';
365
		$values['AUTHORIZATIONID'] = $tid;
366
367
		$urlQuery = http_build_query( $values, '', '&' );
368
		$response = $this->getCommunication()->transmit( $this->apiendpoint, 'POST', $urlQuery );
369
		$this->checkResponse( $order->getId(), $response, __METHOD__ );
370
371
		$order->setPaymentStatus( \Aimeos\MShop\Order\Item\Base::PAY_CANCELED );
372
		$this->saveOrder( $order );
373
	}
374
375
376
	/**
377
	 * Updates the orders for which status updates were received via direct requests (like HTTP).
378
	 *
379
	 * @param array $params Associative list of request parameters
380
	 * @param string|null $body Information sent within the body of the request
381
	 * @param string|null &$response Response body for notification requests
382
	 * @param array &$header Response headers for notification requests
383
	 * @return \Aimeos\MShop\Order\Item\Iface|null Order item if update was successful, null if the given parameters are not valid for this provider
384
	 * @throws \Aimeos\MShop\Service\Exception If updating one of the orders failed
385
	 */
386
	public function updateSync( array $params = array(), $body = null, &$response = null, array &$header = array() )
387
	{
388
		if( isset( $params['token'] ) && isset( $params['PayerID'] ) && isset( $params['orderid'] ) ) {
389
			return $this->doExpressCheckoutPayment( $params );
390
		}
391
392
		//tid from ipn
393
		if( !isset( $params['txn_id'] ) ) {
394
			return null;
395
		}
396
397
		$urlQuery = http_build_query( $params, '', '&' );
398
399
		//validation
400
		$response = $this->getCommunication()->transmit( $this->getConfigValue( array( 'paypalexpress.url-validate' ) ), 'POST', $urlQuery );
401
402
403
		if( $response !== 'VERIFIED' )
404
		{
405
			$msg = sprintf( 'PayPal Express: Invalid request "%1$s"', $urlQuery );
406
			throw new \Aimeos\MShop\Service\Exception( $msg );
407
		}
408
409
410
		$order = $this->getOrder( $params['invoice'] );
411
		$baseItem = $this->getOrderBase( $order->getBaseId() );
412
		$serviceItem = $baseItem->getService( \Aimeos\MShop\Order\Item\Base\Service\Base::TYPE_PAYMENT );
413
414
		$this->checkIPN( $baseItem, $params );
415
416
		$status = array( 'PAYMENTSTATUS' => $params['payment_status'] );
417
418
		if( isset( $params['pending_reason'] ) ) {
419
			$status['PENDINGREASON'] = $params['pending_reason'];
420
		}
421
422
		$this->setAttributes( $serviceItem, array( $params['txn_id'] => $params['payment_status'] ), 'payment/paypal/txn' );
423
		$this->setAttributes( $serviceItem, array( 'TRANSACTIONID' => $params['txn_id'] ), 'payment/paypal' );
424
		$this->saveOrderBase( $baseItem );
425
426
		$this->setPaymentStatus( $order, $status );
427
		$this->saveOrder( $order );
428
429
		return $order;
430
	}
431
432
433
	/**
434
	 * Checks what features the payment provider implements.
435
	 *
436
	 * @param integer $what Constant from abstract class
437
	 * @return boolean True if feature is available in the payment provider, false if not
438
	 */
439
	public function isImplemented( $what )
440
	{
441
		switch( $what )
442
		{
443
			case \Aimeos\MShop\Service\Provider\Payment\Base::FEAT_CAPTURE:
444
			case \Aimeos\MShop\Service\Provider\Payment\Base::FEAT_QUERY:
445
			case \Aimeos\MShop\Service\Provider\Payment\Base::FEAT_CANCEL:
446
			case \Aimeos\MShop\Service\Provider\Payment\Base::FEAT_REFUND:
447
				return true;
448
		}
449
450
		return false;
451
	}
452
453
	/**
454
	 * Begins paypalexpress transaction and saves transaction id.
455
	 *
456
	 * @param mixed $params Update information whose format depends on the payment provider
457
	 * @return \Aimeos\MShop\Order\Item\Iface|null Order item if update was successful, null if the given parameters are not valid for this provider
458
	 */
459
	protected function doExpressCheckoutPayment( $params )
460
	{
461
		$order = $this->getOrder( $params['orderid'] );
462
		$baseid = $order->getBaseId();
463
		$baseItem = $this->getOrderBase( $baseid );
464
		$serviceItem = $baseItem->getService( \Aimeos\MShop\Order\Item\Base\Service\Base::TYPE_PAYMENT );
465
466
		$price = $baseItem->getPrice();
467
468
		$values = $this->getAuthParameter();
469
		$values['METHOD'] = 'DoExpressCheckoutPayment';
470
		$values['TOKEN'] = $params['token'];
471
		$values['PAYERID'] = $params['PayerID'];
472
		$values['PAYMENTACTION'] = $this->getConfigValue( array( 'paypalexpress.PaymentAction' ), 'Sale' );
473
		$values['CURRENCYCODE'] = $price->getCurrencyId();
474
		$values['NOTIFYURL'] = $this->getConfigValue( array( 'payment.url-update', 'payment.url-success' ) );
475
		$values['AMT'] = $this->getAmount( $price );
476
477
		$urlQuery = http_build_query( $values, '', '&' );
478
		$response = $this->getCommunication()->transmit( $this->apiendpoint, 'POST', $urlQuery );
479
		$rvals = $this->checkResponse( $order->getId(), $response, __METHOD__ );
480
481
		$attributes = array( 'PAYERID' => $params['PayerID'] );
482
483
		if( isset( $rvals['TRANSACTIONID'] ) )
484
		{
485
			$attributes['TRANSACTIONID'] = $rvals['TRANSACTIONID'];
486
			$this->setAttributes( $serviceItem, array( $rvals['TRANSACTIONID'] => $rvals['PAYMENTSTATUS'] ), 'payment/paypal/txn' );
487
		}
488
489
		$this->setAttributes( $serviceItem, $attributes, 'payment/paypal' );
490
		$this->saveOrderBase( $baseItem );
491
492
		$this->setPaymentStatus( $order, $rvals );
493
		$this->saveOrder( $order );
494
495
		return $order;
496
	}
497
498
499
	/**
500
	 * Checks the response from the payment server.
501
	 *
502
	 * @param string $orderid Order item ID
503
	 * @param string $response Response from the payment provider
504
	 * @param string $method Name of the calling method
505
	 * @return array Associative list of key/value pairs containing the response parameters
506
	 * @throws \Aimeos\MShop\Service\Exception If request was not successful and an error was returned
507
	 */
508
	protected function checkResponse( $orderid, $response, $method )
509
	{
510
		$rvals = array();
511
		parse_str( $response, $rvals );
512
513
		if( $rvals['ACK'] !== 'Success' )
514
		{
515
			$msg = 'PayPal Express: method = ' . $method . ', order ID = ' . $orderid . ', response = ' . print_r( $rvals, true );
516
			$this->getContext()->getLogger()->log( $msg, \Aimeos\MW\Logger\Base::WARN );
517
518
			if( $rvals['ACK'] !== 'SuccessWithWarning' )
519
			{
520
				$short = ( isset( $rvals['L_SHORTMESSAGE0'] ) ? $rvals['L_SHORTMESSAGE0'] : '<none>' );
521
				$msg = sprintf( 'PayPal Express: Request for order ID "%1$s" failed with "%2$s"', $orderid, $short );
522
				throw new \Aimeos\MShop\Service\Exception( $msg );
523
			}
524
		}
525
526
		return $rvals;
527
	}
528
529
530
	/**
531
	 * Checks if IPN message from paypal is valid.
532
	 *
533
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $basket
534
	 * @param array $params
535
	 */
536
	protected function checkIPN( $basket, $params )
537
	{
538
		$attrManager = \Aimeos\MShop\Factory::createManager( $this->getContext(), 'order/base/service/attribute' );
539
540
		if( $this->getConfigValue( array( 'paypalexpress.AccountEmail' ) ) !== $params['receiver_email'] )
541
		{
542
			$msg = sprintf( 'PayPal Express: Wrong receiver email "%1$s"', $params['receiver_email'] );
543
			throw new \Aimeos\MShop\Service\Exception( $msg );
544
		}
545
546
		$price = $basket->getPrice();
547
548
		if( $this->getAmount( $price ) != $params['payment_amount'] )
549
		{
550
			$msg = sprintf( 'PayPal Express: Wrong payment amount "%1$s" for order ID "%2$s"', $params['payment_amount'], $params['invoice'] );
551
			throw new \Aimeos\MShop\Service\Exception( $msg );
552
		}
553
554
		$search = $attrManager->createSearch();
555
		$expr = array(
556
			$search->compare( '==', 'order.base.service.attribute.code', $params['txn_id'] ),
557
			$search->compare( '==', 'order.base.service.attribute.value', $params['payment_status'] ),
558
		);
559
560
		$search->setConditions( $search->combine( '&&', $expr ) );
561
		$results = $attrManager->searchItems( $search );
562
563
		if( ( $attr = reset( $results ) ) !== false )
564
		{
565
			$msg = sprintf( 'PayPal Express: Duplicate transaction with ID "%1$s" and status "%2$s" ', $params['txn_id'], $params['txn_status'] );
566
			throw new \Aimeos\MShop\Service\Exception( $msg );
567
		}
568
	}
569
570
571
	/**
572
	 * Maps the PayPal status to the appropriate payment status and sets it in the order object.
573
	 *
574
	 * @param \Aimeos\MShop\Order\Item\Iface $invoice Order invoice object
575
	 * @param array $response Associative list of key/value pairs containing the PayPal response
576
	 */
577
	protected function setPaymentStatus( \Aimeos\MShop\Order\Item\Iface $invoice, array $response )
578
	{
579
		if( !isset( $response['PAYMENTSTATUS'] ) ) {
580
			return;
581
		}
582
583
		switch( $response['PAYMENTSTATUS'] )
584
		{
585
			case 'Pending':
586
				if( isset( $response['PENDINGREASON'] ) )
587
				{
588
					if( $response['PENDINGREASON'] === 'authorization' )
589
					{
590
						$invoice->setPaymentStatus( \Aimeos\MShop\Order\Item\Base::PAY_AUTHORIZED );
591
						break;
592
					}
593
594
					$str = 'PayPal Express: order ID = ' . $invoice->getId() . ', PENDINGREASON = ' . $response['PENDINGREASON'];
595
					$this->getContext()->getLogger()->log( $str, \Aimeos\MW\Logger\Base::INFO );
596
				}
597
598
				$invoice->setPaymentStatus( \Aimeos\MShop\Order\Item\Base::PAY_PENDING );
599
				break;
600
601
			case 'In-Progress':
602
				$invoice->setPaymentStatus( \Aimeos\MShop\Order\Item\Base::PAY_PENDING );
603
				break;
604
605
			case 'Completed':
606
			case 'Processed':
607
				$invoice->setPaymentStatus( \Aimeos\MShop\Order\Item\Base::PAY_RECEIVED );
608
				break;
609
610
			case 'Failed':
611
			case 'Denied':
612
			case 'Expired':
613
				$invoice->setPaymentStatus( \Aimeos\MShop\Order\Item\Base::PAY_REFUSED );
614
				break;
615
616
			case 'Refunded':
617
			case 'Partially-Refunded':
618
			case 'Reversed':
619
				$invoice->setPaymentStatus( \Aimeos\MShop\Order\Item\Base::PAY_REFUND );
620
				break;
621
622
			case 'Canceled-Reversal':
623
			case 'Voided':
624
				$invoice->setPaymentStatus( \Aimeos\MShop\Order\Item\Base::PAY_CANCELED );
625
				break;
626
627
			default:
628
				$str = 'PayPal Express: order ID = ' . $invoice->getId() . ', response = ' . print_r( $response, true );
629
				$this->getContext()->getLogger()->log( $str, \Aimeos\MW\Logger\Base::INFO );
630
		}
631
	}
632
633
634
	/**
635
	 * Returns an list of order data required by PayPal.
636
	 *
637
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $orderBase Order base item
638
	 * @return array Associative list of key/value pairs with order data required by PayPal
639
	 */
640
	protected function getOrderDetails( \Aimeos\MShop\Order\Item\Base\Iface $orderBase )
641
	{
642
		$deliveryCosts = 0;
643
		$deliveryPrices = array();
644
		$values = $this->getAuthParameter();
645
646
		try
647
		{
648
			$orderAddressDelivery = $orderBase->getAddress( \Aimeos\MShop\Order\Item\Base\Address\Base::TYPE_PAYMENT );
649
650
			/* setting up the address details */
651
			$values['NOSHIPPING'] = $this->getConfigValue( array( 'paypalexpress.NoShipping' ), 1 );
652
			$values['ADDROVERRIDE'] = $this->getConfigValue( array( 'paypalexpress.AddrOverride' ), 0 );
653
			$values['PAYMENTREQUEST_0_SHIPTONAME'] = $orderAddressDelivery->getFirstName() . ' ' . $orderAddressDelivery->getLastName();
654
			$values['PAYMENTREQUEST_0_SHIPTOSTREET'] = $orderAddressDelivery->getAddress1() . ' ' . $orderAddressDelivery->getAddress2() . ' ' . $orderAddressDelivery->getAddress3();
655
			$values['PAYMENTREQUEST_0_SHIPTOCITY'] = $orderAddressDelivery->getCity();
656
			$values['PAYMENTREQUEST_0_SHIPTOSTATE'] = $orderAddressDelivery->getState();
657
			$values['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] = $orderAddressDelivery->getCountryId();
658
			$values['PAYMENTREQUEST_0_SHIPTOZIP'] = $orderAddressDelivery->getPostal();
659
		}
660
		catch( \Exception $e ) { ; } // If no address is available
661
662
663
		$lastPos = 0;
664
		foreach( $orderBase->getProducts() as $product )
665
		{
666
			$price = $product->getPrice();
667
			$lastPos = $product->getPosition() - 1;
668
			$deliveryPrices = $this->addPrice( $deliveryPrices, (clone $price)->setValue( '0.00' ) );
669
670
			$values['L_PAYMENTREQUEST_0_NUMBER' . $lastPos] = $product->getId();
671
			$values['L_PAYMENTREQUEST_0_NAME' . $lastPos] = $product->getName();
672
			$values['L_PAYMENTREQUEST_0_QTY' . $lastPos] = $product->getQuantity();
673
			$values['L_PAYMENTREQUEST_0_AMT' . $lastPos] = $this->getAmount( $price, false );
674
		}
675
676
677
		$price = $orderBase->getService( 'payment' )->getPrice();
678
		if( ( $paymentCosts = $this->getAmount( $price ) ) > '0.00' )
679
		{
680
			$lastPos++;
681
			$values['L_PAYMENTREQUEST_0_NAME' . $lastPos] = $this->getContext()->getI18n()->dt( 'mshop', 'Payment costs' );
682
			$values['L_PAYMENTREQUEST_0_QTY' . $lastPos] = '1';
683
			$values['L_PAYMENTREQUEST_0_AMT' . $lastPos] = $paymentCosts;
684
		}
685
686
687
		try
688
		{
689
			$orderServiceDeliveryItem = $orderBase->getService( 'delivery' );
690
			$price = $orderServiceDeliveryItem->getPrice();
691
			$deliveryPrices = $this->addPrice( $deliveryPrices, $price );
692
693
			foreach( $deliveryPrices as $priceItem ) {
694
				$deliveryCosts += $this->getAmount( $priceItem );
695
			}
696
697
			$values['L_SHIPPINGOPTIONAMOUNT0'] = number_format( $deliveryCosts, 2, '.', '' );
698
			$values['L_SHIPPINGOPTIONLABEL0'] = $orderServiceDeliveryItem->getCode();
699
			$values['L_SHIPPINGOPTIONNAME0'] = $orderServiceDeliveryItem->getName();
700
			$values['L_SHIPPINGOPTIONISDEFAULT0'] = 'true';
701
		}
702
		catch( \Exception $e ) { ; } // If no delivery service is available
703
704
705
		$price = $orderBase->getPrice();
706
		$amount = $this->getAmount( $price );
707
708
		if( $deliveryCosts === 0 )
709
		{
710
			foreach( $deliveryPrices as $priceItem ) {
711
				$deliveryCosts += $this->getAmount( $priceItem );
712
			}
713
		}
714
715
		$values['MAXAMT'] = $amount + 0.01; // possible rounding error
716
		$values['PAYMENTREQUEST_0_AMT'] = $amount;
717
		$values['PAYMENTREQUEST_0_ITEMAMT'] = number_format( $amount - $deliveryCosts, 2, '.', '' );
718
		$values['PAYMENTREQUEST_0_SHIPPINGAMT'] = number_format( $deliveryCosts, 2, '.', '' );
719
		$values['PAYMENTREQUEST_0_INSURANCEAMT'] = '0.00';
720
		$values['PAYMENTREQUEST_0_INSURANCEOPTIONOFFERED'] = 'false';
721
		$values['PAYMENTREQUEST_0_SHIPDISCAMT'] = '0.00';
722
		$values['PAYMENTREQUEST_0_CURRENCYCODE'] = $orderBase->getPrice()->getCurrencyId();
723
		$values['PAYMENTREQUEST_0_PAYMENTACTION'] = $this->getConfigValue( array( 'paypalexpress.PaymentAction' ), 'sale' );
724
725
		return $values;
726
	}
727
728
729
	/**
730
	 * Returns the data required for authorization against the PayPal server.
731
	 *
732
	 * @return array Associative list of key/value pairs containing the autorization parameters
733
	 */
734
	protected function getAuthParameter()
735
	{
736
		return array(
737
			'VERSION' => '204.0',
738
			'SIGNATURE' => $this->getConfigValue( array( 'paypalexpress.ApiSignature' ) ),
739
			'USER' => $this->getConfigValue( array( 'paypalexpress.ApiUsername' ) ),
740
			'PWD' => $this->getConfigValue( array( 'paypalexpress.ApiPassword' ) ),
741
		);
742
	}
743
744
745
	/**
746
	 * Returns order service item for specified base ID.
747
	 *
748
	 * @param integer $baseid Base ID of the order
749
	 * @return \Aimeos\MShop\Order\Item\Base\Service\Iface Order service item
750
	 */
751
	protected function getOrderServiceItem( $baseid )
752
	{
753
		$basket = $this->getOrderBase( $baseid, \Aimeos\MShop\Order\Manager\Base\Base::PARTS_SERVICE );
754
		return $basket->getService( \Aimeos\MShop\Order\Item\Base\Service\Base::TYPE_PAYMENT );
755
	}
756
757
758
	/**
759
	 * Adds the costs to the price item with the corresponding tax rate
760
	 *
761
	 * @param \Aimeos\MShop\Price\Item\Iface[] $prices Associative list of tax rates as key and price items as value
762
	 * @param \Aimeos\MShop\Price\Item\Iface $price Price item that should be added
763
	 * @return \Aimeos\MShop\Price\Item\Iface[] Updated list of price items
0 ignored issues
show
Documentation introduced by
Should the return type not be array<*,\Aimeos\MShop\Common\Item\Iface>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
764
	 */
765
	protected function addPrice( array $prices, $price )
766
	{
767
		$taxrate = $price->getTaxRate();
768
769
		if( !isset( $prices[$taxrate] ) )
770
		{
771
			$prices[$taxrate] = \Aimeos\MShop\Factory::createManager( $this->getContext(), 'price' )->createItem();
772
			$prices[$taxrate]->setTaxRate( $taxrate );
773
		}
774
775
		$prices[$taxrate]->addItem( $price );
776
777
		return $prices;
778
	}
779
}