Merge pull request #6509 from eileenmcnaughton/test-fixes
[civicrm-core.git] / CRM / Core / Payment / PayPalImpl.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
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 return $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
322 return $params;
323 }
324
325 //LCD add new function for handling recurring payments for PayPal Express
326 /**
327 * @param array $params
328 *
329 * @return mixed
330 */
331 public function createRecurringPayments(&$params) {
332 $args = array();
333 // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
334 $this->initialize($args, 'CreateRecurringPaymentsProfile');
335
336 $start_time = strtotime(date('m/d/Y'));
337 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
338
339 $args['token'] = $params['token'];
340 $args['paymentAction'] = 'Sale';
341 $args['amt'] = $params['amount'];
342 $args['currencyCode'] = $params['currencyID'];
343 $args['payerID'] = $params['payer_id'];
344 $args['invnum'] = $params['invoiceID'];
345 $args['returnURL'] = $params['returnURL'];
346 $args['cancelURL'] = $params['cancelURL'];
347 $args['profilestartdate'] = $start_date;
348 $args['method'] = 'CreateRecurringPaymentsProfile';
349 $args['billingfrequency'] = $params['frequency_interval'];
350 $args['billingperiod'] = ucwords($params['frequency_unit']);
351 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
352 //$args['desc'] = 'Recurring Contribution';
353 $args['totalbillingcycles'] = $params['installments'];
354 $args['version'] = '56.0';
355 $args['profilereference'] = "i={$params['invoiceID']}" .
356 "&m=" .
357 "&c={$params['contactID']}" .
358 "&r={$params['contributionRecurID']}" .
359 "&b={$params['contributionID']}" .
360 "&p={$params['contributionPageID']}";
361
362 // add CiviCRM BN code
363 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
364
365 $result = $this->invokeAPI($args);
366
367 if (is_a($result, 'CRM_Core_Error')) {
368 return $result;
369 }
370
371 /* Success */
372 $params['trxn_id'] = $result['transactionid'];
373 $params['gross_amount'] = $result['amt'];
374 $params['fee_amount'] = $result['feeamt'];
375 $params['net_amount'] = $result['settleamt'];
376 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
377 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
378 }
379 $params['payment_status'] = $result['paymentstatus'];
380 $params['pending_reason'] = $result['pendingreason'];
381
382 return $params;
383 }
384 //LCD end
385 /**
386 * @param $args
387 * @param $method
388 */
389 public function initialize(&$args, $method) {
390 $args['user'] = $this->_paymentProcessor['user_name'];
391 $args['pwd'] = $this->_paymentProcessor['password'];
392 $args['version'] = 3.0;
393 $args['signature'] = $this->_paymentProcessor['signature'];
394 $args['subject'] = CRM_Utils_Array::value('subject', $this->_paymentProcessor);
395 $args['method'] = $method;
396 }
397
398 /**
399 * This function collects all the information from a web/api form and invokes
400 * the relevant payment processor specific functions to perform the transaction
401 *
402 * @param array $params
403 * Assoc array of input parameters for this transaction.
404 *
405 * @param string $component
406 * @return array
407 * the result in an nice formatted array (or an error object)
408 */
409 public function doDirectPayment(&$params, $component = 'contribute') {
410 $args = array();
411
412 $this->initialize($args, 'DoDirectPayment');
413
414 $args['paymentAction'] = 'Sale';
415 $args['amt'] = $params['amount'];
416 $args['currencyCode'] = $params['currencyID'];
417 $args['invnum'] = $params['invoiceID'];
418 $args['ipaddress'] = $params['ip_address'];
419 $args['creditCardType'] = $params['credit_card_type'];
420 $args['acct'] = $params['credit_card_number'];
421 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
422 $args['cvv2'] = $params['cvv2'];
423 $args['firstName'] = $params['first_name'];
424 $args['lastName'] = $params['last_name'];
425 $args['email'] = CRM_Utils_Array::value('email', $params);
426 $args['street'] = $params['street_address'];
427 $args['city'] = $params['city'];
428 $args['state'] = $params['state_province'];
429 $args['countryCode'] = $params['country'];
430 $args['zip'] = $params['postal_code'];
431 $args['desc'] = substr(CRM_Utils_Array::value('description', $params), 0, 127);
432 $args['custom'] = CRM_Utils_Array::value('accountingCode', $params);
433
434 // add CiviCRM BN code
435 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
436
437 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
438 $start_time = strtotime(date('m/d/Y'));
439 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
440
441 $args['PaymentAction'] = 'Sale';
442 $args['billingperiod'] = ucwords($params['frequency_unit']);
443 $args['billingfrequency'] = $params['frequency_interval'];
444 $args['method'] = "CreateRecurringPaymentsProfile";
445 $args['profilestartdate'] = $start_date;
446 $args['desc'] = "" .
447 $params['description'] . ": " .
448 $params['amount'] . " Per " .
449 $params['frequency_interval'] . " " .
450 $params['frequency_unit'];
451 $args['amt'] = $params['amount'];
452 $args['totalbillingcycles'] = $params['installments'];
453 $args['version'] = 56.0;
454 $args['PROFILEREFERENCE'] = "" .
455 "i=" . $params['invoiceID'] . "&m=" . $component .
456 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
457 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
458 }
459
460 // Allow further manipulation of the arguments via custom hooks ..
461 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
462
463 $result = $this->invokeAPI($args);
464
465 //WAG
466 if (is_a($result, 'CRM_Core_Error')) {
467 return $result;
468 }
469
470 $params['recurr_profile_id'] = NULL;
471
472 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
473 $params['recurr_profile_id'] = $result['profileid'];
474 }
475
476 /* Success */
477
478 $params['trxn_id'] = CRM_Utils_Array::value('transactionid', $result);
479 $params['gross_amount'] = CRM_Utils_Array::value('amt', $result);
480 return $params;
481 }
482
483 /**
484 * This function checks to see if we have the right config values.
485 *
486 * @return string
487 * the error message if any
488 */
489 public function checkConfig() {
490 $error = array();
491 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
492
493 if ($this->_paymentProcessor['payment_processor_type_id'] != CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
494 if (empty($this->_paymentProcessor['signature'])) {
495 $error[] = ts('Signature is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
496 }
497
498 if (empty($this->_paymentProcessor['password'])) {
499 $error[] = ts('Password is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
500 }
501 }
502 if (!$this->_paymentProcessor['user_name']) {
503 $error[] = ts('User Name is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
504 }
505
506 if (!empty($error)) {
507 return implode('<p>', $error);
508 }
509 else {
510 return NULL;
511 }
512 }
513
514 /**
515 * @return null|string
516 */
517 public function cancelSubscriptionURL() {
518 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Standard') {
519 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']);
520 }
521 else {
522 return NULL;
523 }
524 }
525
526 /**
527 * Check whether a method is present ( & supported ) by the payment processor object.
528 *
529 * @param string $method
530 * Method to check for.
531 *
532 * @return bool
533 */
534 public function isSupported($method = 'cancelSubscription') {
535 if ($this->_paymentProcessor['payment_processor_type'] != 'PayPal') {
536 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
537 // by standard or express.
538 return FALSE;
539 }
540 return parent::isSupported($method);
541 }
542
543 /**
544 * Paypal express replaces the submit button with it's own.
545 *
546 * @return bool
547 * Should the form button by suppressed?
548 */
549 public function isSuppressSubmitButtons() {
550 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express') {
551 return TRUE;
552 }
553 return FALSE;
554 }
555
556 /**
557 * @param string $message
558 * @param array $params
559 *
560 * @return array|bool|object
561 */
562 public function cancelSubscription(&$message = '', $params = array()) {
563 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
564 $args = array();
565 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
566
567 $args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params);
568 $args['ACTION'] = 'Cancel';
569 $args['NOTE'] = CRM_Utils_Array::value('reason', $params);
570
571 $result = $this->invokeAPI($args);
572 if (is_a($result, 'CRM_Core_Error')) {
573 return $result;
574 }
575 $message = "{$result['ack']}: profileid={$result['profileid']}";
576 return TRUE;
577 }
578 return FALSE;
579 }
580
581 /**
582 * Process incoming notification.
583 *
584 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
585 * for paypal standard as the goal must be to separate the 2.
586 *
587 * We don't need to handle paypal standard using this path as there has never been any historic support
588 * for paypal standard to call civicrm/payment/ipn as a path.
589 */
590 static public function handlePaymentNotification() {
591 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
592 $paypalIPN->main();
593 }
594
595 /**
596 * @param string $message
597 * @param array $params
598 *
599 * @return array|bool|object
600 */
601 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
602 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
603 $config = CRM_Core_Config::singleton();
604 $args = array();
605 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
606
607 $args['PROFILEID'] = $params['subscriptionId'];
608 $args['AMT'] = $params['amount'];
609 $args['CURRENCYCODE'] = $config->defaultCurrency;
610 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
611 $args['ACCT'] = $params['credit_card_number'];
612 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
613 $args['CVV2'] = $params['cvv2'];
614
615 $args['FIRSTNAME'] = $params['first_name'];
616 $args['LASTNAME'] = $params['last_name'];
617 $args['STREET'] = $params['street_address'];
618 $args['CITY'] = $params['city'];
619 $args['STATE'] = $params['state_province'];
620 $args['COUNTRYCODE'] = $params['postal_code'];
621 $args['ZIP'] = $params['country'];
622
623 $result = $this->invokeAPI($args);
624 if (is_a($result, 'CRM_Core_Error')) {
625 return $result;
626 }
627 $message = "{$result['ack']}: profileid={$result['profileid']}";
628 return TRUE;
629 }
630 return FALSE;
631 }
632
633 /**
634 * @param string $message
635 * @param array $params
636 *
637 * @return array|bool|object
638 */
639 public function changeSubscriptionAmount(&$message = '', $params = array()) {
640 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
641 $config = CRM_Core_Config::singleton();
642 $args = array();
643 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
644
645 $args['PROFILEID'] = $params['subscriptionId'];
646 $args['AMT'] = $params['amount'];
647 $args['CURRENCYCODE'] = $config->defaultCurrency;
648 $args['BILLINGFREQUENCY'] = $params['installments'];
649
650 $result = $this->invokeAPI($args);
651 CRM_Core_Error::debug_var('$result', $result);
652 if (is_a($result, 'CRM_Core_Error')) {
653 return $result;
654 }
655 $message = "{$result['ack']}: profileid={$result['profileid']}";
656 return TRUE;
657 }
658 return FALSE;
659 }
660
661 /**
662 * Function to action pre-approval if supported
663 *
664 * @param array $params
665 * Parameters from the form
666 *
667 * @return array
668 * - pre_approval_parameters (this will be stored on the calling form & available later)
669 * - redirect_url (if set the browser will be redirected to this.
670 */
671 public function doPreApproval(&$params) {
672 $this->_component = $params['component'];
673 $token = $this->setExpressCheckOut($params);
674 return array(
675 'pre_approval_parameters' => array('token' => $token),
676 'redirect_url' => $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
677 );
678 }
679
680 /**
681 * @param array $params
682 * @param string $component
683 *
684 * @throws Exception
685 */
686 public function doTransferCheckout(&$params, $component = 'contribute') {
687 $config = CRM_Core_Config::singleton();
688
689 if ($component != 'contribute' && $component != 'event') {
690 CRM_Core_Error::fatal(ts('Component is invalid'));
691 }
692
693 $notifyURL = $config->userFrameworkResourceURL . "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
694
695 if ($component == 'event') {
696 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
697 }
698 else {
699 $membershipID = CRM_Utils_Array::value('membershipID', $params);
700 if ($membershipID) {
701 $notifyURL .= "&membershipID=$membershipID";
702 }
703 $relatedContactID = CRM_Utils_Array::value('related_contact', $params);
704 if ($relatedContactID) {
705 $notifyURL .= "&relatedContactID=$relatedContactID";
706
707 $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params);
708 if ($onBehalfDupeAlert) {
709 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
710 }
711 }
712 }
713
714 $url = ($component == 'event') ? 'civicrm/event/register' : 'civicrm/contribute/transact';
715 $cancel = ($component == 'event') ? '_qf_Register_display' : '_qf_Main_display';
716 $returnURL = CRM_Utils_System::url($url,
717 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
718 TRUE, NULL, FALSE
719 );
720
721 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
722 if (!empty($params['is_recur'])) {
723 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
724 }
725
726 $cancelURL = CRM_Utils_System::url(
727 $url,
728 $cancelUrlString,
729 TRUE, NULL, FALSE
730 );
731
732 // ensure that the returnURL is absolute.
733 if (substr($returnURL, 0, 4) != 'http') {
734 $fixUrl = CRM_Utils_System::url("civicrm/admin/setting/url", '&reset=1');
735 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)));
736 }
737
738 $paypalParams = array(
739 'business' => $this->_paymentProcessor['user_name'],
740 'notify_url' => $notifyURL,
741 'item_name' => $params['item_name'],
742 'quantity' => 1,
743 'undefined_quantity' => 0,
744 'cancel_return' => $cancelURL,
745 'no_note' => 1,
746 'no_shipping' => 1,
747 'return' => $returnURL,
748 'rm' => 2,
749 'currency_code' => $params['currencyID'],
750 'invoice' => $params['invoiceID'],
751 'lc' => substr($config->lcMessages, -2),
752 'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8',
753 'custom' => CRM_Utils_Array::value('accountingCode', $params),
754 'bn' => 'CiviCRM_SP',
755 );
756
757 // add name and address if available, CRM-3130
758 $otherVars = array(
759 'first_name' => 'first_name',
760 'last_name' => 'last_name',
761 'street_address' => 'address1',
762 'country' => 'country',
763 'preferred_language' => 'lc',
764 'city' => 'city',
765 'state_province' => 'state',
766 'postal_code' => 'zip',
767 'email' => 'email',
768 );
769
770 foreach (array_keys($params) as $p) {
771 // get the base name without the location type suffixed to it
772 $parts = explode('-', $p);
773 $name = count($parts) > 1 ? $parts[0] : $p;
774 if (isset($otherVars[$name])) {
775 $value = $params[$p];
776 if ($value) {
777 if ($name == 'state_province') {
778 $stateName = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
779 $value = $stateName;
780 }
781 if ($name == 'country') {
782 $countryName = CRM_Core_PseudoConstant::countryIsoCode($value);
783 $value = $countryName;
784 }
785 // ensure value is not an array
786 // CRM-4174
787 if (!is_array($value)) {
788 $paypalParams[$otherVars[$name]] = $value;
789 }
790 }
791 }
792 }
793
794 // if recurring donations, add a few more items
795 if (!empty($params['is_recur'])) {
796 if ($params['contributionRecurID']) {
797 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
798 $paypalParams['notify_url'] = $notifyURL;
799 }
800 else {
801 CRM_Core_Error::fatal(ts('Recurring contribution, but no database id'));
802 }
803
804 $paypalParams += array(
805 'cmd' => '_xclick-subscriptions',
806 'a3' => $params['amount'],
807 'p3' => $params['frequency_interval'],
808 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
809 'src' => 1,
810 'sra' => 1,
811 'srt' => CRM_Utils_Array::value('installments', $params),
812 'no_note' => 1,
813 'modify' => 0,
814 );
815 }
816 else {
817 $paypalParams += array(
818 'cmd' => '_xclick',
819 'amount' => $params['amount'],
820 );
821 }
822
823 // Allow further manipulation of the arguments via custom hooks ..
824 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $paypalParams);
825
826 $uri = '';
827 foreach ($paypalParams as $key => $value) {
828 if ($value === NULL) {
829 continue;
830 }
831
832 $value = urlencode($value);
833 if ($key == 'return' ||
834 $key == 'cancel_return' ||
835 $key == 'notify_url'
836 ) {
837 $value = str_replace('%2F', '/', $value);
838 }
839 $uri .= "&{$key}={$value}";
840 }
841
842 $uri = substr($uri, 1);
843 $url = $this->_paymentProcessor['url_site'];
844 $sub = empty($params['is_recur']) ? 'cgi-bin/webscr' : 'subscriptions';
845 $paypalURL = "{$url}{$sub}?$uri";
846
847 CRM_Utils_System::redirect($paypalURL);
848 }
849
850 /**
851 * Hash_call: Function to perform the API call to PayPal using API signature
852 * @methodName is name of API method.
853 * @nvpStr is nvp string.
854 * returns an associtive array containing the response from the server.
855 */
856 public function invokeAPI($args, $url = NULL) {
857
858 if ($url === NULL) {
859 if (empty($this->_paymentProcessor['url_api'])) {
860 CRM_Core_Error::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
861 }
862
863 $url = $this->_paymentProcessor['url_api'] . 'nvp';
864 }
865
866 if (!function_exists('curl_init')) {
867 CRM_Core_Error::fatal("curl functions NOT available.");
868 }
869
870 //setting the curl parameters.
871 $ch = curl_init();
872 curl_setopt($ch, CURLOPT_URL, $url);
873 curl_setopt($ch, CURLOPT_VERBOSE, 1);
874
875 //turning off the server and peer verification(TrustManager Concept).
876 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
877 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL') ? 2 : 0);
878
879 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
880 curl_setopt($ch, CURLOPT_POST, 1);
881
882 $p = array();
883 foreach ($args as $n => $v) {
884 $p[] = "$n=" . urlencode($v);
885 }
886
887 //NVPRequest for submitting to server
888 $nvpreq = implode('&', $p);
889
890 //setting the nvpreq as POST FIELD to curl
891 curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
892
893 //getting response from server
894 $response = curl_exec($ch);
895
896 //converting NVPResponse to an Associative Array
897 $result = self::deformat($response);
898
899 if (curl_errno($ch)) {
900 $e = CRM_Core_Error::singleton();
901 $e->push(curl_errno($ch),
902 0, NULL,
903 curl_error($ch)
904 );
905 return $e;
906 }
907 else {
908 curl_close($ch);
909 }
910
911 if (strtolower($result['ack']) != 'success' &&
912 strtolower($result['ack']) != 'successwithwarning'
913 ) {
914 $e = CRM_Core_Error::singleton();
915 $e->push($result['l_errorcode0'],
916 0, NULL,
917 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
918 );
919 return $e;
920 }
921
922 return $result;
923 }
924
925 /**
926 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
927 * It is useful to search for a particular key and displaying arrays.
928 * @nvpstr is NVPString.
929 * @nvpArray is Associative Array.
930 */
931 public static function deformat($str) {
932 $result = array();
933
934 while (strlen($str)) {
935 // position of key
936 $keyPos = strpos($str, '=');
937
938 // position of value
939 $valPos = strpos($str, '&') ? strpos($str, '&') : strlen($str);
940
941 /*getting the Key and Value values and storing in a Associative Array*/
942
943 $key = substr($str, 0, $keyPos);
944 $val = substr($str, $keyPos + 1, $valPos - $keyPos - 1);
945
946 //decoding the respose
947 $result[strtolower(urldecode($key))] = urldecode($val);
948 $str = substr($str, $valPos + 1, strlen($str));
949 }
950
951 return $result;
952 }
953
954 /**
955 * Get array of fields that should be displayed on the payment form.
956 *
957 * @return array
958 * @throws CiviCRM_API3_Exception
959 */
960 public function getPaymentFormFields() {
961 if ($this->_processorName == ts('PayPal Pro')) {
962 return $this->getCreditCardFormFields();
963 }
964 else {
965 return array();
966 }
967 }
968
969 /**
970 * Map the paypal params to CiviCRM params using a field map.
971 *
972 * @param array $fieldMap
973 * @param array $paypalParams
974 *
975 * @return array
976 */
977 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
978 $params = array();
979 foreach ($fieldMap as $civicrmField => $paypalField) {
980 $params[$civicrmField] = isset($paypalParams[$paypalField]) ? $paypalParams[$paypalField] : NULL;
981 }
982 return $params;
983 }
984
985 }