d0f66b54af0cdf5c151aae9334ce70629f988f68
[civicrm-core.git] / CRM / Core / Payment / PayPalImpl.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 *
34 */
35 class 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 */
46 static private $_singleton = NULL;
47
48 /**
49 * Constructor.
50 *
51 * @param string $mode
52 * The mode of operation: live or test.
53 *
54 * @param $paymentProcessor
55 *
56 * @return \CRM_Core_Payment_PayPalImpl
57 */
58 public 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 }
73
74 /**
75 * Are back office payments supported - e.g paypal standard won't permit you to enter a credit card associated with someone else's login
76 * @return bool
77 */
78 protected function supportsBackOffice() {
79 if ($this->_processorName == ts('PayPal Pro')) {
80 return TRUE;
81 }
82 return FALSE;
83 }
84
85 /**
86 * Does this processor support pre-approval.
87 *
88 * This would generally look like a redirect to enter credentials which can then be used in a later payment call.
89 *
90 * Currently Paypal express supports this, with a redirect to paypal after the 'Main' form is submitted in the
91 * contribution page. This token can then be processed at the confirm phase. Although this flow 'looks' like the
92 * 'notify' flow a key difference is that in the notify flow they don't have to return but in this flow they do.
93 *
94 * @return bool
95 */
96 protected function supportsPreApproval() {
97 if ($this->_processorName == ts('PayPal_Express')) {
98 return TRUE;
99 }
100 return FALSE;
101 }
102
103 /**
104 * Opportunity for the payment processor to override the entire form build.
105 *
106 * @param CRM_Core_Form $form
107 *
108 * @return bool
109 * Should form building stop at this point?
110 */
111 public function buildForm(&$form) {
112 if ($this->_processorName == 'PayPal Express' || $this->_processorName == 'PayPal Pro') {
113 $this->addPaypalExpressCode($form);
114 if ($this->_processorName == 'PayPal Express') {
115 CRM_Core_Region::instance('billing-block-post')->add(array(
116 'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
117 'name' => 'paypal_express',
118 ));
119 }
120 if ($this->_processorName == 'PayPal Pro') {
121 CRM_Core_Region::instance('billing-block-pre')->add(array(
122 'template' => 'CRM/Financial/Form/PaypalPro.tpl',
123 ));
124 }
125 }
126 return FALSE;
127 }
128
129 /**
130 * Billing mode button is basically synonymous with paypal express - this is probably a good example of 'odds & sods' code we
131 * need to find a way for the payment processor to assign. A tricky aspect is that the payment processor may need to set the order
132 *
133 * @param $form
134 */
135 protected function addPaypalExpressCode(&$form) {
136 if (empty($form->isBackOffice)) {
137 $form->_expressButtonName = $form->getButtonName('upload', 'express');
138 $form->assign('expressButtonName', $form->_expressButtonName);
139 $form->add(
140 'image',
141 $form->_expressButtonName,
142 $this->_paymentProcessor['url_button'],
143 array('class' => 'crm-form-submit')
144 );
145 }
146 }
147
148 /**
149 * Express checkout code. Check PayPal documentation for more information
150 *
151 * @param array $params
152 * Assoc array of input parameters for this transaction.
153 *
154 * @return array
155 * the result in an nice formatted array (or an error object)
156 */
157 protected function setExpressCheckOut(&$params) {
158 $args = array();
159
160 $this->initialize($args, 'SetExpressCheckout');
161
162 $args['paymentAction'] = 'Sale';
163 $args['amt'] = $params['amount'];
164 $args['currencyCode'] = $params['currencyID'];
165 $args['desc'] = CRM_Utils_Array::value('description', $params);
166 $args['invnum'] = $params['invoiceID'];
167 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
168 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
169 $args['version'] = '56.0';
170
171 //LCD if recurring, collect additional data and set some values
172 if (!empty($params['is_recur'])) {
173 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
174 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
175 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
176 $args['L_PAYMENTTYPE0'] = 'Any';
177 }
178
179 // Allow further manipulation of the arguments via custom hooks ..
180 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
181
182 $result = $this->invokeAPI($args);
183
184 if (is_a($result, 'CRM_Core_Error')) {
185 return $result;
186 }
187
188 /* Success */
189
190 return $result['token'];
191 }
192
193 /**
194 * Get any details that may be available to the payment processor due to an approval process having happened.
195 *
196 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
197 * result.
198 *
199 * @param array $storedDetails
200 *
201 * @return array
202 */
203 public function getPreApprovalDetails($storedDetails) {
204 return $this->getExpressCheckoutDetails($storedDetails['token']);
205 }
206
207 /**
208 * Get details from paypal. Check PayPal documentation for more information
209 *
210 * @param string $token
211 * The key associated with this transaction.
212 *
213 * @return array
214 * the result in an nice formatted array (or an error object)
215 */
216 public function getExpressCheckoutDetails($token) {
217 $args = array();
218
219 $this->initialize($args, 'GetExpressCheckoutDetails');
220 $args['token'] = $token;
221 // LCD
222 $args['method'] = 'GetExpressCheckoutDetails';
223
224 $result = $this->invokeAPI($args);
225
226 if (is_a($result, 'CRM_Core_Error')) {
227 return $result;
228 }
229
230 /* Success */
231
232 $params = array();
233 $params['token'] = $result['token'];
234 $params['payer_id'] = $result['payerid'];
235 $params['payer_status'] = $result['payerstatus'];
236 $params['first_name'] = $result['firstname'];
237 $params['middle_name'] = CRM_Utils_Array::value('middlename', $result);
238 $params['last_name'] = $result['lastname'];
239 $params['street_address'] = $result['shiptostreet'];
240 $params['supplemental_address_1'] = CRM_Utils_Array::value('shiptostreet2', $result);
241 $params['city'] = $result['shiptocity'];
242 $params['state_province'] = $result['shiptostate'];
243 $params['postal_code'] = $result['shiptozip'];
244 $params['country'] = $result['shiptocountrycode'];
245
246 return $params;
247 }
248
249 /**
250 * Do the express checkout at paypal. Check PayPal documentation for more information
251 *
252 * @param array $params
253 *
254 * @internal param string $token the key associated with this transaction
255 *
256 * @return array
257 * the result in an nice formatted array (or an error object)
258 */
259 public function doExpressCheckout(&$params) {
260 $args = array();
261
262 $this->initialize($args, 'DoExpressCheckoutPayment');
263 $args['token'] = $params['token'];
264 $args['paymentAction'] = 'Sale';
265 $args['amt'] = $params['amount'];
266 $args['currencyCode'] = $params['currencyID'];
267 $args['payerID'] = $params['payer_id'];
268 $args['invnum'] = $params['invoiceID'];
269 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
270 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
271 $args['desc'] = $params['description'];
272
273 // add CiviCRM BN code
274 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
275
276 $result = $this->invokeAPI($args);
277
278 if (is_a($result, 'CRM_Core_Error')) {
279 return $result;
280 }
281
282 /* Success */
283
284 $params['trxn_id'] = $result['transactionid'];
285 $params['gross_amount'] = $result['amt'];
286 $params['fee_amount'] = $result['feeamt'];
287 $params['net_amount'] = CRM_Utils_Array::value('settleamt', $result);
288 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
289 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
290 }
291 $params['payment_status'] = $result['paymentstatus'];
292 $params['pending_reason'] = $result['pendingreason'];
293
294 return $params;
295 }
296
297 //LCD add new function for handling recurring payments for PayPal Express
298 /**
299 * @param array $params
300 *
301 * @return mixed
302 */
303 public function createRecurringPayments(&$params) {
304 $args = array();
305
306 $this->initialize($args, 'CreateRecurringPaymentsProfile');
307
308 $start_time = strtotime(date('m/d/Y'));
309 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
310
311 $args['token'] = $params['token'];
312 $args['paymentAction'] = 'Sale';
313 $args['amt'] = $params['amount'];
314 $args['currencyCode'] = $params['currencyID'];
315 $args['payerID'] = $params['payer_id'];
316 $args['invnum'] = $params['invoiceID'];
317 $args['returnURL'] = $params['returnURL'];
318 $args['cancelURL'] = $params['cancelURL'];
319 $args['profilestartdate'] = $start_date;
320 $args['method'] = 'CreateRecurringPaymentsProfile';
321 $args['billingfrequency'] = $params['frequency_interval'];
322 $args['billingperiod'] = ucwords($params['frequency_unit']);
323 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
324 //$args['desc'] = 'Recurring Contribution';
325 $args['totalbillingcycles'] = $params['installments'];
326 $args['version'] = '56.0';
327 $args['profilereference'] = "i={$params['invoiceID']}" .
328 "&m=$component" .
329 "&c={$params['contactID']}" .
330 "&r={$params['contributionRecurID']}" .
331 "&b={$params['contributionID']}" .
332 "&p={$params['contributionPageID']}";
333
334 // add CiviCRM BN code
335 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
336
337 $result = $this->invokeAPI($args);
338
339 if (is_a($result, 'CRM_Core_Error')) {
340 return $result;
341 }
342
343 /* Success */
344 $params['trxn_id'] = $result['transactionid'];
345 $params['gross_amount'] = $result['amt'];
346 $params['fee_amount'] = $result['feeamt'];
347 $params['net_amount'] = $result['settleamt'];
348 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
349 $params['net_amount'] = $params['gross_amount'] - $params['fee_amount'];
350 }
351 $params['payment_status'] = $result['paymentstatus'];
352 $params['pending_reason'] = $result['pendingreason'];
353
354 return $params;
355 }
356 //LCD end
357 /**
358 * @param $args
359 * @param $method
360 */
361 public function initialize(&$args, $method) {
362 $args['user'] = $this->_paymentProcessor['user_name'];
363 $args['pwd'] = $this->_paymentProcessor['password'];
364 $args['version'] = 3.0;
365 $args['signature'] = $this->_paymentProcessor['signature'];
366 $args['subject'] = CRM_Utils_Array::value('subject', $this->_paymentProcessor);
367 $args['method'] = $method;
368 }
369
370 /**
371 * This function collects all the information from a web/api form and invokes
372 * the relevant payment processor specific functions to perform the transaction
373 *
374 * @param array $params
375 * Assoc array of input parameters for this transaction.
376 *
377 * @param string $component
378 * @return array
379 * the result in an nice formatted array (or an error object)
380 */
381 public function doDirectPayment(&$params, $component = 'contribute') {
382 $args = array();
383
384 $this->initialize($args, 'DoDirectPayment');
385
386 $args['paymentAction'] = 'Sale';
387 $args['amt'] = $params['amount'];
388 $args['currencyCode'] = $params['currencyID'];
389 $args['invnum'] = $params['invoiceID'];
390 $args['ipaddress'] = $params['ip_address'];
391 $args['creditCardType'] = $params['credit_card_type'];
392 $args['acct'] = $params['credit_card_number'];
393 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
394 $args['cvv2'] = $params['cvv2'];
395 $args['firstName'] = $params['first_name'];
396 $args['lastName'] = $params['last_name'];
397 $args['email'] = CRM_Utils_Array::value('email', $params);
398 $args['street'] = $params['street_address'];
399 $args['city'] = $params['city'];
400 $args['state'] = $params['state_province'];
401 $args['countryCode'] = $params['country'];
402 $args['zip'] = $params['postal_code'];
403 $args['desc'] = substr(CRM_Utils_Array::value('description', $params), 0, 127);
404 $args['custom'] = CRM_Utils_Array::value('accountingCode', $params);
405
406 // add CiviCRM BN code
407 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
408
409 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
410 $start_time = strtotime(date('m/d/Y'));
411 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
412
413 $args['PaymentAction'] = 'Sale';
414 $args['billingperiod'] = ucwords($params['frequency_unit']);
415 $args['billingfrequency'] = $params['frequency_interval'];
416 $args['method'] = "CreateRecurringPaymentsProfile";
417 $args['profilestartdate'] = $start_date;
418 $args['desc'] = "" .
419 $params['description'] . ": " .
420 $params['amount'] . " Per " .
421 $params['frequency_interval'] . " " .
422 $params['frequency_unit'];
423 $args['amt'] = $params['amount'];
424 $args['totalbillingcycles'] = $params['installments'];
425 $args['version'] = 56.0;
426 $args['PROFILEREFERENCE'] = "" .
427 "i=" . $params['invoiceID'] . "&m=" . $component .
428 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
429 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
430 }
431
432 // Allow further manipulation of the arguments via custom hooks ..
433 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
434
435 $result = $this->invokeAPI($args);
436
437 //WAG
438 if (is_a($result, 'CRM_Core_Error')) {
439 return $result;
440 }
441
442 $params['recurr_profile_id'] = NULL;
443
444 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
445 $params['recurr_profile_id'] = $result['profileid'];
446 }
447
448 /* Success */
449
450 $params['trxn_id'] = CRM_Utils_Array::value('transactionid', $result);
451 $params['gross_amount'] = CRM_Utils_Array::value('amt', $result);
452 return $params;
453 }
454
455 /**
456 * This function checks to see if we have the right config values.
457 *
458 * @return string
459 * the error message if any
460 */
461 public function checkConfig() {
462 $error = array();
463 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
464
465 if ($this->_paymentProcessor['payment_processor_type_id'] != CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
466 if (empty($this->_paymentProcessor['signature'])) {
467 $error[] = ts('Signature is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
468 }
469
470 if (empty($this->_paymentProcessor['password'])) {
471 $error[] = ts('Password is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
472 }
473 }
474 if (!$this->_paymentProcessor['user_name']) {
475 $error[] = ts('User Name is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
476 }
477
478 if (!empty($error)) {
479 return implode('<p>', $error);
480 }
481 else {
482 return NULL;
483 }
484 }
485
486 /**
487 * @return null|string
488 */
489 public function cancelSubscriptionURL() {
490 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Standard') {
491 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']);
492 }
493 else {
494 return NULL;
495 }
496 }
497
498 /**
499 * Check whether a method is present ( & supported ) by the payment processor object.
500 *
501 * @param string $method
502 * Method to check for.
503 *
504 * @return bool
505 */
506 public function isSupported($method = 'cancelSubscription') {
507 if ($this->_paymentProcessor['payment_processor_type'] != 'PayPal') {
508 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
509 // by standard or express.
510 return FALSE;
511 }
512 return parent::isSupported($method);
513 }
514
515 /**
516 * Paypal express replaces the submit button with it's own.
517 *
518 * @return bool
519 * Should the form button by suppressed?
520 */
521 public function isSuppressSubmitButtons() {
522 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express') {
523 return TRUE;
524 }
525 return FALSE;
526 }
527
528 /**
529 * @param string $message
530 * @param array $params
531 *
532 * @return array|bool|object
533 */
534 public function cancelSubscription(&$message = '', $params = array()) {
535 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
536 $args = array();
537 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
538
539 $args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params);
540 $args['ACTION'] = 'Cancel';
541 $args['NOTE'] = CRM_Utils_Array::value('reason', $params);
542
543 $result = $this->invokeAPI($args);
544 if (is_a($result, 'CRM_Core_Error')) {
545 return $result;
546 }
547 $message = "{$result['ack']}: profileid={$result['profileid']}";
548 return TRUE;
549 }
550 return FALSE;
551 }
552
553 /**
554 * Process incoming notification.
555 *
556 * This is only supported for paypal pro at the moment & no specific plans to add this path to core
557 * for paypal standard as the goal must be to separate the 2.
558 *
559 * We don't need to handle paypal standard using this path as there has never been any historic support
560 * for paypal standard to call civicrm/payment/ipn as a path.
561 */
562 static public function handlePaymentNotification() {
563 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($_REQUEST);
564 $paypalIPN->main();
565 }
566
567 /**
568 * @param string $message
569 * @param array $params
570 *
571 * @return array|bool|object
572 */
573 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
574 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
575 $config = CRM_Core_Config::singleton();
576 $args = array();
577 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
578
579 $args['PROFILEID'] = $params['subscriptionId'];
580 $args['AMT'] = $params['amount'];
581 $args['CURRENCYCODE'] = $config->defaultCurrency;
582 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
583 $args['ACCT'] = $params['credit_card_number'];
584 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
585 $args['CVV2'] = $params['cvv2'];
586
587 $args['FIRSTNAME'] = $params['first_name'];
588 $args['LASTNAME'] = $params['last_name'];
589 $args['STREET'] = $params['street_address'];
590 $args['CITY'] = $params['city'];
591 $args['STATE'] = $params['state_province'];
592 $args['COUNTRYCODE'] = $params['postal_code'];
593 $args['ZIP'] = $params['country'];
594
595 $result = $this->invokeAPI($args);
596 if (is_a($result, 'CRM_Core_Error')) {
597 return $result;
598 }
599 $message = "{$result['ack']}: profileid={$result['profileid']}";
600 return TRUE;
601 }
602 return FALSE;
603 }
604
605 /**
606 * @param string $message
607 * @param array $params
608 *
609 * @return array|bool|object
610 */
611 public function changeSubscriptionAmount(&$message = '', $params = array()) {
612 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
613 $config = CRM_Core_Config::singleton();
614 $args = array();
615 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
616
617 $args['PROFILEID'] = $params['subscriptionId'];
618 $args['AMT'] = $params['amount'];
619 $args['CURRENCYCODE'] = $config->defaultCurrency;
620 $args['BILLINGFREQUENCY'] = $params['installments'];
621
622 $result = $this->invokeAPI($args);
623 CRM_Core_Error::debug_var('$result', $result);
624 if (is_a($result, 'CRM_Core_Error')) {
625 return $result;
626 }
627 $message = "{$result['ack']}: profileid={$result['profileid']}";
628 return TRUE;
629 }
630 return FALSE;
631 }
632
633 /**
634 * Function to action pre-approval if supported
635 *
636 * @param array $params
637 * Parameters from the form
638 *
639 * @return array
640 * - pre_approval_parameters (this will be stored on the calling form & available later)
641 * - redirect_url (if set the browser will be redirected to this.
642 */
643 public function doPreApproval(&$params) {
644 $token = $this->setExpressCheckOut($params);
645 return array(
646 'pre_approval_parameters' => array('token' => $token),
647 'redirect_url' => $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
648 );
649 }
650
651 /**
652 * @param array $params
653 * @param string $component
654 *
655 * @throws Exception
656 */
657 public function doTransferCheckout(&$params, $component = 'contribute') {
658 $config = CRM_Core_Config::singleton();
659
660 if ($component != 'contribute' && $component != 'event') {
661 CRM_Core_Error::fatal(ts('Component is invalid'));
662 }
663
664 $notifyURL = $config->userFrameworkResourceURL . "extern/ipn.php?reset=1&contactID={$params['contactID']}" . "&contributionID={$params['contributionID']}" . "&module={$component}";
665
666 if ($component == 'event') {
667 $notifyURL .= "&eventID={$params['eventID']}&participantID={$params['participantID']}";
668 }
669 else {
670 $membershipID = CRM_Utils_Array::value('membershipID', $params);
671 if ($membershipID) {
672 $notifyURL .= "&membershipID=$membershipID";
673 }
674 $relatedContactID = CRM_Utils_Array::value('related_contact', $params);
675 if ($relatedContactID) {
676 $notifyURL .= "&relatedContactID=$relatedContactID";
677
678 $onBehalfDupeAlert = CRM_Utils_Array::value('onbehalf_dupe_alert', $params);
679 if ($onBehalfDupeAlert) {
680 $notifyURL .= "&onBehalfDupeAlert=$onBehalfDupeAlert";
681 }
682 }
683 }
684
685 $url = ($component == 'event') ? 'civicrm/event/register' : 'civicrm/contribute/transact';
686 $cancel = ($component == 'event') ? '_qf_Register_display' : '_qf_Main_display';
687 $returnURL = CRM_Utils_System::url($url,
688 "_qf_ThankYou_display=1&qfKey={$params['qfKey']}",
689 TRUE, NULL, FALSE
690 );
691
692 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
693 if (!empty($params['is_recur'])) {
694 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
695 }
696
697 $cancelURL = CRM_Utils_System::url(
698 $url,
699 $cancelUrlString,
700 TRUE, NULL, FALSE
701 );
702
703 // ensure that the returnURL is absolute.
704 if (substr($returnURL, 0, 4) != 'http') {
705 $fixUrl = CRM_Utils_System::url("civicrm/admin/setting/url", '&reset=1');
706 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)));
707 }
708
709 $paypalParams = array(
710 'business' => $this->_paymentProcessor['user_name'],
711 'notify_url' => $notifyURL,
712 'item_name' => $params['item_name'],
713 'quantity' => 1,
714 'undefined_quantity' => 0,
715 'cancel_return' => $cancelURL,
716 'no_note' => 1,
717 'no_shipping' => 1,
718 'return' => $returnURL,
719 'rm' => 2,
720 'currency_code' => $params['currencyID'],
721 'invoice' => $params['invoiceID'],
722 'lc' => substr($config->lcMessages, -2),
723 'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8',
724 'custom' => CRM_Utils_Array::value('accountingCode', $params),
725 'bn' => 'CiviCRM_SP',
726 );
727
728 // add name and address if available, CRM-3130
729 $otherVars = array(
730 'first_name' => 'first_name',
731 'last_name' => 'last_name',
732 'street_address' => 'address1',
733 'country' => 'country',
734 'preferred_language' => 'lc',
735 'city' => 'city',
736 'state_province' => 'state',
737 'postal_code' => 'zip',
738 'email' => 'email',
739 );
740
741 foreach (array_keys($params) as $p) {
742 // get the base name without the location type suffixed to it
743 $parts = explode('-', $p);
744 $name = count($parts) > 1 ? $parts[0] : $p;
745 if (isset($otherVars[$name])) {
746 $value = $params[$p];
747 if ($value) {
748 if ($name == 'state_province') {
749 $stateName = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
750 $value = $stateName;
751 }
752 if ($name == 'country') {
753 $countryName = CRM_Core_PseudoConstant::countryIsoCode($value);
754 $value = $countryName;
755 }
756 // ensure value is not an array
757 // CRM-4174
758 if (!is_array($value)) {
759 $paypalParams[$otherVars[$name]] = $value;
760 }
761 }
762 }
763 }
764
765 // if recurring donations, add a few more items
766 if (!empty($params['is_recur'])) {
767 if ($params['contributionRecurID']) {
768 $notifyURL .= "&contributionRecurID={$params['contributionRecurID']}&contributionPageID={$params['contributionPageID']}";
769 $paypalParams['notify_url'] = $notifyURL;
770 }
771 else {
772 CRM_Core_Error::fatal(ts('Recurring contribution, but no database id'));
773 }
774
775 $paypalParams += array(
776 'cmd' => '_xclick-subscriptions',
777 'a3' => $params['amount'],
778 'p3' => $params['frequency_interval'],
779 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
780 'src' => 1,
781 'sra' => 1,
782 'srt' => CRM_Utils_Array::value('installments', $params),
783 'no_note' => 1,
784 'modify' => 0,
785 );
786 }
787 else {
788 $paypalParams += array(
789 'cmd' => '_xclick',
790 'amount' => $params['amount'],
791 );
792 }
793
794 // Allow further manipulation of the arguments via custom hooks ..
795 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $paypalParams);
796
797 $uri = '';
798 foreach ($paypalParams as $key => $value) {
799 if ($value === NULL) {
800 continue;
801 }
802
803 $value = urlencode($value);
804 if ($key == 'return' ||
805 $key == 'cancel_return' ||
806 $key == 'notify_url'
807 ) {
808 $value = str_replace('%2F', '/', $value);
809 }
810 $uri .= "&{$key}={$value}";
811 }
812
813 $uri = substr($uri, 1);
814 $url = $this->_paymentProcessor['url_site'];
815 $sub = empty($params['is_recur']) ? 'cgi-bin/webscr' : 'subscriptions';
816 $paypalURL = "{$url}{$sub}?$uri";
817
818 CRM_Utils_System::redirect($paypalURL);
819 }
820
821 /**
822 * Hash_call: Function to perform the API call to PayPal using API signature
823 * @methodName is name of API method.
824 * @nvpStr is nvp string.
825 * returns an associtive array containing the response from the server.
826 */
827 public function invokeAPI($args, $url = NULL) {
828
829 if ($url === NULL) {
830 if (empty($this->_paymentProcessor['url_api'])) {
831 CRM_Core_Error::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
832 }
833
834 $url = $this->_paymentProcessor['url_api'] . 'nvp';
835 }
836
837 if (!function_exists('curl_init')) {
838 CRM_Core_Error::fatal("curl functions NOT available.");
839 }
840
841 //setting the curl parameters.
842 $ch = curl_init();
843 curl_setopt($ch, CURLOPT_URL, $url);
844 curl_setopt($ch, CURLOPT_VERBOSE, 1);
845
846 //turning off the server and peer verification(TrustManager Concept).
847 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
848 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL') ? 2 : 0);
849
850 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
851 curl_setopt($ch, CURLOPT_POST, 1);
852
853 $p = array();
854 foreach ($args as $n => $v) {
855 $p[] = "$n=" . urlencode($v);
856 }
857
858 //NVPRequest for submitting to server
859 $nvpreq = implode('&', $p);
860
861 //setting the nvpreq as POST FIELD to curl
862 curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
863
864 //getting response from server
865 $response = curl_exec($ch);
866
867 //converting NVPResponse to an Associative Array
868 $result = self::deformat($response);
869
870 if (curl_errno($ch)) {
871 $e = CRM_Core_Error::singleton();
872 $e->push(curl_errno($ch),
873 0, NULL,
874 curl_error($ch)
875 );
876 return $e;
877 }
878 else {
879 curl_close($ch);
880 }
881
882 if (strtolower($result['ack']) != 'success' &&
883 strtolower($result['ack']) != 'successwithwarning'
884 ) {
885 $e = CRM_Core_Error::singleton();
886 $e->push($result['l_errorcode0'],
887 0, NULL,
888 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
889 );
890 return $e;
891 }
892
893 return $result;
894 }
895
896 /**
897 * This function will take NVPString and convert it to an Associative Array and it will decode the response.
898 * It is useful to search for a particular key and displaying arrays.
899 * @nvpstr is NVPString.
900 * @nvpArray is Associative Array.
901 */
902 public static function deformat($str) {
903 $result = array();
904
905 while (strlen($str)) {
906 // position of key
907 $keyPos = strpos($str, '=');
908
909 // position of value
910 $valPos = strpos($str, '&') ? strpos($str, '&') : strlen($str);
911
912 /*getting the Key and Value values and storing in a Associative Array*/
913
914 $key = substr($str, 0, $keyPos);
915 $val = substr($str, $keyPos + 1, $valPos - $keyPos - 1);
916
917 //decoding the respose
918 $result[strtolower(urldecode($key))] = urldecode($val);
919 $str = substr($str, $valPos + 1, strlen($str));
920 }
921
922 return $result;
923 }
924
925 }