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