Merge pull request #7329 from lcdservices/CRM-17524
[civicrm-core.git] / CRM / Core / Payment / PayPalImpl.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 $result['payment_status_id'] = array_search('Pending', $statuses);
341 }
342 else {
343 $result['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'] = $params['installments'];
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 if (empty($params['trxn_id'])) {
566 throw new \Civi\Payment\Exception\PaymentProcessorException('transaction id not set');
567 }
568 $args = array(
569 'TRANSACTIONID' => $params['trxn_id'],
570 );
571 $this->initialize($args, 'GetTransactionDetails');
572 $result = $this->invokeAPI($args);
573 return array(
574 'fee_amount' => $result['feeamt'],
575 'net_amount' => $params['gross_amount'] - $result['feeamt'],
576 );
577 }
578
579 /**
580 * This function checks to see if we have the right config values.
581 *
582 * @return string
583 * the error message if any
584 */
585 public function checkConfig() {
586 $error = array();
587 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
588
589 if ($this->_paymentProcessor['payment_processor_type_id'] != CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
590 if (empty($this->_paymentProcessor['signature'])) {
591 $error[] = ts('Signature is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
592 }
593
594 if (empty($this->_paymentProcessor['password'])) {
595 $error[] = ts('Password is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
596 }
597 }
598 if (empty($this->_paymentProcessor['user_name'])) {
599 $error[] = ts('User Name is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
600 }
601
602 if (!empty($error)) {
603 return implode('<p>', $error);
604 }
605 else {
606 return NULL;
607 }
608 }
609
610 /**
611 * @return null|string
612 */
613 public function cancelSubscriptionURL() {
614 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Standard') {
615 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']);
616 }
617 else {
618 return NULL;
619 }
620 }
621
622 /**
623 * Check whether a method is present ( & supported ) by the payment processor object.
624 *
625 * @param string $method
626 * Method to check for.
627 *
628 * @return bool
629 */
630 public function isSupported($method = 'cancelSubscription') {
631 if ($this->_paymentProcessor['payment_processor_type'] != 'PayPal') {
632 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
633 // by standard or express.
634 return FALSE;
635 }
636 return parent::isSupported($method);
637 }
638
639 /**
640 * Paypal express replaces the submit button with it's own.
641 *
642 * @return bool
643 * Should the form button by suppressed?
644 */
645 public function isSuppressSubmitButtons() {
646 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express') {
647 return TRUE;
648 }
649 return FALSE;
650 }
651
652 /**
653 * @param string $message
654 * @param array $params
655 *
656 * @return array|bool|object
657 */
658 public function cancelSubscription(&$message = '', $params = array()) {
659 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
660 $args = array();
661 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
662
663 $args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params);
664 $args['ACTION'] = 'Cancel';
665 $args['NOTE'] = CRM_Utils_Array::value('reason', $params);
666
667 $result = $this->invokeAPI($args);
668 if (is_a($result, 'CRM_Core_Error')) {
669 return $result;
670 }
671 $message = "{$result['ack']}: profileid={$result['profileid']}";
672 return TRUE;
673 }
674 return FALSE;
675 }
676
677 /**
678 * Process incoming notification.
679 *
680 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
681 * for paypal standard as the goal must be to separate the 2.
682 *
683 * We don't need to handle paypal standard using this path as there has never been any historic support
684 * for paypal standard to call civicrm/payment/ipn as a path.
685 */
686 static public function handlePaymentNotification() {
687 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
688 $paypalIPN->main();
689 }
690
691 /**
692 * @param string $message
693 * @param array $params
694 *
695 * @return array|bool|object
696 */
697 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
698 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
699 $config = CRM_Core_Config::singleton();
700 $args = array();
701 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
702
703 $args['PROFILEID'] = $params['subscriptionId'];
704 $args['AMT'] = $params['amount'];
705 $args['CURRENCYCODE'] = $config->defaultCurrency;
706 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
707 $args['ACCT'] = $params['credit_card_number'];
708 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
709 $args['CVV2'] = $params['cvv2'];
710
711 $args['FIRSTNAME'] = $params['first_name'];
712 $args['LASTNAME'] = $params['last_name'];
713 $args['STREET'] = $params['street_address'];
714 $args['CITY'] = $params['city'];
715 $args['STATE'] = $params['state_province'];
716 $args['COUNTRYCODE'] = $params['postal_code'];
717 $args['ZIP'] = $params['country'];
718
719 $result = $this->invokeAPI($args);
720 if (is_a($result, 'CRM_Core_Error')) {
721 return $result;
722 }
723 $message = "{$result['ack']}: profileid={$result['profileid']}";
724 return TRUE;
725 }
726 return FALSE;
727 }
728
729 /**
730 * @param string $message
731 * @param array $params
732 *
733 * @return array|bool|object
734 */
735 public function changeSubscriptionAmount(&$message = '', $params = array()) {
736 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
737 $config = CRM_Core_Config::singleton();
738 $args = array();
739 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
740
741 $args['PROFILEID'] = $params['subscriptionId'];
742 $args['AMT'] = $params['amount'];
743 $args['CURRENCYCODE'] = $config->defaultCurrency;
744 $args['BILLINGFREQUENCY'] = $params['installments'];
745
746 $result = $this->invokeAPI($args);
747 CRM_Core_Error::debug_var('$result', $result);
748 if (is_a($result, 'CRM_Core_Error')) {
749 return $result;
750 }
751 $message = "{$result['ack']}: profileid={$result['profileid']}";
752 return TRUE;
753 }
754 return FALSE;
755 }
756
757 /**
758 * Function to action pre-approval if supported
759 *
760 * @param array $params
761 * Parameters from the form
762 *
763 * @return array
764 * - pre_approval_parameters (this will be stored on the calling form & available later)
765 * - redirect_url (if set the browser will be redirected to this.
766 */
767 public function doPreApproval(&$params) {
768 if (!$this->isPaypalExpress($params)) {
769 return array();
770 }
771 $this->_component = $params['component'];
772 $token = $this->setExpressCheckOut($params);
773 return array(
774 'pre_approval_parameters' => array('token' => $token),
775 'redirect_url' => $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
776 );
777 }
778
779 /**
780 * @param array $params
781 * @param string $component
782 *
783 * @throws Exception
784 */
785 public function doTransferCheckout(&$params, $component = 'contribute') {
786 $config = CRM_Core_Config::singleton();
787
788 if ($component != 'contribute' && $component != 'event') {
789 CRM_Core_Error::fatal(ts('Component is invalid'));
790 }
791
792 $notifyURL = $config->userFrameworkResourceURL . "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
793
794 if ($component == 'event') {
795 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
796 }
797 else {
798 $membershipID = CRM_Utils_Array::value('membershipID', $params);
799 if ($membershipID) {
800 $notifyURL .= "&membershipID=$membershipID";
801 }
802 $relatedContactID = CRM_Utils_Array::value('related_contact', $params);
803 if ($relatedContactID) {
804 $notifyURL .= "&relatedContactID=$relatedContactID";
805
806 $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params);
807 if ($onBehalfDupeAlert) {
808 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
809 }
810 }
811 }
812
813 $url = ($component == 'event') ? 'civicrm/event/register' : 'civicrm/contribute/transact';
814 $cancel = ($component == 'event') ? '_qf_Register_display' : '_qf_Main_display';
815 $returnURL = CRM_Utils_System::url($url,
816 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
817 TRUE, NULL, FALSE
818 );
819
820 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
821 if (!empty($params['is_recur'])) {
822 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
823 }
824
825 $cancelURL = CRM_Utils_System::url(
826 $url,
827 $cancelUrlString,
828 TRUE, NULL, FALSE
829 );
830
831 // ensure that the returnURL is absolute.
832 if (substr($returnURL, 0, 4) != 'http') {
833 $fixUrl = CRM_Utils_System::url("civicrm/admin/setting/url", '&reset=1');
834 CRM_Core_Error::fatal(ts('Sending a relative URL to PayPalIPN is erroneous. Please make your resource URL (in <a href="%1">Administer &raquo; System Settings &raquo; Resource URLs</a> ) complete.', array(1 => $fixUrl)));
835 }
836
837 $paypalParams = array(
838 'business' => $this->_paymentProcessor['user_name'],
839 'notify_url' => $notifyURL,
840 'item_name' => $this->getPaymentDescription($params),
841 'quantity' => 1,
842 'undefined_quantity' => 0,
843 'cancel_return' => $cancelURL,
844 'no_note' => 1,
845 'no_shipping' => 1,
846 'return' => $returnURL,
847 'rm' => 2,
848 'currency_code' => $params['currencyID'],
849 'invoice' => $params['invoiceID'],
850 'lc' => substr($config->lcMessages, -2),
851 'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8',
852 'custom' => CRM_Utils_Array::value('accountingCode', $params),
853 'bn' => 'CiviCRM_SP',
854 );
855
856 // add name and address if available, CRM-3130
857 $otherVars = array(
858 'first_name' => 'first_name',
859 'last_name' => 'last_name',
860 'street_address' => 'address1',
861 'country' => 'country',
862 'preferred_language' => 'lc',
863 'city' => 'city',
864 'state_province' => 'state',
865 'postal_code' => 'zip',
866 'email' => 'email',
867 );
868
869 foreach (array_keys($params) as $p) {
870 // get the base name without the location type suffixed to it
871 $parts = explode('-', $p);
872 $name = count($parts) > 1 ? $parts[0] : $p;
873 if (isset($otherVars[$name])) {
874 $value = $params[$p];
875 if ($value) {
876 if ($name == 'state_province') {
877 $stateName = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
878 $value = $stateName;
879 }
880 if ($name == 'country') {
881 $countryName = CRM_Core_PseudoConstant::countryIsoCode($value);
882 $value = $countryName;
883 }
884 // ensure value is not an array
885 // CRM-4174
886 if (!is_array($value)) {
887 $paypalParams[$otherVars[$name]] = $value;
888 }
889 }
890 }
891 }
892
893 // if recurring donations, add a few more items
894 if (!empty($params['is_recur'])) {
895 if ($params['contributionRecurID']) {
896 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
897 $paypalParams['notify_url'] = $notifyURL;
898 }
899 else {
900 CRM_Core_Error::fatal(ts('Recurring contribution, but no database id'));
901 }
902
903 $paypalParams += array(
904 'cmd' => '_xclick-subscriptions',
905 'a3' => $params['amount'],
906 'p3' => $params['frequency_interval'],
907 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
908 'src' => 1,
909 'sra' => 1,
910 'srt' => CRM_Utils_Array::value('installments', $params),
911 'no_note' => 1,
912 'modify' => 0,
913 );
914 }
915 else {
916 $paypalParams += array(
917 'cmd' => '_xclick',
918 'amount' => $params['amount'],
919 );
920 }
921
922 // Allow further manipulation of the arguments via custom hooks ..
923 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $paypalParams);
924
925 $uri = '';
926 foreach ($paypalParams as $key => $value) {
927 if ($value === NULL) {
928 continue;
929 }
930
931 $value = urlencode($value);
932 if ($key == 'return' ||
933 $key == 'cancel_return' ||
934 $key == 'notify_url'
935 ) {
936 $value = str_replace('%2F', '/', $value);
937 }
938 $uri .= "&{$key}={$value}";
939 }
940
941 $uri = substr($uri, 1);
942 $url = $this->_paymentProcessor['url_site'];
943 $sub = empty($params['is_recur']) ? 'cgi-bin/webscr' : 'subscriptions';
944 $paypalURL = "{$url}{$sub}?$uri";
945
946 CRM_Utils_System::redirect($paypalURL);
947 }
948
949 /**
950 * Hash_call: Function to perform the API call to PayPal using API signature.
951 *
952 * @methodName is name of API method.
953 * @nvpStr is nvp string.
954 * returns an associative array containing the response from the server.
955 *
956 * @param array $args
957 * @param null $url
958 *
959 * @return array|object
960 * @throws \Exception
961 */
962 public function invokeAPI($args, $url = NULL) {
963
964 if ($url === NULL) {
965 if (empty($this->_paymentProcessor['url_api'])) {
966 CRM_Core_Error::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
967 }
968
969 $url = $this->_paymentProcessor['url_api'] . 'nvp';
970 }
971
972 if (!function_exists('curl_init')) {
973 CRM_Core_Error::fatal("curl functions NOT available.");
974 }
975
976 //setting the curl parameters.
977 $ch = curl_init();
978 curl_setopt($ch, CURLOPT_URL, $url);
979 curl_setopt($ch, CURLOPT_VERBOSE, 1);
980
981 //turning off the server and peer verification(TrustManager Concept).
982 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL'));
983 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, Civi::settings()->get('verifySSL') ? 2 : 0);
984
985 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
986 curl_setopt($ch, CURLOPT_POST, 1);
987
988 $p = array();
989 foreach ($args as $n => $v) {
990 $p[] = "$n=" . urlencode($v);
991 }
992
993 //NVPRequest for submitting to server
994 $nvpreq = implode('&', $p);
995
996 //setting the nvpreq as POST FIELD to curl
997 curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
998
999 //getting response from server
1000 $response = curl_exec($ch);
1001
1002 //converting NVPResponse to an Associative Array
1003 $result = self::deformat($response);
1004
1005 if (curl_errno($ch)) {
1006 $e = CRM_Core_Error::singleton();
1007 $e->push(curl_errno($ch),
1008 0, NULL,
1009 curl_error($ch)
1010 );
1011 return $e;
1012 }
1013 else {
1014 curl_close($ch);
1015 }
1016
1017 if (strtolower($result['ack']) != 'success' &&
1018 strtolower($result['ack']) != 'successwithwarning'
1019 ) {
1020 throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
1021 $e = CRM_Core_Error::singleton();
1022 $e->push($result['l_errorcode0'],
1023 0, NULL,
1024 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
1025 );
1026 return $e;
1027 }
1028
1029 return $result;
1030 }
1031
1032 /**
1033 * This function will take NVPString and convert it to an Associative Array.
1034 *
1035 * It will decode the response. It is useful to search for a particular key and displaying arrays.
1036 *
1037 * @param string $str
1038 *
1039 * @return array
1040 */
1041 public static function deformat($str) {
1042 $result = array();
1043
1044 while (strlen($str)) {
1045 // position of key
1046 $keyPos = strpos($str, '=');
1047
1048 // position of value
1049 $valPos = strpos($str, '&') ? strpos($str, '&') : strlen($str);
1050
1051 /*getting the Key and Value values and storing in a Associative Array*/
1052
1053 $key = substr($str, 0, $keyPos);
1054 $val = substr($str, $keyPos + 1, $valPos - $keyPos - 1);
1055
1056 //decoding the respose
1057 $result[strtolower(urldecode($key))] = urldecode($val);
1058 $str = substr($str, $valPos + 1, strlen($str));
1059 }
1060
1061 return $result;
1062 }
1063
1064 /**
1065 * Get array of fields that should be displayed on the payment form.
1066 *
1067 * @return array
1068 * @throws CiviCRM_API3_Exception
1069 */
1070 public function getPaymentFormFields() {
1071 if ($this->_processorName == ts('PayPal Pro')) {
1072 return $this->getCreditCardFormFields();
1073 }
1074 else {
1075 return array();
1076 }
1077 }
1078
1079 /**
1080 * Map the paypal params to CiviCRM params using a field map.
1081 *
1082 * @param array $fieldMap
1083 * @param array $paypalParams
1084 *
1085 * @return array
1086 */
1087 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1088 $params = array();
1089 foreach ($fieldMap as $civicrmField => $paypalField) {
1090 $params[$civicrmField] = isset($paypalParams[$paypalField]) ? $paypalParams[$paypalField] : NULL;
1091 }
1092 return $params;
1093 }
1094
1095 /**
1096 * Is this being processed by payment express.
1097 *
1098 * Either because it is payment express or because is pro with paypal express in use.
1099 *
1100 * @param array $params
1101 *
1102 * @return bool
1103 */
1104 protected function isPaypalExpress($params) {
1105 if ($this->_processorName == ts('PayPal Express')) {
1106 return TRUE;
1107 }
1108
1109 // This would occur postProcess.
1110 if (!empty($params['token'])) {
1111 return TRUE;
1112 }
1113 if (isset($params['button']) && stristr($params['button'], 'express')) {
1114 return TRUE;
1115 }
1116
1117 // The contribution form passes a 'button' but the event form might still set one of these fields.
1118 // @todo more standardisation & get paypal fully out of the form layer.
1119 $possibleExpressFields = array(
1120 '_qf_Register_upload_express_x',
1121 '_qf_Payment_upload_express_x',
1122 );
1123 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {
1124 return TRUE;
1125 }
1126 return FALSE;
1127 }
1128
1129 }