Comment fixes
[civicrm-core.git] / CRM / Core / Payment / PayPalImpl.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035 27
ec022878 28use Civi\Payment\Exception\PaymentProcessorException;
29
6a488035
TO
30/**
31 *
32 * @package CRM
0f03f337 33 * @copyright CiviCRM LLC (c) 2004-2017
5fb28746
EM
34 */
35
36/**
37 * Class CRM_Core_Payment_PayPalImpl for paypal pro, paypal standard & paypal express.
6a488035
TO
38 */
39class CRM_Core_Payment_PayPalImpl extends CRM_Core_Payment {
7da04cde 40 const CHARSET = 'iso-8859-1';
6a488035
TO
41
42 protected $_mode = NULL;
43
6a488035 44 /**
fe482240 45 * Constructor.
6a488035 46 *
6a0b768e
TO
47 * @param string $mode
48 * The mode of operation: live or test.
6a488035 49 *
e58c1c1a 50 * @param CRM_Core_Payment $paymentProcessor
77b97be7
EM
51 *
52 * @return \CRM_Core_Payment_PayPalImpl
6a488035 53 */
00be9182 54 public function __construct($mode, &$paymentProcessor) {
6a488035
TO
55 $this->_mode = $mode;
56 $this->_paymentProcessor = $paymentProcessor;
57 $this->_processorName = ts('PayPal Pro');
2aa397bc 58 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
6a488035
TO
59
60 if ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
61 $this->_processorName = ts('PayPal Standard');
62 return;
63 }
64 elseif ($this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('PayPal_Express', $paymentProcessorType)) {
65 $this->_processorName = ts('PayPal Express');
66 }
67
6a488035
TO
68 }
69
fbcb6fba 70 /**
e58c1c1a 71 * Are back office payments supported.
72 *
73 * E.g paypal standard won't permit you to enter a credit card associated
74 * with someone else's login.
75 *
fbcb6fba
EM
76 * @return bool
77 */
d8ce0d68 78 protected function supportsBackOffice() {
fbcb6fba
EM
79 if ($this->_processorName == ts('PayPal Pro')) {
80 return TRUE;
81 }
82 return FALSE;
83 }
353ffa53 84
3910048c
EM
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() {
ec022878 97 if ($this->_processorName == ts('PayPal Express') || $this->_processorName == ts('PayPal Pro')) {
3910048c
EM
98 return TRUE;
99 }
100 return FALSE;
101 }
102
dbbd55dc
EM
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);
31d31a05
EM
114 if ($this->_processorName == 'PayPal Express') {
115 CRM_Core_Region::instance('billing-block-post')->add(array(
116 'template' => 'CRM/Financial/Form/PaypalExpress.tpl',
aefd7f6b 117 'name' => 'paypal_express',
31d31a05
EM
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 }
dbbd55dc
EM
125 }
126 return FALSE;
127 }
128
129 /**
e58c1c1a 130 * Billing mode button is basically synonymous with paypal express.
131 *
132 * This is probably a good example of 'odds & sods' code we
133 * need to find a way for the payment processor to assign.
134 *
135 * A tricky aspect is that the payment processor may need to set the order
dbbd55dc 136 *
416a7c99 137 * @param CRM_Core_Form $form
dbbd55dc 138 */
31d31a05 139 protected function addPaypalExpressCode(&$form) {
dbbd55dc
EM
140 if (empty($form->isBackOffice)) {
141 $form->_expressButtonName = $form->getButtonName('upload', 'express');
142 $form->assign('expressButtonName', $form->_expressButtonName);
143 $form->add(
144 'image',
145 $form->_expressButtonName,
31d31a05 146 $this->_paymentProcessor['url_button'],
dbbd55dc
EM
147 array('class' => 'crm-form-submit')
148 );
149 }
150 }
151
677fe56c
EM
152 /**
153 * Can recurring contributions be set against pledges.
154 *
155 * In practice all processors that use the baseIPN function to finish transactions or
156 * call the completetransaction api support this by looking up previous contributions in the
157 * series and, if there is a prior contribution against a pledge, and the pledge is not complete,
158 * adding the new payment to the pledge.
159 *
160 * However, only enabling for processors it has been tested against.
161 *
162 * @return bool
163 */
164 protected function supportsRecurContributionsForPledges() {
165 return TRUE;
166 }
167
8ccce14a 168 /**
169 * Default payment instrument validation.
170 *
171 * Implement the usual Luhn algorithm via a static function in the CRM_Core_Payment_Form if it's a credit card
172 * Not a static function, because I need to check for payment_type.
173 *
174 * @param array $values
175 * @param array $errors
176 */
177 public function validatePaymentInstrument($values, &$errors) {
1d292cf3 178 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal' && !$this->isPaypalExpress($values)) {
06051ca4 179 CRM_Core_Payment_Form::validateCreditCard($values, $errors, $this->_paymentProcessor['id']);
c319039f 180 CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $values, $errors);
8ccce14a 181 }
182 }
183
6a488035 184 /**
e58c1c1a 185 * Express checkout code.
186 *
187 * Check PayPal documentation for more information
6a488035 188 *
6a0b768e
TO
189 * @param array $params
190 * Assoc array of input parameters for this transaction.
6a488035 191 *
a6c01b45
CW
192 * @return array
193 * the result in an nice formatted array (or an error object)
dbb0d30b 194 * @throws \Civi\Payment\Exception\PaymentProcessorException
6a488035 195 */
3a80832a 196 protected function setExpressCheckOut(&$params) {
6a488035
TO
197 $args = array();
198
199 $this->initialize($args, 'SetExpressCheckout');
200
aefd7f6b 201 $args['paymentAction'] = 'Sale';
6a488035
TO
202 $args['amt'] = $params['amount'];
203 $args['currencyCode'] = $params['currencyID'];
4233eb14 204 $args['desc'] = CRM_Utils_Array::value('description', $params);
6a488035 205 $args['invnum'] = $params['invoiceID'];
aefd7f6b
EM
206 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
207 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
6a488035
TO
208 $args['version'] = '56.0';
209
210 //LCD if recurring, collect additional data and set some values
a7488080 211 if (!empty($params['is_recur'])) {
6a488035
TO
212 $args['L_BILLINGTYPE0'] = 'RecurringPayments';
213 //$args['L_BILLINGAGREEMENTDESCRIPTION0'] = 'Recurring Contribution';
214 $args['L_BILLINGAGREEMENTDESCRIPTION0'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
215 $args['L_PAYMENTTYPE0'] = 'Any';
216 }
217
218 // Allow further manipulation of the arguments via custom hooks ..
219 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
220
221 $result = $this->invokeAPI($args);
222
223 if (is_a($result, 'CRM_Core_Error')) {
abfb35ee 224 throw new PaymentProcessorException($result->message);
6a488035
TO
225 }
226
227 /* Success */
228
229 return $result['token'];
230 }
231
3105efd2
EM
232 /**
233 * Get any details that may be available to the payment processor due to an approval process having happened.
234 *
235 * In some cases the browser is redirected to enter details on a processor site. Some details may be available as a
236 * result.
237 *
238 * @param array $storedDetails
239 *
240 * @return array
241 */
242 public function getPreApprovalDetails($storedDetails) {
ec022878 243 return empty($storedDetails['token']) ? array() : $this->getExpressCheckoutDetails($storedDetails['token']);
3105efd2
EM
244 }
245
6a488035 246 /**
e58c1c1a 247 * Get details from paypal.
248 *
249 * Check PayPal documentation for more information
6a488035 250 *
6a0b768e
TO
251 * @param string $token
252 * The key associated with this transaction.
6a488035 253 *
a6c01b45
CW
254 * @return array
255 * the result in an nice formatted array (or an error object)
6a488035 256 */
00be9182 257 public function getExpressCheckoutDetails($token) {
6a488035
TO
258 $args = array();
259
260 $this->initialize($args, 'GetExpressCheckoutDetails');
261 $args['token'] = $token;
262 // LCD
263 $args['method'] = 'GetExpressCheckoutDetails';
264
265 $result = $this->invokeAPI($args);
266
267 if (is_a($result, 'CRM_Core_Error')) {
abfb35ee 268 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
6a488035
TO
269 }
270
271 /* Success */
933da5b5
EM
272 $fieldMap = array(
273 'token' => 'token',
274 'payer_status' => 'payerstatus',
275 'payer_id' => 'payerid',
276 'first_name' => 'firstname',
277 'middle_name' => 'middlename',
278 'last_name' => 'lastname',
279 'street_address' => 'shiptostreet',
280 'supplemental_address_1' => 'shiptostreet2',
281 'city' => 'shiptocity',
282 'postal_code' => 'shiptozip',
283 'state_province' => 'shiptostate',
284 'country' => 'shiptocountrycode',
285 );
286 return $this->mapPaypalParamsToCivicrmParams($fieldMap, $result);
6a488035
TO
287 }
288
289 /**
e58c1c1a 290 * Do the express checkout at paypal.
6a488035 291 *
e58c1c1a 292 * Check PayPal documentation for more information
da6b46f4 293 *
e58c1c1a 294 * @param array $params
6a488035 295 *
a6c01b45 296 * @return array
e58c1c1a 297 * The result in an nice formatted array.
298 *
299 * @throws \Civi\Payment\Exception\PaymentProcessorException
6a488035 300 */
00be9182 301 public function doExpressCheckout(&$params) {
f8453bef 302 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
5fb28746
EM
303 if (!empty($params['is_recur'])) {
304 return $this->createRecurringPayments($params);
305 }
6a488035
TO
306 $args = array();
307
308 $this->initialize($args, 'DoExpressCheckoutPayment');
6a488035 309 $args['token'] = $params['token'];
aefd7f6b 310 $args['paymentAction'] = 'Sale';
6a488035
TO
311 $args['amt'] = $params['amount'];
312 $args['currencyCode'] = $params['currencyID'];
313 $args['payerID'] = $params['payer_id'];
314 $args['invnum'] = $params['invoiceID'];
aefd7f6b
EM
315 $args['returnURL'] = $this->getReturnSuccessUrl($params['qfKey']);
316 $args['cancelURL'] = $this->getCancelUrl($params['qfKey'], NULL);
fc7063a4 317 $args['desc'] = $params['description'];
6a488035 318
ebf695c3 319 // add CiviCRM BN code
320 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
321
6a488035
TO
322 $result = $this->invokeAPI($args);
323
324 if (is_a($result, 'CRM_Core_Error')) {
f8453bef 325 throw new PaymentProcessorException(CRM_Core_Error::getMessages($result));
6a488035
TO
326 }
327
328 /* Success */
329
330 $params['trxn_id'] = $result['transactionid'];
331 $params['gross_amount'] = $result['amt'];
332 $params['fee_amount'] = $result['feeamt'];
4233eb14 333 $params['net_amount'] = CRM_Utils_Array::value('settleamt', $result);
6a488035 334 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
b26c99af 335 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
6a488035
TO
336 }
337 $params['payment_status'] = $result['paymentstatus'];
338 $params['pending_reason'] = $result['pendingreason'];
f8453bef 339 if (!empty($params['is_recur'])) {
340 // See comment block.
2dec2069 341 $params['payment_status_id'] = array_search('Pending', $statuses);
f8453bef 342 }
343 else {
2dec2069 344 $params['payment_status_id'] = array_search('Completed', $statuses);
f8453bef 345 }
6a488035
TO
346 return $params;
347 }
348
6c786a9b 349 /**
e58c1c1a 350 * Create recurring payments.
351 *
c490a46a 352 * @param array $params
6c786a9b
EM
353 *
354 * @return mixed
355 */
00be9182 356 public function createRecurringPayments(&$params) {
6a488035 357 $args = array();
933da5b5 358 // @todo this function is riddled with enotices - perhaps use $this->mapPaypalParamsToCivicrmParams($fieldMap, $result)
6a488035
TO
359 $this->initialize($args, 'CreateRecurringPaymentsProfile');
360
361 $start_time = strtotime(date('m/d/Y'));
362 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
363
364 $args['token'] = $params['token'];
aefd7f6b 365 $args['paymentAction'] = 'Sale';
6a488035
TO
366 $args['amt'] = $params['amount'];
367 $args['currencyCode'] = $params['currencyID'];
368 $args['payerID'] = $params['payer_id'];
369 $args['invnum'] = $params['invoiceID'];
370 $args['returnURL'] = $params['returnURL'];
371 $args['cancelURL'] = $params['cancelURL'];
372 $args['profilestartdate'] = $start_date;
373 $args['method'] = 'CreateRecurringPaymentsProfile';
374 $args['billingfrequency'] = $params['frequency_interval'];
375 $args['billingperiod'] = ucwords($params['frequency_unit']);
376 $args['desc'] = $params['amount'] . " Per " . $params['frequency_interval'] . " " . $params['frequency_unit'];
377 //$args['desc'] = 'Recurring Contribution';
378 $args['totalbillingcycles'] = $params['installments'];
379 $args['version'] = '56.0';
6c552737 380 $args['profilereference'] = "i={$params['invoiceID']}" .
933da5b5 381 "&m=" .
1ac462d0
DL
382 "&c={$params['contactID']}" .
383 "&r={$params['contributionRecurID']}" .
384 "&b={$params['contributionID']}" .
385 "&p={$params['contributionPageID']}";
6a488035 386
a3caf338 387 // add CiviCRM BN code
388 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
389
6a488035
TO
390 $result = $this->invokeAPI($args);
391
392 if (is_a($result, 'CRM_Core_Error')) {
393 return $result;
394 }
395
396 /* Success */
6a488035
TO
397 $params['trxn_id'] = $result['transactionid'];
398 $params['gross_amount'] = $result['amt'];
399 $params['fee_amount'] = $result['feeamt'];
400 $params['net_amount'] = $result['settleamt'];
401 if ($params['net_amount'] == 0 && $params['fee_amount'] != 0) {
b26c99af 402 $params['net_amount'] = number_format(($params['gross_amount'] - $params['fee_amount']), 2);
6a488035
TO
403 }
404 $params['payment_status'] = $result['paymentstatus'];
405 $params['pending_reason'] = $result['pendingreason'];
406
407 return $params;
408 }
e58c1c1a 409
6c786a9b 410 /**
e58c1c1a 411 * Initialise.
412 *
6c786a9b
EM
413 * @param $args
414 * @param $method
415 */
00be9182 416 public function initialize(&$args, $method) {
353ffa53
TO
417 $args['user'] = $this->_paymentProcessor['user_name'];
418 $args['pwd'] = $this->_paymentProcessor['password'];
419 $args['version'] = 3.0;
6a488035 420 $args['signature'] = $this->_paymentProcessor['signature'];
353ffa53
TO
421 $args['subject'] = CRM_Utils_Array::value('subject', $this->_paymentProcessor);
422 $args['method'] = $method;
6a488035 423 }
f8453bef 424
425 /**
426 * Process payment - this function wraps around both doTransferPayment and doDirectPayment.
427 *
428 * The function ensures an exception is thrown & moves some of this logic out of the form layer and makes the forms
429 * more agnostic.
430 *
431 * Payment processors should set payment_status_id. This function adds some historical defaults ie. the
432 * assumption that if a 'doDirectPayment' processors comes back it completed the transaction & in fact
433 * doTransferCheckout would not traditionally come back.
434 *
435 * doDirectPayment does not do an immediate payment for Authorize.net or Paypal so the default is assumed
436 * to be Pending.
437 *
438 * Once this function is fully rolled out then it will be preferred for processors to throw exceptions than to
439 * return Error objects
440 *
441 * @param array $params
442 *
443 * @param string $component
444 *
445 * @return array
446 * Result array
447 *
448 * @throws \Civi\Payment\Exception\PaymentProcessorException
449 */
450 public function doPayment(&$params, $component = 'contribute') {
e58c1c1a 451 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express'
c319039f 452 || ($this->_paymentProcessor['payment_processor_type'] == 'PayPal' && !empty($params['token']))
ec022878 453 ) {
e58c1c1a 454 $this->_component = $component;
455 return $this->doExpressCheckout($params);
456
f8453bef 457 }
e58c1c1a 458 return parent::doPayment($params, $component);
f8453bef 459 }
6a488035
TO
460
461 /**
462 * This function collects all the information from a web/api form and invokes
463 * the relevant payment processor specific functions to perform the transaction
464 *
6a0b768e
TO
465 * @param array $params
466 * Assoc array of input parameters for this transaction.
6a488035 467 *
da6b46f4 468 * @param string $component
a6c01b45
CW
469 * @return array
470 * the result in an nice formatted array (or an error object)
6a488035 471 */
00be9182 472 public function doDirectPayment(&$params, $component = 'contribute') {
6a488035
TO
473 $args = array();
474
475 $this->initialize($args, 'DoDirectPayment');
476
aefd7f6b 477 $args['paymentAction'] = 'Sale';
6a488035
TO
478 $args['amt'] = $params['amount'];
479 $args['currencyCode'] = $params['currencyID'];
480 $args['invnum'] = $params['invoiceID'];
481 $args['ipaddress'] = $params['ip_address'];
482 $args['creditCardType'] = $params['credit_card_type'];
483 $args['acct'] = $params['credit_card_number'];
484 $args['expDate'] = sprintf('%02d', $params['month']) . $params['year'];
485 $args['cvv2'] = $params['cvv2'];
486 $args['firstName'] = $params['first_name'];
487 $args['lastName'] = $params['last_name'];
488 $args['email'] = CRM_Utils_Array::value('email', $params);
489 $args['street'] = $params['street_address'];
490 $args['city'] = $params['city'];
491 $args['state'] = $params['state_province'];
492 $args['countryCode'] = $params['country'];
493 $args['zip'] = $params['postal_code'];
0ab1fbfb 494 $args['desc'] = substr(CRM_Utils_Array::value('description', $params), 0, 127);
6a488035
TO
495 $args['custom'] = CRM_Utils_Array::value('accountingCode', $params);
496
ebf695c3 497 // add CiviCRM BN code
498 $args['BUTTONSOURCE'] = 'CiviCRM_SP';
499
6a488035
TO
500 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
501 $start_time = strtotime(date('m/d/Y'));
502 $start_date = date('Y-m-d\T00:00:00\Z', $start_time);
503
504 $args['PaymentAction'] = 'Sale';
505 $args['billingperiod'] = ucwords($params['frequency_unit']);
506 $args['billingfrequency'] = $params['frequency_interval'];
507 $args['method'] = "CreateRecurringPaymentsProfile";
508 $args['profilestartdate'] = $start_date;
6c552737 509 $args['desc'] = "" .
1ac462d0
DL
510 $params['description'] . ": " .
511 $params['amount'] . " Per " .
512 $params['frequency_interval'] . " " .
513 $params['frequency_unit'];
6a488035 514 $args['amt'] = $params['amount'];
0bde274f 515 $args['totalbillingcycles'] = CRM_Utils_Array::value('installments', $params);
6a488035 516 $args['version'] = 56.0;
6c552737 517 $args['PROFILEREFERENCE'] = "" .
1ac462d0
DL
518 "i=" . $params['invoiceID'] . "&m=" . $component .
519 "&c=" . $params['contactID'] . "&r=" . $params['contributionRecurID'] .
520 "&b=" . $params['contributionID'] . "&p=" . $params['contributionPageID'];
6a488035
TO
521 }
522
523 // Allow further manipulation of the arguments via custom hooks ..
524 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $args);
525
526 $result = $this->invokeAPI($args);
527
528 //WAG
529 if (is_a($result, 'CRM_Core_Error')) {
530 return $result;
531 }
532
533 $params['recurr_profile_id'] = NULL;
534
535 if (CRM_Utils_Array::value('is_recur', $params) == 1) {
536 $params['recurr_profile_id'] = $result['profileid'];
537 }
538
539 /* Success */
540
541 $params['trxn_id'] = CRM_Utils_Array::value('transactionid', $result);
542 $params['gross_amount'] = CRM_Utils_Array::value('amt', $result);
9d2f24ee 543 $params = array_merge($params, $this->doQuery($params));
6a488035
TO
544 return $params;
545 }
546
9d2f24ee 547 /**
548 * Query payment processor for details about a transaction.
549 *
550 * For paypal see : https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/GetTransactionDetails_API_Operation_NVP/
551 *
552 * @param array $params
553 * Array of parameters containing one of:
554 * - trxn_id Id of an individual transaction.
555 * - processor_id Id of a recurring contribution series as stored in the civicrm_contribution_recur table.
556 *
557 * @return array
558 * Extra parameters retrieved.
559 * Any parameters retrievable through this should be documented in the function comments at
560 * CRM_Core_Payment::doQuery. Currently
561 * - fee_amount Amount of fee paid
562 *
563 * @throws \Civi\Payment\Exception\PaymentProcessorException
564 */
565 public function doQuery($params) {
0bde274f 566 //CRM-18140 - trxn_id not returned for recurring paypal transaction
567 if (!empty($params['is_recur'])) {
568 return array();
569 }
570 elseif (empty($params['trxn_id'])) {
9d2f24ee 571 throw new \Civi\Payment\Exception\PaymentProcessorException('transaction id not set');
572 }
573 $args = array(
574 'TRANSACTIONID' => $params['trxn_id'],
575 );
576 $this->initialize($args, 'GetTransactionDetails');
577 $result = $this->invokeAPI($args);
578 return array(
579 'fee_amount' => $result['feeamt'],
8a2a56e9 580 'net_amount' => $params['gross_amount'] - $result['feeamt'],
9d2f24ee 581 );
582 }
583
6a488035 584 /**
fe482240 585 * This function checks to see if we have the right config values.
6a488035 586 *
a6c01b45
CW
587 * @return string
588 * the error message if any
6a488035 589 */
00be9182 590 public function checkConfig() {
6a488035 591 $error = array();
2aa397bc 592 $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, NULL, 'name');
6a488035
TO
593
594 if ($this->_paymentProcessor['payment_processor_type_id'] != CRM_Utils_Array::key('PayPal_Standard', $paymentProcessorType)) {
595 if (empty($this->_paymentProcessor['signature'])) {
0501a7d6 596 $error[] = ts('Signature is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
6a488035
TO
597 }
598
599 if (empty($this->_paymentProcessor['password'])) {
0501a7d6 600 $error[] = ts('Password is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
6a488035
TO
601 }
602 }
75466733 603 if (empty($this->_paymentProcessor['user_name'])) {
1b9f9ca3
EM
604 $error[] = ts('User Name is not set in the Administer &raquo; System Settings &raquo; Payment Processors.');
605 }
6a488035
TO
606
607 if (!empty($error)) {
608 return implode('<p>', $error);
609 }
610 else {
611 return NULL;
612 }
613 }
614
6c786a9b
EM
615 /**
616 * @return null|string
617 */
00be9182 618 public function cancelSubscriptionURL() {
6a488035
TO
619 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Standard') {
620 return "{$this->_paymentProcessor['url_site']}cgi-bin/webscr?cmd=_subscr-find&alias=" . urlencode($this->_paymentProcessor['user_name']);
621 }
622 else {
623 return NULL;
624 }
625 }
626
b5c2afd0 627 /**
100fef9d 628 * Check whether a method is present ( & supported ) by the payment processor object.
b5c2afd0 629 *
6a0b768e
TO
630 * @param string $method
631 * Method to check for.
b5c2afd0 632 *
5c766a0b 633 * @return bool
b5c2afd0 634 */
1524a007 635 public function isSupported($method) {
6a488035
TO
636 if ($this->_paymentProcessor['payment_processor_type'] != 'PayPal') {
637 // since subscription methods like cancelSubscription or updateBilling is not yet implemented / supported
638 // by standard or express.
639 return FALSE;
640 }
641 return parent::isSupported($method);
642 }
643
1ba4a3aa
EM
644 /**
645 * Paypal express replaces the submit button with it's own.
646 *
647 * @return bool
648 * Should the form button by suppressed?
649 */
650 public function isSuppressSubmitButtons() {
651 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal_Express') {
652 return TRUE;
653 }
654 return FALSE;
655 }
656
6c786a9b
EM
657 /**
658 * @param string $message
659 * @param array $params
660 *
661 * @return array|bool|object
662 */
00be9182 663 public function cancelSubscription(&$message = '', $params = array()) {
6a488035
TO
664 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
665 $args = array();
666 $this->initialize($args, 'ManageRecurringPaymentsProfileStatus');
667
668 $args['PROFILEID'] = CRM_Utils_Array::value('subscriptionId', $params);
353ffa53
TO
669 $args['ACTION'] = 'Cancel';
670 $args['NOTE'] = CRM_Utils_Array::value('reason', $params);
6a488035
TO
671
672 $result = $this->invokeAPI($args);
673 if (is_a($result, 'CRM_Core_Error')) {
674 return $result;
675 }
676 $message = "{$result['ack']}: profileid={$result['profileid']}";
677 return TRUE;
678 }
679 return FALSE;
680 }
681
5495e78a
EM
682 /**
683 * Process incoming notification.
5495e78a
EM
684 */
685 static public function handlePaymentNotification() {
ddc4b5af 686 $params = array_merge($_GET, $_REQUEST);
687 $q = explode('/', CRM_Utils_Array::value('q', $params, ''));
688 $lastParam = array_pop($q);
689 if (is_numeric($lastParam)) {
690 $params['processor_id'] = $lastParam;
691 }
692 if (civicrm_api3('PaymentProcessor', 'getvalue', array(
693 'id' => $params['processor_id'],
694 'return' => 'class_name')
695 ) == 'Payment_PayPalImpl') {
696 $paypalIPN = new CRM_Core_Payment_PayPalIPN($params);
697 }
698 else {
699 $paypalIPN = new CRM_Core_Payment_PayPalProIPN($params);
700 }
5495e78a
EM
701 $paypalIPN->main();
702 }
703
6c786a9b
EM
704 /**
705 * @param string $message
706 * @param array $params
707 *
708 * @return array|bool|object
709 */
00be9182 710 public function updateSubscriptionBillingInfo(&$message = '', $params = array()) {
6a488035
TO
711 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
712 $config = CRM_Core_Config::singleton();
713 $args = array();
714 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
715
716 $args['PROFILEID'] = $params['subscriptionId'];
717 $args['AMT'] = $params['amount'];
718 $args['CURRENCYCODE'] = $config->defaultCurrency;
719 $args['CREDITCARDTYPE'] = $params['credit_card_type'];
720 $args['ACCT'] = $params['credit_card_number'];
721 $args['EXPDATE'] = sprintf('%02d', $params['month']) . $params['year'];
722 $args['CVV2'] = $params['cvv2'];
723
353ffa53
TO
724 $args['FIRSTNAME'] = $params['first_name'];
725 $args['LASTNAME'] = $params['last_name'];
726 $args['STREET'] = $params['street_address'];
727 $args['CITY'] = $params['city'];
728 $args['STATE'] = $params['state_province'];
6a488035 729 $args['COUNTRYCODE'] = $params['postal_code'];
353ffa53 730 $args['ZIP'] = $params['country'];
6a488035
TO
731
732 $result = $this->invokeAPI($args);
733 if (is_a($result, 'CRM_Core_Error')) {
734 return $result;
735 }
736 $message = "{$result['ack']}: profileid={$result['profileid']}";
737 return TRUE;
738 }
739 return FALSE;
740 }
741
6c786a9b
EM
742 /**
743 * @param string $message
744 * @param array $params
745 *
746 * @return array|bool|object
747 */
00be9182 748 public function changeSubscriptionAmount(&$message = '', $params = array()) {
6a488035
TO
749 if ($this->_paymentProcessor['payment_processor_type'] == 'PayPal') {
750 $config = CRM_Core_Config::singleton();
751 $args = array();
752 $this->initialize($args, 'UpdateRecurringPaymentsProfile');
753
754 $args['PROFILEID'] = $params['subscriptionId'];
755 $args['AMT'] = $params['amount'];
756 $args['CURRENCYCODE'] = $config->defaultCurrency;
757 $args['BILLINGFREQUENCY'] = $params['installments'];
758
759 $result = $this->invokeAPI($args);
760 CRM_Core_Error::debug_var('$result', $result);
761 if (is_a($result, 'CRM_Core_Error')) {
762 return $result;
763 }
764 $message = "{$result['ack']}: profileid={$result['profileid']}";
765 return TRUE;
766 }
767 return FALSE;
768 }
769
38b66756
EM
770 /**
771 * Function to action pre-approval if supported
772 *
773 * @param array $params
774 * Parameters from the form
775 *
776 * @return array
777 * - pre_approval_parameters (this will be stored on the calling form & available later)
778 * - redirect_url (if set the browser will be redirected to this.
779 */
3910048c 780 public function doPreApproval(&$params) {
1d292cf3 781 if (!$this->isPaypalExpress($params)) {
ec022878 782 return array();
783 }
05c302ec 784 $this->_component = $params['component'];
3910048c
EM
785 $token = $this->setExpressCheckOut($params);
786 return array(
787 'pre_approval_parameters' => array('token' => $token),
788 'redirect_url' => $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token",
789 );
790 }
791
6c786a9b 792 /**
c490a46a 793 * @param array $params
6c786a9b
EM
794 * @param string $component
795 *
796 * @throws Exception
797 */
00be9182 798 public function doTransferCheckout(&$params, $component = 'contribute') {
6a488035 799
ddc4b5af 800 $notifyParameters = array('module' => $component);
801 $notifyParameterMap = array(
802 'contactID' => 'contactID',
803 'contributionID' => 'contributionID',
804 'eventID' => 'eventID',
805 'participantID' => 'participantID',
806 'membershipID' => 'membershipID',
807 'related_contact' => 'relatedContactID',
808 'onbehalf_dupe_alert' => 'onBehalfDupeAlert',
068fb0de 809 'accountingCode' => 'accountingCode',
11a4431c 810 'contributionRecurID' => 'contributionRecurID',
811 'contributionPageID' => 'contributionPageID',
ddc4b5af 812 );
813 foreach ($notifyParameterMap as $paramsName => $notifyName) {
814 if (!empty($params[$paramsName])) {
815 $notifyParameters[$notifyName] = $params[$paramsName];
6a488035
TO
816 }
817 }
ddc4b5af 818 $notifyURL = $this->getNotifyUrl();
6a488035 819
ddc4b5af 820 $config = CRM_Core_Config::singleton();
353ffa53
TO
821 $url = ($component == 'event') ? 'civicrm/event/register' : 'civicrm/contribute/transact';
822 $cancel = ($component == 'event') ? '_qf_Register_display' : '_qf_Main_display';
6a488035
TO
823
824 $cancelUrlString = "$cancel=1&cancel=1&qfKey={$params['qfKey']}";
a7488080 825 if (!empty($params['is_recur'])) {
1ac462d0 826 $cancelUrlString .= "&isRecur=1&recurId={$params['contributionRecurID']}&contribId={$params['contributionID']}";
6a488035
TO
827 }
828
1ac462d0
DL
829 $cancelURL = CRM_Utils_System::url(
830 $url,
6a488035
TO
831 $cancelUrlString,
832 TRUE, NULL, FALSE
833 );
834
6a488035
TO
835 $paypalParams = array(
836 'business' => $this->_paymentProcessor['user_name'],
837 'notify_url' => $notifyURL,
683538c8 838 'item_name' => $this->getPaymentDescription($params, 127),
6a488035
TO
839 'quantity' => 1,
840 'undefined_quantity' => 0,
841 'cancel_return' => $cancelURL,
842 'no_note' => 1,
843 'no_shipping' => 1,
ddc4b5af 844 'return' => $this->getReturnSuccessUrl($params['qfKey']),
6a488035
TO
845 'rm' => 2,
846 'currency_code' => $params['currencyID'],
847 'invoice' => $params['invoiceID'],
848 'lc' => substr($config->lcMessages, -2),
849 'charset' => function_exists('mb_internal_encoding') ? mb_internal_encoding() : 'UTF-8',
068fb0de 850 'custom' => json_encode($notifyParameters),
de753541 851 'bn' => 'CiviCRM_SP',
6a488035
TO
852 );
853
854 // add name and address if available, CRM-3130
855 $otherVars = array(
856 'first_name' => 'first_name',
857 'last_name' => 'last_name',
858 'street_address' => 'address1',
859 'country' => 'country',
860 'preferred_language' => 'lc',
861 'city' => 'city',
862 'state_province' => 'state',
863 'postal_code' => 'zip',
864 'email' => 'email',
865 );
866
867 foreach (array_keys($params) as $p) {
868 // get the base name without the location type suffixed to it
869 $parts = explode('-', $p);
870 $name = count($parts) > 1 ? $parts[0] : $p;
871 if (isset($otherVars[$name])) {
872 $value = $params[$p];
873 if ($value) {
874 if ($name == 'state_province') {
875 $stateName = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value);
876 $value = $stateName;
877 }
878 if ($name == 'country') {
879 $countryName = CRM_Core_PseudoConstant::countryIsoCode($value);
880 $value = $countryName;
881 }
882 // ensure value is not an array
883 // CRM-4174
884 if (!is_array($value)) {
885 $paypalParams[$otherVars[$name]] = $value;
886 }
887 }
888 }
889 }
890
891 // if recurring donations, add a few more items
892 if (!empty($params['is_recur'])) {
11a4431c 893 if (!$params['contributionRecurID']) {
6a488035
TO
894 CRM_Core_Error::fatal(ts('Recurring contribution, but no database id'));
895 }
896
897 $paypalParams += array(
898 'cmd' => '_xclick-subscriptions',
353ffa53
TO
899 'a3' => $params['amount'],
900 'p3' => $params['frequency_interval'],
901 't3' => ucfirst(substr($params['frequency_unit'], 0, 1)),
6a488035
TO
902 'src' => 1,
903 'sra' => 1,
14965416 904 'srt' => CRM_Utils_Array::value('installments', $params),
6a488035
TO
905 'no_note' => 1,
906 'modify' => 0,
907 );
908 }
909 else {
910 $paypalParams += array(
911 'cmd' => '_xclick',
912 'amount' => $params['amount'],
913 );
914 }
915
916 // Allow further manipulation of the arguments via custom hooks ..
917 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $paypalParams);
918
919 $uri = '';
920 foreach ($paypalParams as $key => $value) {
921 if ($value === NULL) {
922 continue;
923 }
924
925 $value = urlencode($value);
926 if ($key == 'return' ||
927 $key == 'cancel_return' ||
928 $key == 'notify_url'
929 ) {
930 $value = str_replace('%2F', '/', $value);
931 }
932 $uri .= "&{$key}={$value}";
933 }
934
353ffa53
TO
935 $uri = substr($uri, 1);
936 $url = $this->_paymentProcessor['url_site'];
937 $sub = empty($params['is_recur']) ? 'cgi-bin/webscr' : 'subscriptions';
6a488035
TO
938 $paypalURL = "{$url}{$sub}?$uri";
939
940 CRM_Utils_System::redirect($paypalURL);
941 }
942
943 /**
ad37ac8e 944 * Hash_call: Function to perform the API call to PayPal using API signature.
945 *
6a488035
TO
946 * @methodName is name of API method.
947 * @nvpStr is nvp string.
ad37ac8e 948 * returns an associative array containing the response from the server.
949 *
950 * @param array $args
951 * @param null $url
952 *
953 * @return array|object
954 * @throws \Exception
6a488035 955 */
00be9182 956 public function invokeAPI($args, $url = NULL) {
6a488035
TO
957
958 if ($url === NULL) {
959 if (empty($this->_paymentProcessor['url_api'])) {
960 CRM_Core_Error::fatal(ts('Please set the API URL. Please refer to the documentation for more details'));
961 }
962
963 $url = $this->_paymentProcessor['url_api'] . 'nvp';
964 }
965
966 if (!function_exists('curl_init')) {
967 CRM_Core_Error::fatal("curl functions NOT available.");
968 }
969
970 //setting the curl parameters.
971 $ch = curl_init();
972 curl_setopt($ch, CURLOPT_URL, $url);
c20af6a3 973 curl_setopt($ch, CURLOPT_VERBOSE, 0);
6a488035
TO
974
975 //turning off the server and peer verification(TrustManager Concept).
aaffa79f 976 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, Civi::settings()->get('verifySSL'));
977 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, Civi::settings()->get('verifySSL') ? 2 : 0);
6a488035
TO
978
979 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
980 curl_setopt($ch, CURLOPT_POST, 1);
981
982 $p = array();
983 foreach ($args as $n => $v) {
984 $p[] = "$n=" . urlencode($v);
985 }
986
987 //NVPRequest for submitting to server
988 $nvpreq = implode('&', $p);
989
990 //setting the nvpreq as POST FIELD to curl
991 curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
992
993 //getting response from server
994 $response = curl_exec($ch);
995
996 //converting NVPResponse to an Associative Array
997 $result = self::deformat($response);
998
999 if (curl_errno($ch)) {
1000 $e = CRM_Core_Error::singleton();
1001 $e->push(curl_errno($ch),
1002 0, NULL,
1003 curl_error($ch)
1004 );
1005 return $e;
1006 }
1007 else {
1008 curl_close($ch);
1009 }
1010
1011 if (strtolower($result['ack']) != 'success' &&
1012 strtolower($result['ack']) != 'successwithwarning'
1013 ) {
abfb35ee 1014 throw new PaymentProcessorException("{$result['l_shortmessage0']} {$result['l_longmessage0']}");
6a488035
TO
1015 $e = CRM_Core_Error::singleton();
1016 $e->push($result['l_errorcode0'],
1017 0, NULL,
1018 "{$result['l_shortmessage0']} {$result['l_longmessage0']}"
1019 );
1020 return $e;
1021 }
1022
1023 return $result;
1024 }
1025
be2e0c6a 1026 /**
ad37ac8e 1027 * This function will take NVPString and convert it to an Associative Array.
1028 *
1029 * It will decode the response. It is useful to search for a particular key and displaying arrays.
1030 *
1031 * @param string $str
1032 *
1033 * @return array
6a488035 1034 */
00be9182 1035 public static function deformat($str) {
6a488035
TO
1036 $result = array();
1037
1038 while (strlen($str)) {
b44e3f84 1039 // position of key
6a488035
TO
1040 $keyPos = strpos($str, '=');
1041
1042 // position of value
1043 $valPos = strpos($str, '&') ? strpos($str, '&') : strlen($str);
1044
1045 /*getting the Key and Value values and storing in a Associative Array*/
1046
1047 $key = substr($str, 0, $keyPos);
1048 $val = substr($str, $keyPos + 1, $valPos - $keyPos - 1);
1049
1050 //decoding the respose
1051 $result[strtolower(urldecode($key))] = urldecode($val);
1052 $str = substr($str, $valPos + 1, strlen($str));
1053 }
1054
1055 return $result;
1056 }
96025800 1057
3cc8d80d 1058 /**
1059 * Get array of fields that should be displayed on the payment form.
1060 *
1061 * @return array
1062 * @throws CiviCRM_API3_Exception
1063 */
1064 public function getPaymentFormFields() {
1065 if ($this->_processorName == ts('PayPal Pro')) {
1066 return $this->getCreditCardFormFields();
1067 }
1068 else {
1069 return array();
1070 }
1071 }
1072
933da5b5
EM
1073 /**
1074 * Map the paypal params to CiviCRM params using a field map.
1075 *
1076 * @param array $fieldMap
1077 * @param array $paypalParams
1078 *
1079 * @return array
1080 */
1081 protected function mapPaypalParamsToCivicrmParams($fieldMap, $paypalParams) {
1082 $params = array();
1083 foreach ($fieldMap as $civicrmField => $paypalField) {
1084 $params[$civicrmField] = isset($paypalParams[$paypalField]) ? $paypalParams[$paypalField] : NULL;
1085 }
1086 return $params;
1087 }
1088
1d292cf3 1089 /**
1090 * Is this being processed by payment express.
1091 *
1092 * Either because it is payment express or because is pro with paypal express in use.
1093 *
1094 * @param array $params
1095 *
1096 * @return bool
1097 */
1098 protected function isPaypalExpress($params) {
1099 if ($this->_processorName == ts('PayPal Express')) {
1100 return TRUE;
1101 }
1102
1103 // This would occur postProcess.
1104 if (!empty($params['token'])) {
1105 return TRUE;
1106 }
1107 if (isset($params['button']) && stristr($params['button'], 'express')) {
1108 return TRUE;
1109 }
1110
1111 // The contribution form passes a 'button' but the event form might still set one of these fields.
1112 // @todo more standardisation & get paypal fully out of the form layer.
1113 $possibleExpressFields = array(
1114 '_qf_Register_upload_express_x',
1115 '_qf_Payment_upload_express_x',
1116 );
1117 if (array_intersect_key($params, array_fill_keys($possibleExpressFields, 1))) {
1118 return TRUE;
1119 }
1120 return FALSE;
1121 }
1122
6a488035 1123}