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