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