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