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