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