CRM-11338 retrieve fee_amount from paypal
[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 * $Id$
33 *
34 */
35 class CRM_Core_Payment_PayPalImpl extends CRM_Core_Payment {
36 const CHARSET = 'iso-8859-1';
37
38 protected $_mode = NULL;
39
40 /**
41 * We only need one instance of this object. So we use the singleton
42 * pattern and cache the instance in this variable
43 *
44 * @var object
45 */
46 static private $_singleton = NULL;
47
48 /**
49 * Constructor.
50 *
51 * @param string $mode
52 * The mode of operation: live or test.
53 *
54 * @param $paymentProcessor
55 *
56 * @return \CRM_Core_Payment_PayPalImpl
57 */
58 public function __construct($mode, &$paymentProcessor) {
59 $this->_mode = $mode;
60 $this->_paymentProcessor = $paymentProcessor;
61 $this->_processorName = ts('PayPal Pro');
62 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
63
64 if ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
65 $this->_processorName = ts('PayPal Standard');
66 return;
67 }
68 elseif ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Express', $paymentProcessorType)) {
69 $this->_processorName = ts('PayPal Express');
70 }
71
72 if (!$this->_paymentProcessor['user_name']) {
73 CRM_Core_Error::fatal(ts('Could not find user name for payment processor'));
74 }
75 }
76
77 /**
78 * Are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
79 * @return bool
80 */
81 protected function supportsBackOffice() {
82 if ($this->_processorName == ts('PayPal Pro')) {
83 return TRUE;
84 }
85 return FALSE;
86 }
87
88 /**
89 * Can recurring contributions be set against pledges.
90 *
91 * In practice all processors that use the baseIPN function to finish transactions or
92 * call the completetransaction api support this by looking up previous contributions in the
93 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
94 * adding the new payment to the pledge.
95 *
96 * However, only enabling for processors it has been tested against.
97 *
98 * @return bool
99 */
100 protected function supportsRecurContributionsForPledges() {
101 return TRUE;
102 }
103
104 /**
105 * Express checkout code. Check PayPal documentation for more information
106 *
107 * @param array $params
108 * Assoc array of input parameters for this transaction.
109 *
110 * @return array
111 * the result in an nice formatted array (or an error object)
112 */
113 public function setExpressCheckOut(&$params) {
114 $args = array();
115
116 $this->initialize($args, 'SetExpressCheckout');
117
118 $args['paymentAction'] = $params['payment_action'];
119 $args['amt'] = $params['amount'];
120 $args['currencyCode'] = $params['currencyID'];
121 $args['desc'] = CRM_Utils_Array::value('description', $params);
122 $args['invnum'] = $params['invoiceID'];
123 $args['returnURL'] = $params['returnURL'];
124 $args['cancelURL'] = $params['cancelURL'];
125 $args['version'] = '56.0';
126
127 //LCD if recurring, collect additional data and set some values
128 if (!empty($params['is_recur'])) {
129 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
130 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
131 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
132 $args['L_PAYMENTTYPE0'] = 'Any';
133 }
134
135 // Allow further manipulation of the arguments via custom hooks ..
136 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
137
138 $result = $this->invokeAPI($args);
139
140 if (is_a($result, 'CRM_Core_Error')) {
141 return $result;
142 }
143
144 /* Success */
145
146 return $result['token'];
147 }
148
149 /**
150 * Get details from paypal. Check PayPal documentation for more information
151 *
152 * @param string $token
153 * The key associated with this transaction.
154 *
155 * @return array
156 * the result in an nice formatted array (or an error object)
157 */
158 public function getExpressCheckoutDetails($token) {
159 $args = array();
160
161 $this->initialize($args, 'GetExpressCheckoutDetails');
162 $args['token'] = $token;
163 // LCD
164 $args['method'] = 'GetExpressCheckoutDetails';
165
166 $result = $this->invokeAPI($args);
167
168 if (is_a($result, 'CRM_Core_Error')) {
169 return $result;
170 }
171
172 /* Success */
173
174 $params = array();
175 $params['token'] = $result['token'];
176 $params['payer_id'] = $result['payerid'];
177 $params['payer_status'] = $result['payerstatus'];
178 $params['first_name'] = $result['firstname'];
179 $params['middle_name'] = CRM_Utils_Array::value('middlename', $result);
180 $params['last_name'] = $result['lastname'];
181 $params['street_address'] = $result['shiptostreet'];
182 $params['supplemental_address_1'] = CRM_Utils_Array::value('shiptostreet2', $result);
183 $params['city'] = $result['shiptocity'];
184 $params['state_province'] = $result['shiptostate'];
185 $params['postal_code'] = $result['shiptozip'];
186 $params['country'] = $result['shiptocountrycode'];
187
188 return $params;
189 }
190
191 /**
192 * Do the express checkout at paypal. Check PayPal documentation for more information
193 *
194 * @param array $params
195 *
196 * @internal param string $token the key associated with this transaction
197 *
198 * @return array
199 * the result in an nice formatted array (or an error object)
200 */
201 public function doExpressCheckout(&$params) {
202 $args = array();
203
204 $this->initialize($args, 'DoExpressCheckoutPayment');
205
206 $args['token'] = $params['token'];
207 $args['paymentAction'] = $params['payment_action'];
208 $args['amt'] = $params['amount'];
209 $args['currencyCode'] = $params['currencyID'];
210 $args['payerID'] = $params['payer_id'];
211 $args['invnum'] = $params['invoiceID'];
212 $args['returnURL'] = CRM_Utils_Array::value('returnURL', $params);
213 $args['cancelURL'] = CRM_Utils_Array::value('cancelURL', $params);
214 $args['desc'] = $params['description'];
215
216 // add CiviCRM BN code
217 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
218
219 $result = $this->invokeAPI($args);
220
221 if (is_a($result, 'CRM_Core_Error')) {
222 return $result;
223 }
224
225 /* Success */
226
227 $params['trxn_id'] = $result['transactionid'];
228 $params['gross_amount'] = $result['amt'];
229 $params['fee_amount'] = $result['feeamt'];
230 $params['net_amount'] = CRM_Utils_Array::value('settleamt', $result);
231 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
232 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
233 }
234 $params['payment_status'] = $result['paymentstatus'];
235 $params['pending_reason'] = $result['pendingreason'];
236
237 return $params;
238 }
239
240 //LCD add new function for handling recurring payments for PayPal Express
241 /**
242 * @param array $params
243 *
244 * @return mixed
245 */
246 public function createRecurringPayments(&$params) {
247 $args = array();
248
249 $this->initialize($args, 'CreateRecurringPaymentsProfile');
250
251 $start_time = strtotime(date('m/d/Y'));
252 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
253
254 $args['token'] = $params['token'];
255 $args['paymentAction'] = $params['payment_action'];
256 $args['amt'] = $params['amount'];
257 $args['currencyCode'] = $params['currencyID'];
258 $args['payerID'] = $params['payer_id'];
259 $args['invnum'] = $params['invoiceID'];
260 $args['returnURL'] = $params['returnURL'];
261 $args['cancelURL'] = $params['cancelURL'];
262 $args['profilestartdate'] = $start_date;
263 $args['method'] = 'CreateRecurringPaymentsProfile';
264 $args['billingfrequency'] = $params['frequency_interval'];
265 $args['billingperiod'] = ucwords($params['frequency_unit']);
266 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
267 //$args['desc'] = 'Recurring Contribution';
268 $args['totalbillingcycles'] = $params['installments'];
269 $args['version'] = '56.0';
270 $args['profilereference'] = "i={$params['invoiceID']}" .
271 "&m=$component" .
272 "&c={$params['contactID']}" .
273 "&r={$params['contributionRecurID']}" .
274 "&b={$params['contributionID']}" .
275 "&p={$params['contributionPageID']}";
276
277 // add CiviCRM BN code
278 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
279
280 $result = $this->invokeAPI($args);
281
282 if (is_a($result, 'CRM_Core_Error')) {
283 return $result;
284 }
285
286 /* Success */
287 $params['trxn_id'] = $result['transactionid'];
288 $params['gross_amount'] = $result['amt'];
289 $params['fee_amount'] = $result['feeamt'];
290 $params['net_amount'] = $result['settleamt'];
291 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
292 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
293 }
294 $params['payment_status'] = $result['paymentstatus'];
295 $params['pending_reason'] = $result['pendingreason'];
296
297 return $params;
298 }
299 //LCD end
300 /**
301 * @param $args
302 * @param $method
303 */
304 public function initialize(&$args, $method) {
305 $args['user'] = $this->_paymentProcessor['user_name'];
306 $args['pwd'] = $this->_paymentProcessor['password'];
307 $args['version'] = 3.0;
308 $args['signature'] = $this->_paymentProcessor['signature'];
309 $args['subject'] = CRM_Utils_Array::value('subject', $this->_paymentProcessor);
310 $args['method'] = $method;
311 }
312
313 /**
314 * This function collects all the information from a web/api form and invokes
315 * the relevant payment processor specific functions to perform the transaction
316 *
317 * @param array $params
318 * Assoc array of input parameters for this transaction.
319 *
320 * @param string $component
321 * @return array
322 * the result in an nice formatted array (or an error object)
323 */
324 public function doDirectPayment(&$params, $component = 'contribute') {
325 $args = array();
326
327 $this->initialize($args, 'DoDirectPayment');
328
329 $args['paymentAction'] = $params['payment_action'];
330 $args['amt'] = $params['amount'];
331 $args['currencyCode'] = $params['currencyID'];
332 $args['invnum'] = $params['invoiceID'];
333 $args['ipaddress'] = $params['ip_address'];
334 $args['creditCardType'] = $params['credit_card_type'];
335 $args['acct'] = $params['credit_card_number'];
336 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
337 $args['cvv2'] = $params['cvv2'];
338 $args['firstName'] = $params['first_name'];
339 $args['lastName'] = $params['last_name'];
340 $args['email'] = CRM_Utils_Array::value('email', $params);
341 $args['street'] = $params['street_address'];
342 $args['city'] = $params['city'];
343 $args['state'] = $params['state_province'];
344 $args['countryCode'] = $params['country'];
345 $args['zip'] = $params['postal_code'];
346 $args['desc'] = substr(CRM_Utils_Array::value('description', $params), 0, 127);
347 $args['custom'] = CRM_Utils_Array::value('accountingCode', $params);
348
349 // add CiviCRM BN code
350 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
351
352 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
353 $start_time = strtotime(date('m/d/Y'));
354 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
355
356 $args['PaymentAction'] = 'Sale';
357 $args['billingperiod'] = ucwords($params['frequency_unit']);
358 $args['billingfrequency'] = $params['frequency_interval'];
359 $args['method'] = "CreateRecurringPaymentsProfile";
360 $args['profilestartdate'] = $start_date;
361 $args['desc'] = "" .
362 $params['description'] . ": " .
363 $params['amount'] . " Per " .
364 $params['frequency_interval'] . " " .
365 $params['frequency_unit'];
366 $args['amt'] = $params['amount'];
367 $args['totalbillingcycles'] = $params['installments'];
368 $args['version'] = 56.0;
369 $args['PROFILEREFERENCE'] = "" .
370 "i=" . $params['invoiceID'] . "&m=" . $component .
371 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
372 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
373 }
374
375 // Allow further manipulation of the arguments via custom hooks ..
376 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
377
378 $result = $this->invokeAPI($args);
379
380 //WAG
381 if (is_a($result, 'CRM_Core_Error')) {
382 return $result;
383 }
384
385 $params['recurr_profile_id'] = NULL;
386
387 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
388 $params['recurr_profile_id'] = $result['profileid'];
389 }
390
391 /* Success */
392
393 $params['trxn_id'] = CRM_Utils_Array::value('transactionid', $result);
394 $params['gross_amount'] = CRM_Utils_Array::value('amt', $result);
395 $params = array_merge($params, $this->doQuery($params));
396 return $params;
397 }
398
399 /**
400 * Query payment processor for details about a transaction.
401 *
402 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
403 *
404 * @param array $params
405 * Array of parameters containing one of:
406 * - trxn_id Id of an individual transaction.
407 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
408 *
409 * @return array
410 * Extra parameters retrieved.
411 * Any parameters retrievable through this should be documented in the function comments at
412 * CRM_Core_Payment::doQuery. Currently
413 * - fee_amount Amount of fee paid
414 *
415 * @throws \Civi\Payment\Exception\PaymentProcessorException
416 */
417 public function doQuery($params) {
418 if (empty($params['trxn_id'])) {
419 throw new \Civi\Payment\Exception\PaymentProcessorException('transaction id not set');
420 }
421 $args = array(
422 'TRANSACTIONID' => $params['trxn_id'],
423 );
424 $this->initialize($args, 'GetTransactionDetails');
425 $result = $this->invokeAPI($args);
426 return array(
427 'fee_amount' => $result['feeamt'],
428 );
429 }
430
431 /**
432 * This function checks to see if we have the right config values.
433 *
434 * @return string
435 * the error message if any
436 */
437 public function checkConfig() {
438 $error = array();
439 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
440 if (
441 $this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType) ||
442 $this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal', $paymentProcessorType)
443 ) {
444 if (empty($this->_paymentProcessor['user_name'])) {
445 $error[] = ts('User Name is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
446 }
447 }
448
449 if ($this->_paymentProcessor['payment_processor_type_id'] != CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
450 if (empty($this->_paymentProcessor['signature'])) {
451 $error[] = ts('Signature is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
452 }
453
454 if (empty($this->_paymentProcessor['password'])) {
455 $error[] = ts('Password is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
456 }
457 }
458
459 if (!empty($error)) {
460 return implode('<p>', $error);
461 }
462 else {
463 return NULL;
464 }
465 }
466
467 /**
468 * @return null|string
469 */
470 public function cancelSubscriptionURL() {
471 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Standard') {
472 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']);
473 }
474 else {
475 return NULL;
476 }
477 }
478
479 /**
480 * Check whether a method is present ( & supported ) by the payment processor object.
481 *
482 * @param string $method
483 * Method to check for.
484 *
485 * @return bool
486 */
487 public function isSupported($method = 'cancelSubscription') {
488 if ($this->_paymentProcessor['payment_processor_type'] != 'PayPal') {
489 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
490 // by standard or express.
491 return FALSE;
492 }
493 return parent::isSupported($method);
494 }
495
496 /**
497 * @param string $message
498 * @param array $params
499 *
500 * @return array|bool|object
501 */
502 public function cancelSubscription(&$message = '', $params = array()) {
503 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
504 $args = array();
505 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
506
507 $args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params);
508 $args['ACTION'] = 'Cancel';
509 $args['NOTE'] = CRM_Utils_Array::value('reason', $params);
510
511 $result = $this->invokeAPI($args);
512 if (is_a($result, 'CRM_Core_Error')) {
513 return $result;
514 }
515 $message = "{$result['ack']}: profileid={$result['profileid']}";
516 return TRUE;
517 }
518 return FALSE;
519 }
520
521 /**
522 * Process incoming notification.
523 *
524 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
525 * for paypal standard as the goal must be to separate the 2.
526 *
527 * We don't need to handle paypal standard using this path as there has never been any historic support
528 * for paypal standard to call civicrm/payment/ipn as a path.
529 */
530 static public function handlePaymentNotification() {
531 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
532 $paypalIPN->main();
533 }
534
535 /**
536 * @param string $message
537 * @param array $params
538 *
539 * @return array|bool|object
540 */
541 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
542 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
543 $config = CRM_Core_Config::singleton();
544 $args = array();
545 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
546
547 $args['PROFILEID'] = $params['subscriptionId'];
548 $args['AMT'] = $params['amount'];
549 $args['CURRENCYCODE'] = $config->defaultCurrency;
550 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
551 $args['ACCT'] = $params['credit_card_number'];
552 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
553 $args['CVV2'] = $params['cvv2'];
554
555 $args['FIRSTNAME'] = $params['first_name'];
556 $args['LASTNAME'] = $params['last_name'];
557 $args['STREET'] = $params['street_address'];
558 $args['CITY'] = $params['city'];
559 $args['STATE'] = $params['state_province'];
560 $args['COUNTRYCODE'] = $params['postal_code'];
561 $args['ZIP'] = $params['country'];
562
563 $result = $this->invokeAPI($args);
564 if (is_a($result, 'CRM_Core_Error')) {
565 return $result;
566 }
567 $message = "{$result['ack']}: profileid={$result['profileid']}";
568 return TRUE;
569 }
570 return FALSE;
571 }
572
573 /**
574 * @param string $message
575 * @param array $params
576 *
577 * @return array|bool|object
578 */
579 public function changeSubscriptionAmount(&$message = '', $params = array()) {
580 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
581 $config = CRM_Core_Config::singleton();
582 $args = array();
583 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
584
585 $args['PROFILEID'] = $params['subscriptionId'];
586 $args['AMT'] = $params['amount'];
587 $args['CURRENCYCODE'] = $config->defaultCurrency;
588 $args['BILLINGFREQUENCY'] = $params['installments'];
589
590 $result = $this->invokeAPI($args);
591 CRM_Core_Error::debug_var('$result', $result);
592 if (is_a($result, 'CRM_Core_Error')) {
593 return $result;
594 }
595 $message = "{$result['ack']}: profileid={$result['profileid']}";
596 return TRUE;
597 }
598 return FALSE;
599 }
600
601 /**
602 * @param array $params
603 * @param string $component
604 *
605 * @throws Exception
606 */
607 public function doTransferCheckout(&$params, $component = 'contribute') {
608 $config = CRM_Core_Config::singleton();
609
610 if ($component != 'contribute' && $component != 'event') {
611 CRM_Core_Error::fatal(ts('Component is invalid'));
612 }
613
614 $notifyURL = $config->userFrameworkResourceURL . "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
615
616 if ($component == 'event') {
617 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
618 }
619 else {
620 $membershipID = CRM_Utils_Array::value('membershipID', $params);
621 if ($membershipID) {
622 $notifyURL .= "&membershipID=$membershipID";
623 }
624 $relatedContactID = CRM_Utils_Array::value('related_contact', $params);
625 if ($relatedContactID) {
626 $notifyURL .= "&relatedContactID=$relatedContactID";
627
628 $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params);
629 if ($onBehalfDupeAlert) {
630 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
631 }
632 }
633 }
634
635 $url = ($component == 'event') ? 'civicrm/event/register' : 'civicrm/contribute/transact';
636 $cancel = ($component == 'event') ? '_qf_Register_display' : '_qf_Main_display';
637 $returnURL = CRM_Utils_System::url($url,
638 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
639 TRUE, NULL, FALSE
640 );
641
642 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
643 if (!empty($params['is_recur'])) {
644 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
645 }
646
647 $cancelURL = CRM_Utils_System::url(
648 $url,
649 $cancelUrlString,
650 TRUE, NULL, FALSE
651 );
652
653 // ensure that the returnURL is absolute.
654 if (substr($returnURL, 0, 4) != 'http') {
655 $fixUrl = CRM_Utils_System::url("civicrm/admin/setting/url", '&reset=1');
656 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)));
657 }
658
659 $paypalParams = array(
660 'business' => $this->_paymentProcessor['user_name'],
661 'notify_url' => $notifyURL,
662 'item_name' => $params['item_name'],
663 'quantity' => 1,
664 'undefined_quantity' => 0,
665 'cancel_return' => $cancelURL,
666 'no_note' => 1,
667 'no_shipping' => 1,
668 'return' => $returnURL,
669 'rm' => 2,
670 'currency_code' => $params['currencyID'],
671 'invoice' => $params['invoiceID'],
672 'lc' => substr($config->lcMessages, -2),
673 'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8',
674 'custom' => CRM_Utils_Array::value('accountingCode', $params),
675 'bn' => 'CiviCRM_SP',
676 );
677
678 // add name and address if available, CRM-3130
679 $otherVars = array(
680 'first_name' => 'first_name',
681 'last_name' => 'last_name',
682 'street_address' => 'address1',
683 'country' => 'country',
684 'preferred_language' => 'lc',
685 'city' => 'city',
686 'state_province' => 'state',
687 'postal_code' => 'zip',
688 'email' => 'email',
689 );
690
691 foreach (array_keys($params) as $p) {
692 // get the base name without the location type suffixed to it
693 $parts = explode('-', $p);
694 $name = count($parts) > 1 ? $parts[0] : $p;
695 if (isset($otherVars[$name])) {
696 $value = $params[$p];
697 if ($value) {
698 if ($name == 'state_province') {
699 $stateName = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
700 $value = $stateName;
701 }
702 if ($name == 'country') {
703 $countryName = CRM_Core_PseudoConstant::countryIsoCode($value);
704 $value = $countryName;
705 }
706 // ensure value is not an array
707 // CRM-4174
708 if (!is_array($value)) {
709 $paypalParams[$otherVars[$name]] = $value;
710 }
711 }
712 }
713 }
714
715 // if recurring donations, add a few more items
716 if (!empty($params['is_recur'])) {
717 if ($params['contributionRecurID']) {
718 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
719 $paypalParams['notify_url'] = $notifyURL;
720 }
721 else {
722 CRM_Core_Error::fatal(ts('Recurring contribution, but no database id'));
723 }
724
725 $paypalParams += array(
726 'cmd' => '_xclick-subscriptions',
727 'a3' => $params['amount'],
728 'p3' => $params['frequency_interval'],
729 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
730 'src' => 1,
731 'sra' => 1,
732 'srt' => CRM_Utils_Array::value('installments', $params),
733 'no_note' => 1,
734 'modify' => 0,
735 );
736 }
737 else {
738 $paypalParams += array(
739 'cmd' => '_xclick',
740 'amount' => $params['amount'],
741 );
742 }
743
744 // Allow further manipulation of the arguments via custom hooks ..
745 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $paypalParams);
746
747 $uri = '';
748 foreach ($paypalParams as $key => $value) {
749 if ($value === NULL) {
750 continue;
751 }
752
753 $value = urlencode($value);
754 if ($key == 'return' ||
755 $key == 'cancel_return' ||
756 $key == 'notify_url'
757 ) {
758 $value = str_replace('%2F', '/', $value);
759 }
760 $uri .= "&{$key}={$value}";
761 }
762
763 $uri = substr($uri, 1);
764 $url = $this->_paymentProcessor['url_site'];
765 $sub = empty($params['is_recur']) ? 'cgi-bin/webscr' : 'subscriptions';
766 $paypalURL = "{$url}{$sub}?$uri";
767
768 CRM_Utils_System::redirect($paypalURL);
769 }
770
771 /**
772 * Hash_call: Function to perform the API call to PayPal using API signature
773 * @methodName is name of API method.
774 * @nvpStr is nvp string.
775 * returns an associtive array containing the response from the server.
776 */
777 public function invokeAPI($args, $url = NULL) {
778
779 if ($url === NULL) {
780 if (empty($this->_paymentProcessor['url_api'])) {
781 CRM_Core_Error::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
782 }
783
784 $url = $this->_paymentProcessor['url_api'] . 'nvp';
785 }
786
787 if (!function_exists('curl_init')) {
788 CRM_Core_Error::fatal("curl functions NOT available.");
789 }
790
791 //setting the curl parameters.
792 $ch = curl_init();
793 curl_setopt($ch, CURLOPT_URL, $url);
794 curl_setopt($ch, CURLOPT_VERBOSE, 1);
795
796 //turning off the server and peer verification(TrustManager Concept).
797 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
798 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL') ? 2 : 0);
799
800 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
801 curl_setopt($ch, CURLOPT_POST, 1);
802
803 $p = array();
804 foreach ($args as $n => $v) {
805 $p[] = "$n=" . urlencode($v);
806 }
807
808 //NVPRequest for submitting to server
809 $nvpreq = implode('&', $p);
810
811 //setting the nvpreq as POST FIELD to curl
812 curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
813
814 //getting response from server
815 $response = curl_exec($ch);
816
817 //converting NVPResponse to an Associative Array
818 $result = self::deformat($response);
819
820 if (curl_errno($ch)) {
821 $e = CRM_Core_Error::singleton();
822 $e->push(curl_errno($ch),
823 0, NULL,
824 curl_error($ch)
825 );
826 return $e;
827 }
828 else {
829 curl_close($ch);
830 }
831
832 if (strtolower($result['ack']) != 'success' &&
833 strtolower($result['ack']) != 'successwithwarning'
834 ) {
835 $e = CRM_Core_Error::singleton();
836 $e->push($result['l_errorcode0'],
837 0, NULL,
838 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
839 );
840 return $e;
841 }
842
843 return $result;
844 }
845
846 /**
847 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
848 * It is usefull to search for a particular key and displaying arrays.
849 * @nvpstr is NVPString.
850 * @nvpArray is Associative Array.
851 */
852 public static function deformat($str) {
853 $result = array();
854
855 while (strlen($str)) {
856 // postion of key
857 $keyPos = strpos($str, '=');
858
859 // position of value
860 $valPos = strpos($str, '&') ? strpos($str, '&') : strlen($str);
861
862 /*getting the Key and Value values and storing in a Associative Array*/
863
864 $key = substr($str, 0, $keyPos);
865 $val = substr($str, $keyPos + 1, $valPos - $keyPos - 1);
866
867 //decoding the respose
868 $result[strtolower(urldecode($key))] = urldecode($val);
869 $str = substr($str, $valPos + 1, strlen($str));
870 }
871
872 return $result;
873 }
874
875 }