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