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