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