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