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