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