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