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