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