Merge pull request #11672 from omarabuhussein/CRM-21769-improve-unsupported-locale...
[civicrm-core.git] / CRM / Core / Payment / PayPalImpl.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 use Civi\Payment\Exception\PaymentProcessorException;
29
30 /**
31 *
32 * @package CRM
33 * @copyright CiviCRM LLC (c) 2004-2018
34 */
35
36 /**
37 * Class CRM_Core_Payment_PayPalImpl for paypal pro, paypal standard & paypal express.
38 */
39 class CRM_Core_Payment_PayPalImpl extends CRM_Core_Payment {
40 const CHARSET = 'iso-8859-1';
41
42 const PAYPAL_PRO = 'PayPal';
43 const PAYPAL_STANDARD = 'PayPal_Standard';
44 const PAYPAL_EXPRESS = 'PayPal_Express';
45
46 protected $_mode = NULL;
47
48 /**
49 * Constructor.
50 *
51 * @param string $mode
52 * The mode of operation: live or test.
53 *
54 * @param CRM_Core_Payment $paymentProcessor
55 *
56 * @return \CRM_Core_Payment_PayPalImpl
57 * @throws \Civi\Payment\Exception\PaymentProcessorException
58 */
59 public function __construct($mode, &$paymentProcessor) {
60 $this->_mode = $mode;
61 $this->_paymentProcessor = $paymentProcessor;
62
63 if ($this->isPayPalType($this::PAYPAL_STANDARD)) {
64 $this->_processorName = ts('PayPal Standard');
65 }
66 elseif ($this->isPayPalType($this::PAYPAL_EXPRESS)) {
67 $this->_processorName = ts('PayPal Express');
68 }
69 elseif ($this->isPayPalType($this::PAYPAL_PRO)) {
70 $this->_processorName = ts('PayPal Pro');
71 }
72 else {
73 throw new PaymentProcessorException('CRM_Core_Payment_PayPalImpl: Payment processor type is not defined!');
74 }
75 }
76
77 /**
78 * Helper function to check which payment processor type is being used.
79 *
80 * @param $typeName
81 *
82 * @return bool
83 * @throws \Civi\Payment\Exception\PaymentProcessorException
84 */
85 public function isPayPalType($typeName) {
86 // Historically payment_processor_type may have been set to the name of the processor but newer versions of CiviCRM use the id set in payment_processor_type_id
87 if (empty($this->_paymentProcessor['payment_processor_type_id']) && empty($this->_paymentProcessor['payment_processor_type'])) {
88 // We need one of them to be set!
89 throw new PaymentProcessorException('CRM_Core_Payment_PayPalImpl: Payment processor type is not defined!');
90 }
91 if (empty($this->_paymentProcessor['payment_processor_type_id']) && !empty($this->_paymentProcessor['payment_processor_type'])) {
92 // Handle legacy case where payment_processor_type was set, but payment_processor_type_id was not.
93 $this->_paymentProcessor['payment_processor_type_id']
94 = CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $this->_paymentProcessor['payment_processor_type']);
95 }
96 if ((int) $this->_paymentProcessor['payment_processor_type_id'] ===
97 CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', $typeName)) {
98 return TRUE;
99 }
100 return FALSE;
101 }
102
103 /**
104 * Are back office payments supported.
105 *
106 * E.g paypal standard won't permit you to enter a credit card associated
107 * with someone else's login.
108 *
109 * @return bool
110 * @throws \Civi\Payment\Exception\PaymentProcessorException
111 */
112 protected function supportsBackOffice() {
113 if ($this->isPayPalType($this::PAYPAL_PRO)) {
114 return TRUE;
115 }
116 return FALSE;
117 }
118
119 /**
120 * Does this processor support pre-approval.
121 *
122 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
123 *
124 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
125 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
126 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
127 *
128 * @return bool
129 * @throws \Civi\Payment\Exception\PaymentProcessorException
130 */
131 protected function supportsPreApproval() {
132 if ($this->isPayPalType($this::PAYPAL_EXPRESS) || $this->isPayPalType($this::PAYPAL_PRO)) {
133 return TRUE;
134 }
135 return FALSE;
136 }
137
138 /**
139 * Opportunity for the payment processor to override the entire form build.
140 *
141 * @param CRM_Core_Form $form
142 *
143 * @return bool
144 * Should form building stop at this point?
145 * @throws \Civi\Payment\Exception\PaymentProcessorException
146 */
147 public function buildForm(&$form) {
148 if ($this->supportsPreApproval()) {
149 $this->addPaypalExpressCode($form);
150 if ($this->isPayPalType($this::PAYPAL_EXPRESS)) {
151 CRM_Core_Region::instance('billing-block-post')->add(array(
152 'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
153 'name' => 'paypal_express',
154 ));
155 }
156 if ($this->isPayPalType($this::PAYPAL_PRO)) {
157 CRM_Core_Region::instance('billing-block-pre')->add(array(
158 'template' => 'CRM/Financial/Form/PaypalPro.tpl',
159 ));
160 }
161 }
162 return FALSE;
163 }
164
165 /**
166 * Billing mode button is basically synonymous with paypal express.
167 *
168 * This is probably a good example of 'odds & sods' code we
169 * need to find a way for the payment processor to assign.
170 *
171 * A tricky aspect is that the payment processor may need to set the order
172 *
173 * @param CRM_Core_Form $form
174 */
175 protected function addPaypalExpressCode(&$form) {
176 // @todo use $this->isBackOffice() instead, test.
177 if (empty($form->isBackOffice)) {
178
179 /**
180 * if payment method selected using ajax call then form object is of 'CRM_Financial_Form_Payment',
181 * instead of 'CRM_Contribute_Form_Contribution_Main' so it generate wrong button name
182 * and then clicking on express button it redirect to confirm screen rather than PayPal Express form
183 */
184
185 if ('CRM_Financial_Form_Payment' == get_class($form) && $form->_formName) {
186 $form->_expressButtonName = '_qf_' . $form->_formName . '_upload_express';
187 }
188 else {
189 $form->_expressButtonName = $form->getButtonName('upload', 'express');
190 }
191 $form->assign('expressButtonName', $form->_expressButtonName);
192 $form->add(
193 'image',
194 $form->_expressButtonName,
195 $this->_paymentProcessor['url_button'],
196 array('class' => 'crm-form-submit')
197 );
198 }
199 }
200
201 /**
202 * Can recurring contributions be set against pledges.
203 *
204 * In practice all processors that use the baseIPN function to finish transactions or
205 * call the completetransaction api support this by looking up previous contributions in the
206 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
207 * adding the new payment to the pledge.
208 *
209 * However, only enabling for processors it has been tested against.
210 *
211 * @return bool
212 */
213 protected function supportsRecurContributionsForPledges() {
214 return TRUE;
215 }
216
217 /**
218 * Default payment instrument validation.
219 *
220 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
221 * Not a static function, because I need to check for payment_type.
222 *
223 * @param array $values
224 * @param array $errors
225 *
226 * @throws \Civi\Payment\Exception\PaymentProcessorException
227 */
228 public function validatePaymentInstrument($values, &$errors) {
229 if ($this->isPayPalType($this::PAYPAL_PRO) && !$this->isPaypalExpress($values)) {
230 CRM_Core_Payment_Form::validateCreditCard($values, $errors, $this->_paymentProcessor['id']);
231 CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
232 }
233 }
234
235 /**
236 * Express checkout code.
237 *
238 * Check PayPal documentation for more information
239 *
240 * @param array $params
241 * Assoc array of input parameters for this transaction.
242 *
243 * @return array
244 * the result in an nice formatted array (or an error object)
245 * @throws \Civi\Payment\Exception\PaymentProcessorException
246 */
247 protected function setExpressCheckOut(&$params) {
248 $args = array();
249
250 $this->initialize($args, 'SetExpressCheckout');
251
252 $args['paymentAction'] = 'Sale';
253 $args['amt'] = $params['amount'];
254 $args['currencyCode'] = $params['currencyID'];
255 $args['desc'] = CRM_Utils_Array::value('description', $params);
256 $args['invnum'] = $params['invoiceID'];
257 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
258 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
259 $args['version'] = '56.0';
260
261 //LCD if recurring, collect additional data and set some values
262 if (!empty($params['is_recur'])) {
263 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
264 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
265 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
266 $args['L_PAYMENTTYPE0'] = 'Any';
267 }
268
269 // Allow further manipulation of the arguments via custom hooks ..
270 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
271
272 $result = $this->invokeAPI($args);
273
274 if (is_a($result, 'CRM_Core_Error')) {
275 throw new PaymentProcessorException($result->message);
276 }
277
278 /* Success */
279
280 return $result['token'];
281 }
282
283 /**
284 * Get any details that may be available to the payment processor due to an approval process having happened.
285 *
286 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
287 * result.
288 *
289 * @param array $storedDetails
290 *
291 * @return array
292 * @throws \Civi\Payment\Exception\PaymentProcessorException
293 */
294 public function getPreApprovalDetails($storedDetails) {
295 return empty($storedDetails['token']) ? array() : $this->getExpressCheckoutDetails($storedDetails['token']);
296 }
297
298 /**
299 * Get details from paypal.
300 *
301 * Check PayPal documentation for more information
302 *
303 * @param string $token
304 * The key associated with this transaction.
305 *
306 * @return array
307 * the result in an nice formatted array (or an error object)
308 * @throws \Civi\Payment\Exception\PaymentProcessorException
309 */
310 public function getExpressCheckoutDetails($token) {
311 $args = array();
312
313 $this->initialize($args, 'GetExpressCheckoutDetails');
314 $args['token'] = $token;
315 // LCD
316 $args['method'] = 'GetExpressCheckoutDetails';
317
318 $result = $this->invokeAPI($args);
319
320 if (is_a($result, 'CRM_Core_Error')) {
321 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
322 }
323
324 /* Success */
325 $fieldMap = array(
326 'token' => 'token',
327 'payer_status' => 'payerstatus',
328 'payer_id' => 'payerid',
329 'first_name' => 'firstname',
330 'middle_name' => 'middlename',
331 'last_name' => 'lastname',
332 'street_address' => 'shiptostreet',
333 'supplemental_address_1' => 'shiptostreet2',
334 'city' => 'shiptocity',
335 'postal_code' => 'shiptozip',
336 'state_province' => 'shiptostate',
337 'country' => 'shiptocountrycode',
338 );
339 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
340 }
341
342 /**
343 * Do the express checkout at paypal.
344 *
345 * Check PayPal documentation for more information
346 *
347 * @param array $params
348 *
349 * @return array
350 * The result in an nice formatted array.
351 *
352 * @throws \Civi\Payment\Exception\PaymentProcessorException
353 */
354 public function doExpressCheckout(&$params) {
355 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
356 if (!empty($params['is_recur'])) {
357 return $this->createRecurringPayments($params);
358 }
359 $args = array();
360
361 $this->initialize($args, 'DoExpressCheckoutPayment');
362 $args['token'] = $params['token'];
363 $args['paymentAction'] = 'Sale';
364 $args['amt'] = $params['amount'];
365 $args['currencyCode'] = $params['currencyID'];
366 $args['payerID'] = $params['payer_id'];
367 $args['invnum'] = $params['invoiceID'];
368 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
369 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
370 $args['desc'] = $params['description'];
371
372 // add CiviCRM BN code
373 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
374
375 $result = $this->invokeAPI($args);
376
377 if (is_a($result, 'CRM_Core_Error')) {
378 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
379 }
380
381 /* Success */
382
383 $params['trxn_id'] = $result['transactionid'];
384 $params['gross_amount'] = $result['amt'];
385 $params['fee_amount'] = $result['feeamt'];
386 $params['net_amount'] = CRM_Utils_Array::value('settleamt', $result);
387 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
388 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
389 }
390 $params['payment_status'] = $result['paymentstatus'];
391 $params['pending_reason'] = $result['pendingreason'];
392 if (!empty($params['is_recur'])) {
393 // See comment block.
394 $params['payment_status_id'] = array_search('Pending', $statuses);
395 }
396 else {
397 $params['payment_status_id'] = array_search('Completed', $statuses);
398 }
399 return $params;
400 }
401
402 /**
403 * Create recurring payments.
404 *
405 * Use a pre-authorisation token to activate a recurring payment profile
406 * https://developer.paypal.com/docs/classic/api/merchant/CreateRecurringPaymentsProfile_API_Operation_NVP/
407 *
408 * @param array $params
409 *
410 * @return mixed
411 * @throws \Exception
412 */
413 public function createRecurringPayments(&$params) {
414 $args = array();
415 // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
416 $this->initialize($args, 'CreateRecurringPaymentsProfile');
417
418 $start_time = strtotime(date('m/d/Y'));
419 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
420
421 $args['token'] = $params['token'];
422 $args['paymentAction'] = 'Sale';
423 $args['amt'] = $params['amount'];
424 $args['currencyCode'] = $params['currencyID'];
425 $args['payerID'] = $params['payer_id'];
426 $args['invnum'] = $params['invoiceID'];
427 $args['returnURL'] = $params['returnURL'];
428 $args['cancelURL'] = $params['cancelURL'];
429 $args['profilestartdate'] = $start_date;
430 $args['method'] = 'CreateRecurringPaymentsProfile';
431 $args['billingfrequency'] = $params['frequency_interval'];
432 $args['billingperiod'] = ucwords($params['frequency_unit']);
433 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
434 //$args['desc'] = 'Recurring Contribution';
435 $args['totalbillingcycles'] = $params['installments'];
436 $args['version'] = '56.0';
437 $args['profilereference'] = "i={$params['invoiceID']}" .
438 "&m=" .
439 "&c={$params['contactID']}" .
440 "&r={$params['contributionRecurID']}" .
441 "&b={$params['contributionID']}" .
442 "&p={$params['contributionPageID']}";
443
444 // add CiviCRM BN code
445 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
446
447 $result = $this->invokeAPI($args);
448
449 if (is_a($result, 'CRM_Core_Error')) {
450 return $result;
451 }
452
453 /* Success */
454 $params['trxn_id'] = $result['transactionid'];
455 $params['gross_amount'] = $result['amt'];
456 $params['fee_amount'] = $result['feeamt'];
457 $params['net_amount'] = $result['settleamt'];
458 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
459 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
460 }
461 $params['payment_status'] = $result['paymentstatus'];
462 $params['pending_reason'] = $result['pendingreason'];
463
464 return $params;
465 }
466
467 /**
468 * Initialise.
469 *
470 * @param $args
471 * @param $method
472 */
473 public function initialize(&$args, $method) {
474 $args['user'] = $this->_paymentProcessor['user_name'];
475 $args['pwd'] = $this->_paymentProcessor['password'];
476 $args['version'] = 3.0;
477 $args['signature'] = $this->_paymentProcessor['signature'];
478 $args['subject'] = CRM_Utils_Array::value('subject', $this->_paymentProcessor);
479 $args['method'] = $method;
480 }
481
482 /**
483 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
484 *
485 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
486 * more agnostic.
487 *
488 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
489 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
490 * doTransferCheckout would not traditionally come back.
491 *
492 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
493 * to be Pending.
494 *
495 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
496 * return Error objects
497 *
498 * @param array $params
499 *
500 * @param string $component
501 *
502 * @return array
503 * Result array
504 *
505 * @throws \Civi\Payment\Exception\PaymentProcessorException
506 */
507 public function doPayment(&$params, $component = 'contribute') {
508 if ($this->isPayPalType($this::PAYPAL_EXPRESS) || ($this->isPayPalType($this::PAYPAL_PRO) && !empty($params['token']))) {
509 $this->_component = $component;
510 return $this->doExpressCheckout($params);
511
512 }
513 return parent::doPayment($params, $component);
514 }
515
516 /**
517 * This function collects all the information from a web/api form and invokes
518 * the relevant payment processor specific functions to perform the transaction
519 *
520 * @param array $params
521 * Assoc array of input parameters for this transaction.
522 *
523 * @param string $component
524 * @return array
525 * the result in an nice formatted array (or an error object)
526 * @throws \Civi\Payment\Exception\PaymentProcessorException
527 */
528 public function doDirectPayment(&$params, $component = 'contribute') {
529 $args = array();
530
531 $this->initialize($args, 'DoDirectPayment');
532
533 $args['paymentAction'] = 'Sale';
534 $args['amt'] = $this->getAmount($params);
535 $args['currencyCode'] = $this->getCurrency($params);
536 $args['invnum'] = $params['invoiceID'];
537 $args['ipaddress'] = $params['ip_address'];
538 $args['creditCardType'] = $params['credit_card_type'];
539 $args['acct'] = $params['credit_card_number'];
540 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
541 $args['cvv2'] = $params['cvv2'];
542 $args['firstName'] = $params['first_name'];
543 $args['lastName'] = $params['last_name'];
544 $args['email'] = CRM_Utils_Array::value('email', $params);
545 $args['street'] = $params['street_address'];
546 $args['city'] = $params['city'];
547 $args['state'] = $params['state_province'];
548 $args['countryCode'] = $params['country'];
549 $args['zip'] = $params['postal_code'];
550 $args['desc'] = substr(CRM_Utils_Array::value('description', $params), 0, 127);
551 $args['custom'] = CRM_Utils_Array::value('accountingCode', $params);
552
553 // add CiviCRM BN code
554 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
555
556 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
557 $start_time = strtotime(date('m/d/Y'));
558 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
559
560 $args['PaymentAction'] = 'Sale';
561 $args['billingperiod'] = ucwords($params['frequency_unit']);
562 $args['billingfrequency'] = $params['frequency_interval'];
563 $args['method'] = "CreateRecurringPaymentsProfile";
564 $args['profilestartdate'] = $start_date;
565 $args['desc'] = "" .
566 $params['description'] . ": " .
567 $params['amount'] . " Per " .
568 $params['frequency_interval'] . " " .
569 $params['frequency_unit'];
570 $args['amt'] = $this->getAmount($params);
571 $args['totalbillingcycles'] = CRM_Utils_Array::value('installments', $params);
572 $args['version'] = 56.0;
573 $args['PROFILEREFERENCE'] = "" .
574 "i=" . $params['invoiceID'] . "&m=" . $component .
575 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
576 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
577 }
578
579 // Allow further manipulation of the arguments via custom hooks ..
580 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
581
582 $result = $this->invokeAPI($args);
583
584 // WAG
585 if (is_a($result, 'CRM_Core_Error')) {
586 return $result;
587 }
588
589 $params['recurr_profile_id'] = NULL;
590
591 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
592 $params['recurr_profile_id'] = $result['profileid'];
593 }
594
595 /* Success */
596
597 $params['trxn_id'] = CRM_Utils_Array::value('transactionid', $result);
598 $params['gross_amount'] = CRM_Utils_Array::value('amt', $result);
599 $params = array_merge($params, $this->doQuery($params));
600 return $params;
601 }
602
603 /**
604 * Query payment processor for details about a transaction.
605 *
606 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
607 *
608 * @param array $params
609 * Array of parameters containing one of:
610 * - trxn_id Id of an individual transaction.
611 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
612 *
613 * @return array
614 * Extra parameters retrieved.
615 * Any parameters retrievable through this should be documented in the function comments at
616 * CRM_Core_Payment::doQuery. Currently
617 * - fee_amount Amount of fee paid
618 *
619 * @throws \Civi\Payment\Exception\PaymentProcessorException
620 */
621 public function doQuery($params) {
622 //CRM-18140 - trxn_id not returned for recurring paypal transaction
623 if (!empty($params['is_recur'])) {
624 return array();
625 }
626 elseif (empty($params['trxn_id'])) {
627 throw new \Civi\Payment\Exception\PaymentProcessorException('transaction id not set');
628 }
629 $args = array(
630 'TRANSACTIONID' => $params['trxn_id'],
631 );
632 $this->initialize($args, 'GetTransactionDetails');
633 $result = $this->invokeAPI($args);
634 return array(
635 'fee_amount' => $result['feeamt'],
636 'net_amount' => $params['gross_amount'] - $result['feeamt'],
637 );
638 }
639
640 /**
641 * This function checks to see if we have the right config values.
642 *
643 * @return null|string
644 * the error message if any
645 * @throws \Civi\Payment\Exception\PaymentProcessorException
646 */
647 public function checkConfig() {
648 $error = array();
649
650 if (!$this->isPayPalType($this::PAYPAL_STANDARD)) {
651 if (empty($this->_paymentProcessor['signature'])) {
652 $error[] = ts('Signature is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
653 }
654
655 if (empty($this->_paymentProcessor['password'])) {
656 $error[] = ts('Password is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
657 }
658 }
659 if (empty($this->_paymentProcessor['user_name'])) {
660 $error[] = ts('User Name is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
661 }
662
663 if (!empty($error)) {
664 return implode('<p>', $error);
665 }
666 else {
667 return NULL;
668 }
669 }
670
671 /**
672 * @return null|string
673 * @throws \Civi\Payment\Exception\PaymentProcessorException
674 */
675 public function cancelSubscriptionURL() {
676 if ($this->isPayPalType($this::PAYPAL_STANDARD)) {
677 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']);
678 }
679 else {
680 return NULL;
681 }
682 }
683
684 /**
685 * Check whether a method is present ( & supported ) by the payment processor object.
686 *
687 * @param string $method
688 * Method to check for.
689 *
690 * @return bool
691 * @throws \Civi\Payment\Exception\PaymentProcessorException
692 */
693 public function isSupported($method) {
694 if (!$this->isPayPalType($this::PAYPAL_PRO)) {
695 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
696 // by standard or express.
697 return FALSE;
698 }
699 return parent::isSupported($method);
700 }
701
702 /**
703 * Paypal express replaces the submit button with it's own.
704 *
705 * @return bool
706 * Should the form button by suppressed?
707 * @throws \Civi\Payment\Exception\PaymentProcessorException
708 */
709 public function isSuppressSubmitButtons() {
710 if ($this->isPayPalType($this::PAYPAL_EXPRESS)) {
711 return TRUE;
712 }
713 return FALSE;
714 }
715
716 /**
717 * @param string $message
718 * @param array $params
719 *
720 * @return array|bool|object
721 * @throws \Civi\Payment\Exception\PaymentProcessorException
722 */
723 public function cancelSubscription(&$message = '', $params = array()) {
724 if ($this->isPayPalType($this::PAYPAL_PRO)) {
725 $args = array();
726 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
727
728 $args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params);
729 $args['ACTION'] = 'Cancel';
730 $args['NOTE'] = CRM_Utils_Array::value('reason', $params);
731
732 $result = $this->invokeAPI($args);
733 if (is_a($result, 'CRM_Core_Error')) {
734 return $result;
735 }
736 $message = "{$result['ack']}: profileid={$result['profileid']}";
737 return TRUE;
738 }
739 return FALSE;
740 }
741
742 /**
743 * Process incoming notification.
744 *
745 * @throws \CRM_Core_Exception
746 * @throws \CiviCRM_API3_Exception
747 */
748 static public function handlePaymentNotification() {
749 $params = array_merge($_GET, $_REQUEST);
750 $q = explode('/', CRM_Utils_Array::value('q', $params, ''));
751 $lastParam = array_pop($q);
752 if (is_numeric($lastParam)) {
753 $params['processor_id'] = $lastParam;
754 }
755 $result = civicrm_api3('PaymentProcessor', 'get', array(
756 'sequential' => 1,
757 'id' => $params['processor_id'],
758 'api.PaymentProcessorType.getvalue' => array('return' => "name"),
759 ));
760 if (!$result['count']) {
761 throw new CRM_Core_Exception("Could not find a processor with the given processor_id value '{$params['processor_id']}'.");
762 }
763
764 $paymentProcessorType = CRM_Utils_Array::value('api.PaymentProcessorType.getvalue', $result['values'][0]);
765 switch ($paymentProcessorType) {
766 case 'PayPal':
767 // "PayPal - Website Payments Pro"
768 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
769 break;
770
771 case 'PayPal_Standard':
772 // "PayPal - Website Payments Standard"
773 $paypalIPN = new CRM_Core_Payment_PayPalIPN($params);
774 break;
775
776 default:
777 // If we don't have PayPal Standard or PayPal Pro, something's wrong.
778 // Log an error and exit.
779 throw new CRM_Core_Exception("The processor_id value '{$params['processor_id']}' is for a processor of type '{$paymentProcessorType}', which is invalid in this context.");
780 }
781
782 $paypalIPN->main();
783 }
784
785 /**
786 * @param string $message
787 * @param array $params
788 *
789 * @return array|bool|object
790 * @throws \Civi\Payment\Exception\PaymentProcessorException
791 */
792 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
793 if ($this->isPayPalType($this::PAYPAL_PRO)) {
794 $config = CRM_Core_Config::singleton();
795 $args = array();
796 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
797
798 $args['PROFILEID'] = $params['subscriptionId'];
799 $args['AMT'] = $this->getAmount($params);
800 $args['CURRENCYCODE'] = $config->defaultCurrency;
801 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
802 $args['ACCT'] = $params['credit_card_number'];
803 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
804 $args['CVV2'] = $params['cvv2'];
805
806 $args['FIRSTNAME'] = $params['first_name'];
807 $args['LASTNAME'] = $params['last_name'];
808 $args['STREET'] = $params['street_address'];
809 $args['CITY'] = $params['city'];
810 $args['STATE'] = $params['state_province'];
811 $args['COUNTRYCODE'] = $params['postal_code'];
812 $args['ZIP'] = $params['country'];
813
814 $result = $this->invokeAPI($args);
815 if (is_a($result, 'CRM_Core_Error')) {
816 return $result;
817 }
818 $message = "{$result['ack']}: profileid={$result['profileid']}";
819 return TRUE;
820 }
821 return FALSE;
822 }
823
824 /**
825 * @param string $message
826 * @param array $params
827 *
828 * @return array|bool|object
829 * @throws \Civi\Payment\Exception\PaymentProcessorException
830 */
831 public function changeSubscriptionAmount(&$message = '', $params = array()) {
832 if ($this->isPayPalType($this::PAYPAL_PRO)) {
833 $config = CRM_Core_Config::singleton();
834 $args = array();
835 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
836
837 $args['PROFILEID'] = $params['subscriptionId'];
838 $args['AMT'] = $this->getAmount($params);
839 $args['CURRENCYCODE'] = $config->defaultCurrency;
840 $args['BILLINGFREQUENCY'] = $params['installments'];
841
842 $result = $this->invokeAPI($args);
843 CRM_Core_Error::debug_var('$result', $result);
844 if (is_a($result, 'CRM_Core_Error')) {
845 return $result;
846 }
847 $message = "{$result['ack']}: profileid={$result['profileid']}";
848 return TRUE;
849 }
850 return FALSE;
851 }
852
853 /**
854 * Function to action pre-approval if supported
855 *
856 * @param array $params
857 * Parameters from the form
858 *
859 * @return array
860 * - pre_approval_parameters (this will be stored on the calling form & available later)
861 * - redirect_url (if set the browser will be redirected to this.
862 * @throws \Civi\Payment\Exception\PaymentProcessorException
863 */
864 public function doPreApproval(&$params) {
865 if (!$this->isPaypalExpress($params)) {
866 return array();
867 }
868 $this->_component = $params['component'];
869 $token = $this->setExpressCheckOut($params);
870 return array(
871 'pre_approval_parameters' => array('token' => $token),
872 'redirect_url' => $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
873 );
874 }
875
876 /**
877 * @param array $params
878 * @param string $component
879 *
880 * @throws Exception
881 */
882 public function doTransferCheckout(&$params, $component = 'contribute') {
883
884 $notifyParameters = array('module' => $component);
885 $notifyParameterMap = array(
886 'contactID' => 'contactID',
887 'contributionID' => 'contributionID',
888 'eventID' => 'eventID',
889 'participantID' => 'participantID',
890 'membershipID' => 'membershipID',
891 'related_contact' => 'relatedContactID',
892 'onbehalf_dupe_alert' => 'onBehalfDupeAlert',
893 'accountingCode' => 'accountingCode',
894 'contributionRecurID' => 'contributionRecurID',
895 'contributionPageID' => 'contributionPageID',
896 );
897 foreach ($notifyParameterMap as $paramsName => $notifyName) {
898 if (!empty($params[$paramsName])) {
899 $notifyParameters[$notifyName] = $params[$paramsName];
900 }
901 }
902 $notifyURL = $this->getNotifyUrl();
903
904 $config = CRM_Core_Config::singleton();
905 $url = ($component == 'event') ? 'civicrm/event/register' : 'civicrm/contribute/transact';
906 $cancel = ($component == 'event') ? '_qf_Register_display' : '_qf_Main_display';
907
908 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
909 if (!empty($params['is_recur'])) {
910 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
911 }
912
913 $cancelURL = CRM_Utils_System::url(
914 $url,
915 $cancelUrlString,
916 TRUE, NULL, FALSE
917 );
918
919 $paypalParams = array(
920 'business' => $this->_paymentProcessor['user_name'],
921 'notify_url' => $notifyURL,
922 'item_name' => $this->getPaymentDescription($params, 127),
923 'quantity' => 1,
924 'undefined_quantity' => 0,
925 'cancel_return' => $cancelURL,
926 'no_note' => 1,
927 'no_shipping' => 1,
928 'return' => $this->getReturnSuccessUrl($params['qfKey']),
929 'rm' => 2,
930 'currency_code' => $params['currencyID'],
931 'invoice' => $params['invoiceID'],
932 'lc' => substr($config->lcMessages, -2),
933 'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8',
934 'custom' => json_encode($notifyParameters),
935 'bn' => 'CiviCRM_SP',
936 );
937
938 // add name and address if available, CRM-3130
939 $otherVars = array(
940 'first_name' => 'first_name',
941 'last_name' => 'last_name',
942 'street_address' => 'address1',
943 'country' => 'country',
944 'preferred_language' => 'lc',
945 'city' => 'city',
946 'state_province' => 'state',
947 'postal_code' => 'zip',
948 'email' => 'email',
949 );
950
951 foreach (array_keys($params) as $p) {
952 // get the base name without the location type suffixed to it
953 $parts = explode('-', $p);
954 $name = count($parts) > 1 ? $parts[0] : $p;
955 if (isset($otherVars[$name])) {
956 $value = $params[$p];
957 if ($value) {
958 if ($name == 'state_province') {
959 $stateName = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
960 $value = $stateName;
961 }
962 if ($name == 'country') {
963 $countryName = CRM_Core_PseudoConstant::countryIsoCode($value);
964 $value = $countryName;
965 }
966 // ensure value is not an array
967 // CRM-4174
968 if (!is_array($value)) {
969 $paypalParams[$otherVars[$name]] = $value;
970 }
971 }
972 }
973 }
974
975 // if recurring donations, add a few more items
976 if (!empty($params['is_recur'])) {
977 if (!$params['contributionRecurID']) {
978 CRM_Core_Error::fatal(ts('Recurring contribution, but no database id'));
979 }
980
981 $paypalParams += array(
982 'cmd' => '_xclick-subscriptions',
983 'a3' => $this->getAmount($params),
984 'p3' => $params['frequency_interval'],
985 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
986 'src' => 1,
987 'sra' => 1,
988 'srt' => CRM_Utils_Array::value('installments', $params),
989 'no_note' => 1,
990 'modify' => 0,
991 );
992 }
993 else {
994 $paypalParams += array(
995 'cmd' => '_xclick',
996 'amount' => $params['amount'],
997 );
998 }
999
1000 // Allow further manipulation of the arguments via custom hooks ..
1001 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $paypalParams);
1002
1003 $uri = '';
1004 foreach ($paypalParams as $key => $value) {
1005 if ($value === NULL) {
1006 continue;
1007 }
1008
1009 $value = urlencode($value);
1010 if ($key == 'return' ||
1011 $key == 'cancel_return' ||
1012 $key == 'notify_url'
1013 ) {
1014 $value = str_replace('%2F', '/', $value);
1015 }
1016 $uri .= "&{$key}={$value}";
1017 }
1018
1019 $uri = substr($uri, 1);
1020 $url = $this->_paymentProcessor['url_site'];
1021 $sub = empty($params['is_recur']) ? 'cgi-bin/webscr' : 'subscriptions';
1022 $paypalURL = "{$url}{$sub}?$uri";
1023
1024 CRM_Utils_System::redirect($paypalURL);
1025 }
1026
1027 /**
1028 * Hash_call: Function to perform the API call to PayPal using API signature.
1029 *
1030 * @methodName is name of API method.
1031 * @nvpStr is nvp string.
1032 * returns an associative array containing the response from the server.
1033 *
1034 * @param array $args
1035 * @param null $url
1036 *
1037 * @return array|object
1038 * @throws \Exception
1039 */
1040 public function invokeAPI($args, $url = NULL) {
1041
1042 if ($url === NULL) {
1043 if (empty($this->_paymentProcessor['url_api'])) {
1044 CRM_Core_Error::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
1045 }
1046
1047 $url = $this->_paymentProcessor['url_api'] . 'nvp';
1048 }
1049
1050 $p = array();
1051 foreach ($args as $n => $v) {
1052 $p[] = "$n=" . urlencode($v);
1053 }
1054
1055 //NVPRequest for submitting to server
1056 $nvpreq = implode('&', $p);
1057
1058 if (!function_exists('curl_init')) {
1059 CRM_Core_Error::fatal("curl functions NOT available.");
1060 }
1061
1062 //setting the curl parameters.
1063 $ch = curl_init();
1064 curl_setopt($ch, CURLOPT_URL, $url);
1065 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1066
1067 //turning off the server and peer verification(TrustManager Concept).
1068 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL'));
1069 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, Civi::settings()->get('verifySSL') ? 2 : 0);
1070
1071 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1072 curl_setopt($ch, CURLOPT_POST, 1);
1073
1074 //setting the nvpreq as POST FIELD to curl
1075 curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
1076
1077 //getting response from server
1078 $response = curl_exec($ch);
1079
1080 //converting NVPResponse to an Associative Array
1081 $result = self::deformat($response);
1082
1083 if (curl_errno($ch)) {
1084 $e = CRM_Core_Error::singleton();
1085 $e->push(curl_errno($ch),
1086 0, NULL,
1087 curl_error($ch)
1088 );
1089 return $e;
1090 }
1091 else {
1092 curl_close($ch);
1093 }
1094
1095 $outcome = strtolower(CRM_Utils_Array::value('ack', $result));
1096
1097 if ($outcome != 'success' && $outcome != 'successwithwarning') {
1098 throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
1099 $e = CRM_Core_Error::singleton();
1100 $e->push($result['l_errorcode0'],
1101 0, NULL,
1102 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
1103 );
1104 return $e;
1105 }
1106
1107 return $result;
1108 }
1109
1110 /**
1111 * This function will take NVPString and convert it to an Associative Array.
1112 *
1113 * It will decode the response. It is useful to search for a particular key and displaying arrays.
1114 *
1115 * @param string $str
1116 *
1117 * @return array
1118 */
1119 public static function deformat($str) {
1120 $result = array();
1121
1122 while (strlen($str)) {
1123 // position of key
1124 $keyPos = strpos($str, '=');
1125
1126 // position of value
1127 $valPos = strpos($str, '&') ? strpos($str, '&') : strlen($str);
1128
1129 /*getting the Key and Value values and storing in a Associative Array*/
1130
1131 $key = substr($str, 0, $keyPos);
1132 $val = substr($str, $keyPos + 1, $valPos - $keyPos - 1);
1133
1134 //decoding the respose
1135 $result[strtolower(urldecode($key))] = urldecode($val);
1136 $str = substr($str, $valPos + 1, strlen($str));
1137 }
1138
1139 return $result;
1140 }
1141
1142 /**
1143 * Get array of fields that should be displayed on the payment form.
1144 *
1145 * @return array
1146 * @throws \Civi\Payment\Exception\PaymentProcessorException
1147 */
1148 public function getPaymentFormFields() {
1149 if ($this->isPayPalType($this::PAYPAL_PRO)) {
1150 return $this->getCreditCardFormFields();
1151 }
1152 else {
1153 return array();
1154 }
1155 }
1156
1157 /**
1158 * Map the paypal params to CiviCRM params using a field map.
1159 *
1160 * @param array $fieldMap
1161 * @param array $paypalParams
1162 *
1163 * @return array
1164 */
1165 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1166 $params = array();
1167 foreach ($fieldMap as $civicrmField => $paypalField) {
1168 $params[$civicrmField] = isset($paypalParams[$paypalField]) ? $paypalParams[$paypalField] : NULL;
1169 }
1170 return $params;
1171 }
1172
1173 /**
1174 * Is this being processed by payment express.
1175 *
1176 * Either because it is payment express or because is pro with paypal express in use.
1177 *
1178 * @param array $params
1179 *
1180 * @return bool
1181 * @throws \Civi\Payment\Exception\PaymentProcessorException
1182 */
1183 protected function isPaypalExpress($params) {
1184 if ($this->isPayPalType($this::PAYPAL_EXPRESS)) {
1185 return TRUE;
1186 }
1187
1188 // This would occur postProcess.
1189 if (!empty($params['token'])) {
1190 return TRUE;
1191 }
1192 if (isset($params['button']) && stristr($params['button'], 'express')) {
1193 return TRUE;
1194 }
1195
1196 // The contribution form passes a 'button' but the event form might still set one of these fields.
1197 // @todo more standardisation & get paypal fully out of the form layer.
1198 $possibleExpressFields = array(
1199 '_qf_Register_upload_express_x',
1200 '_qf_Payment_upload_express_x',
1201 );
1202 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {
1203 return TRUE;
1204 }
1205 return FALSE;
1206 }
1207
1208 }