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