db76d97e72094ed7a20de331bd500f8a107a7f91
[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 'net_amount' => $params['gross_amount'] - $result['feeamt'],
429 );
430 }
431
432 /**
433 * This function checks to see if we have the right config values.
434 *
435 * @return string
436 * the error message if any
437 */
438 public function checkConfig() {
439 $error = array();
440 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
441 if (
442 $this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType) ||
443 $this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal', $paymentProcessorType)
444 ) {
445 if (empty($this->_paymentProcessor['user_name'])) {
446 $error[] = ts('User Name is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
447 }
448 }
449
450 if ($this->_paymentProcessor['payment_processor_type_id'] != CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
451 if (empty($this->_paymentProcessor['signature'])) {
452 $error[] = ts('Signature is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
453 }
454
455 if (empty($this->_paymentProcessor['password'])) {
456 $error[] = ts('Password is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
457 }
458 }
459
460 if (!empty($error)) {
461 return implode('<p>', $error);
462 }
463 else {
464 return NULL;
465 }
466 }
467
468 /**
469 * @return null|string
470 */
471 public function cancelSubscriptionURL() {
472 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Standard') {
473 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']);
474 }
475 else {
476 return NULL;
477 }
478 }
479
480 /**
481 * Check whether a method is present ( & supported ) by the payment processor object.
482 *
483 * @param string $method
484 * Method to check for.
485 *
486 * @return bool
487 */
488 public function isSupported($method = 'cancelSubscription') {
489 if ($this->_paymentProcessor['payment_processor_type'] != 'PayPal') {
490 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
491 // by standard or express.
492 return FALSE;
493 }
494 return parent::isSupported($method);
495 }
496
497 /**
498 * @param string $message
499 * @param array $params
500 *
501 * @return array|bool|object
502 */
503 public function cancelSubscription(&$message = '', $params = array()) {
504 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
505 $args = array();
506 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
507
508 $args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params);
509 $args['ACTION'] = 'Cancel';
510 $args['NOTE'] = CRM_Utils_Array::value('reason', $params);
511
512 $result = $this->invokeAPI($args);
513 if (is_a($result, 'CRM_Core_Error')) {
514 return $result;
515 }
516 $message = "{$result['ack']}: profileid={$result['profileid']}";
517 return TRUE;
518 }
519 return FALSE;
520 }
521
522 /**
523 * Process incoming notification.
524 *
525 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
526 * for paypal standard as the goal must be to separate the 2.
527 *
528 * We don't need to handle paypal standard using this path as there has never been any historic support
529 * for paypal standard to call civicrm/payment/ipn as a path.
530 */
531 static public function handlePaymentNotification() {
532 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
533 $paypalIPN->main();
534 }
535
536 /**
537 * @param string $message
538 * @param array $params
539 *
540 * @return array|bool|object
541 */
542 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
543 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
544 $config = CRM_Core_Config::singleton();
545 $args = array();
546 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
547
548 $args['PROFILEID'] = $params['subscriptionId'];
549 $args['AMT'] = $params['amount'];
550 $args['CURRENCYCODE'] = $config->defaultCurrency;
551 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
552 $args['ACCT'] = $params['credit_card_number'];
553 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
554 $args['CVV2'] = $params['cvv2'];
555
556 $args['FIRSTNAME'] = $params['first_name'];
557 $args['LASTNAME'] = $params['last_name'];
558 $args['STREET'] = $params['street_address'];
559 $args['CITY'] = $params['city'];
560 $args['STATE'] = $params['state_province'];
561 $args['COUNTRYCODE'] = $params['postal_code'];
562 $args['ZIP'] = $params['country'];
563
564 $result = $this->invokeAPI($args);
565 if (is_a($result, 'CRM_Core_Error')) {
566 return $result;
567 }
568 $message = "{$result['ack']}: profileid={$result['profileid']}";
569 return TRUE;
570 }
571 return FALSE;
572 }
573
574 /**
575 * @param string $message
576 * @param array $params
577 *
578 * @return array|bool|object
579 */
580 public function changeSubscriptionAmount(&$message = '', $params = array()) {
581 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
582 $config = CRM_Core_Config::singleton();
583 $args = array();
584 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
585
586 $args['PROFILEID'] = $params['subscriptionId'];
587 $args['AMT'] = $params['amount'];
588 $args['CURRENCYCODE'] = $config->defaultCurrency;
589 $args['BILLINGFREQUENCY'] = $params['installments'];
590
591 $result = $this->invokeAPI($args);
592 CRM_Core_Error::debug_var('$result', $result);
593 if (is_a($result, 'CRM_Core_Error')) {
594 return $result;
595 }
596 $message = "{$result['ack']}: profileid={$result['profileid']}";
597 return TRUE;
598 }
599 return FALSE;
600 }
601
602 /**
603 * @param array $params
604 * @param string $component
605 *
606 * @throws Exception
607 */
608 public function doTransferCheckout(&$params, $component = 'contribute') {
609 $config = CRM_Core_Config::singleton();
610
611 if ($component != 'contribute' && $component != 'event') {
612 CRM_Core_Error::fatal(ts('Component is invalid'));
613 }
614
615 $notifyURL = $config->userFrameworkResourceURL . "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
616
617 if ($component == 'event') {
618 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
619 }
620 else {
621 $membershipID = CRM_Utils_Array::value('membershipID', $params);
622 if ($membershipID) {
623 $notifyURL .= "&membershipID=$membershipID";
624 }
625 $relatedContactID = CRM_Utils_Array::value('related_contact', $params);
626 if ($relatedContactID) {
627 $notifyURL .= "&relatedContactID=$relatedContactID";
628
629 $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params);
630 if ($onBehalfDupeAlert) {
631 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
632 }
633 }
634 }
635
636 $url = ($component == 'event') ? 'civicrm/event/register' : 'civicrm/contribute/transact';
637 $cancel = ($component == 'event') ? '_qf_Register_display' : '_qf_Main_display';
638 $returnURL = CRM_Utils_System::url($url,
639 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
640 TRUE, NULL, FALSE
641 );
642
643 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
644 if (!empty($params['is_recur'])) {
645 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
646 }
647
648 $cancelURL = CRM_Utils_System::url(
649 $url,
650 $cancelUrlString,
651 TRUE, NULL, FALSE
652 );
653
654 // ensure that the returnURL is absolute.
655 if (substr($returnURL, 0, 4) != 'http') {
656 $fixUrl = CRM_Utils_System::url("civicrm/admin/setting/url", '&reset=1');
657 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)));
658 }
659
660 $paypalParams = array(
661 'business' => $this->_paymentProcessor['user_name'],
662 'notify_url' => $notifyURL,
663 'item_name' => $params['item_name'],
664 'quantity' => 1,
665 'undefined_quantity' => 0,
666 'cancel_return' => $cancelURL,
667 'no_note' => 1,
668 'no_shipping' => 1,
669 'return' => $returnURL,
670 'rm' => 2,
671 'currency_code' => $params['currencyID'],
672 'invoice' => $params['invoiceID'],
673 'lc' => substr($config->lcMessages, -2),
674 'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8',
675 'custom' => CRM_Utils_Array::value('accountingCode', $params),
676 'bn' => 'CiviCRM_SP',
677 );
678
679 // add name and address if available, CRM-3130
680 $otherVars = array(
681 'first_name' => 'first_name',
682 'last_name' => 'last_name',
683 'street_address' => 'address1',
684 'country' => 'country',
685 'preferred_language' => 'lc',
686 'city' => 'city',
687 'state_province' => 'state',
688 'postal_code' => 'zip',
689 'email' => 'email',
690 );
691
692 foreach (array_keys($params) as $p) {
693 // get the base name without the location type suffixed to it
694 $parts = explode('-', $p);
695 $name = count($parts) > 1 ? $parts[0] : $p;
696 if (isset($otherVars[$name])) {
697 $value = $params[$p];
698 if ($value) {
699 if ($name == 'state_province') {
700 $stateName = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
701 $value = $stateName;
702 }
703 if ($name == 'country') {
704 $countryName = CRM_Core_PseudoConstant::countryIsoCode($value);
705 $value = $countryName;
706 }
707 // ensure value is not an array
708 // CRM-4174
709 if (!is_array($value)) {
710 $paypalParams[$otherVars[$name]] = $value;
711 }
712 }
713 }
714 }
715
716 // if recurring donations, add a few more items
717 if (!empty($params['is_recur'])) {
718 if ($params['contributionRecurID']) {
719 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
720 $paypalParams['notify_url'] = $notifyURL;
721 }
722 else {
723 CRM_Core_Error::fatal(ts('Recurring contribution, but no database id'));
724 }
725
726 $paypalParams += array(
727 'cmd' => '_xclick-subscriptions',
728 'a3' => $params['amount'],
729 'p3' => $params['frequency_interval'],
730 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
731 'src' => 1,
732 'sra' => 1,
733 'srt' => CRM_Utils_Array::value('installments', $params),
734 'no_note' => 1,
735 'modify' => 0,
736 );
737 }
738 else {
739 $paypalParams += array(
740 'cmd' => '_xclick',
741 'amount' => $params['amount'],
742 );
743 }
744
745 // Allow further manipulation of the arguments via custom hooks ..
746 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $paypalParams);
747
748 $uri = '';
749 foreach ($paypalParams as $key => $value) {
750 if ($value === NULL) {
751 continue;
752 }
753
754 $value = urlencode($value);
755 if ($key == 'return' ||
756 $key == 'cancel_return' ||
757 $key == 'notify_url'
758 ) {
759 $value = str_replace('%2F', '/', $value);
760 }
761 $uri .= "&{$key}={$value}";
762 }
763
764 $uri = substr($uri, 1);
765 $url = $this->_paymentProcessor['url_site'];
766 $sub = empty($params['is_recur']) ? 'cgi-bin/webscr' : 'subscriptions';
767 $paypalURL = "{$url}{$sub}?$uri";
768
769 CRM_Utils_System::redirect($paypalURL);
770 }
771
772 /**
773 * Hash_call: Function to perform the API call to PayPal using API signature
774 * @methodName is name of API method.
775 * @nvpStr is nvp string.
776 * returns an associtive array containing the response from the server.
777 */
778 public function invokeAPI($args, $url = NULL) {
779
780 if ($url === NULL) {
781 if (empty($this->_paymentProcessor['url_api'])) {
782 CRM_Core_Error::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
783 }
784
785 $url = $this->_paymentProcessor['url_api'] . 'nvp';
786 }
787
788 if (!function_exists('curl_init')) {
789 CRM_Core_Error::fatal("curl functions NOT available.");
790 }
791
792 //setting the curl parameters.
793 $ch = curl_init();
794 curl_setopt($ch, CURLOPT_URL, $url);
795 curl_setopt($ch, CURLOPT_VERBOSE, 1);
796
797 //turning off the server and peer verification(TrustManager Concept).
798 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
799 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL') ? 2 : 0);
800
801 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
802 curl_setopt($ch, CURLOPT_POST, 1);
803
804 $p = array();
805 foreach ($args as $n => $v) {
806 $p[] = "$n=" . urlencode($v);
807 }
808
809 //NVPRequest for submitting to server
810 $nvpreq = implode('&', $p);
811
812 //setting the nvpreq as POST FIELD to curl
813 curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
814
815 //getting response from server
816 $response = curl_exec($ch);
817
818 //converting NVPResponse to an Associative Array
819 $result = self::deformat($response);
820
821 if (curl_errno($ch)) {
822 $e = CRM_Core_Error::singleton();
823 $e->push(curl_errno($ch),
824 0, NULL,
825 curl_error($ch)
826 );
827 return $e;
828 }
829 else {
830 curl_close($ch);
831 }
832
833 if (strtolower($result['ack']) != 'success' &&
834 strtolower($result['ack']) != 'successwithwarning'
835 ) {
836 $e = CRM_Core_Error::singleton();
837 $e->push($result['l_errorcode0'],
838 0, NULL,
839 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
840 );
841 return $e;
842 }
843
844 return $result;
845 }
846
847 /**
848 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
849 * It is usefull to search for a particular key and displaying arrays.
850 * @nvpstr is NVPString.
851 * @nvpArray is Associative Array.
852 */
853 public static function deformat($str) {
854 $result = array();
855
856 while (strlen($str)) {
857 // postion of key
858 $keyPos = strpos($str, '=');
859
860 // position of value
861 $valPos = strpos($str, '&') ? strpos($str, '&') : strlen($str);
862
863 /*getting the Key and Value values and storing in a Associative Array*/
864
865 $key = substr($str, 0, $keyPos);
866 $val = substr($str, $keyPos + 1, $valPos - $keyPos - 1);
867
868 //decoding the respose
869 $result[strtolower(urldecode($key))] = urldecode($val);
870 $str = substr($str, $valPos + 1, strlen($str));
871 }
872
873 return $result;
874 }
875
876 }