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