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