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