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