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