Merge pull request #18028 from eileenmcnaughton/anet
[civicrm-core.git] / CRM / Core / Payment / PayPalProIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Core_Payment_PayPalProIPN extends CRM_Core_Payment_BaseIPN {
18
19 public static $_paymentProcessor = NULL;
20
21 /**
22 * Input parameters from payment processor. Store these so that
23 * the code does not need to keep retrieving from the http request
24 * @var array
25 */
26 protected $_inputParameters = [];
27
28 /**
29 * Store for the variables from the invoice string.
30 * @var array
31 */
32 protected $_invoiceData = [];
33
34 /**
35 * Is this a payment express transaction.
36 * @var bool
37 */
38 protected $_isPaymentExpress = FALSE;
39
40 /**
41 * Component.
42 *
43 * Are we dealing with an event an 'anything else' (contribute).
44 *
45 * @var string
46 */
47 protected $_component = 'contribute';
48
49 /**
50 * Constructor function.
51 *
52 * @param array $inputData
53 * Contents of HTTP REQUEST.
54 *
55 * @throws CRM_Core_Exception
56 */
57 public function __construct($inputData) {
58 $this->setInputParameters($inputData);
59 $this->setInvoiceData();
60 parent::__construct();
61 }
62
63 /**
64 * get the values from the rp_invoice_id string.
65 *
66 * @param string $name
67 * E.g. i, values are stored in the string with letter codes.
68 * @param bool $abort
69 * Throw exception if not found
70 *
71 * @throws CRM_Core_Exception
72 * @return mixed
73 */
74 public function getValue($name, $abort = TRUE) {
75 if ($abort && empty($this->_invoiceData[$name])) {
76 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
77 }
78 else {
79 return $this->_invoiceData[$name] ?? NULL;
80 }
81 }
82
83 /**
84 * Set $this->_invoiceData from the input array
85 */
86 public function setInvoiceData() {
87 if (empty($this->_inputParameters['rp_invoice_id'])) {
88 $this->_isPaymentExpress = TRUE;
89 return;
90 }
91 $rpInvoiceArray = explode('&', $this->_inputParameters['rp_invoice_id']);
92 // for clarify let's also store without the single letter unreadable
93 //@todo after more refactoring we might ditch storing the one letter stuff
94 $mapping = [
95 'i' => 'invoice_id',
96 'm' => 'component',
97 'c' => 'contact_id',
98 'b' => 'contribution_id',
99 'r' => 'contribution_recur_id',
100 'p' => 'participant_id',
101 'e' => 'event_id',
102 ];
103 foreach ($rpInvoiceArray as $rpInvoiceValue) {
104 $rpValueArray = explode('=', $rpInvoiceValue);
105 $this->_invoiceData[$rpValueArray[0]] = $rpValueArray[1];
106 $this->_inputParameters[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
107 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
108 // alphabet with more letters.
109 // the mode will always be resolved before the mystery p is reached
110 if ($rpValueArray[1] == 'contribute') {
111 $mapping['p'] = 'contribution_page_id';
112 }
113 }
114 if (empty($this->_inputParameters['component'])) {
115 $this->_isPaymentExpress = TRUE;
116 }
117 }
118
119 /**
120 * @param string $name
121 * Of variable to return.
122 * @param string $type
123 * Data type.
124 * - String
125 * - Integer
126 * @param string $location
127 * Deprecated.
128 * @param bool $abort
129 * Abort if empty.
130 *
131 * @throws CRM_Core_Exception
132 * @return mixed
133 */
134 public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
135 $value = CRM_Utils_Type::validate(
136 CRM_Utils_Array::value($name, $this->_inputParameters),
137 $type,
138 FALSE
139 );
140 if ($abort && $value === NULL) {
141 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
142 }
143 return $value;
144 }
145
146 /**
147 * Process recurring contributions.
148 * @param array $input
149 * @param array $ids
150 * @param array $objects
151 * @param bool $first
152 * @return void
153 */
154 public function recur(&$input, &$ids, &$objects, $first) {
155 if (!isset($input['txnType'])) {
156 Civi::log()->debug('PayPalProIPN: Could not find txn_type in input request.');
157 echo "Failure: Invalid parameters<p>";
158 return;
159 }
160
161 $recur = &$objects['contributionRecur'];
162
163 // make sure the invoice ids match
164 // make sure the invoice is valid and matches what we have in
165 // the contribution record
166 if ($recur->invoice_id != $input['invoice']) {
167 Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . ' input is ' . $input['invoice']);
168 echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice'];
169 return;
170 }
171
172 $now = date('YmdHis');
173
174 // fix dates that already exist
175 $dates = ['create', 'start', 'end', 'cancel', 'modified'];
176 foreach ($dates as $date) {
177 $name = "{$date}_date";
178 if ($recur->$name) {
179 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
180 }
181 }
182
183 $sendNotification = FALSE;
184 $subscriptionPaymentStatus = NULL;
185 //List of Transaction Type
186 /*
187 recurring_payment_profile_created RP Profile Created
188 recurring_payment RP Successful Payment
189 recurring_payment_failed RP Failed Payment
190 recurring_payment_profile_cancel RP Profile Cancelled
191 recurring_payment_expired RP Profile Expired
192 recurring_payment_skipped RP Profile Skipped
193 recurring_payment_outstanding_payment RP Successful Outstanding Payment
194 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
195 recurring_payment_suspended RP Profile Suspended
196 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
197 */
198
199 //set transaction type
200 $txnType = $this->retrieve('txn_type', 'String');
201 //Changes for paypal pro recurring payment
202 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
203 switch ($txnType) {
204 case 'recurring_payment_profile_created':
205 if (in_array($recur->contribution_status_id, [
206 $contributionStatuses['Pending'],
207 $contributionStatuses['In Progress'],
208 ])
209 && !empty($recur->processor_id)
210 ) {
211 echo "already handled";
212 return;
213 }
214 $recur->create_date = $now;
215 $recur->contribution_status_id = $contributionStatuses['Pending'];
216 $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
217 $recur->trxn_id = $recur->processor_id;
218 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
219 $sendNotification = TRUE;
220 break;
221
222 case 'recurring_payment':
223 if ($first) {
224 $recur->start_date = $now;
225 }
226 else {
227 if ($input['paymentStatus'] != 'Completed') {
228 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
229 }
230
231 // In future moving to create pending & then complete, but this OK for now.
232 // Also consider accepting 'Failed' like other processors.
233 $input['contribution_status_id'] = $contributionStatuses['Completed'];
234 $input['invoice_id'] = md5(uniqid(rand(), TRUE));
235 $input['original_contribution_id'] = $ids['contribution'];
236 $input['contribution_recur_id'] = $ids['contributionRecur'];
237
238 civicrm_api3('Contribution', 'repeattransaction', $input);
239 return;
240 }
241
242 //contribution installment is completed
243 if ($this->retrieve('profile_status', 'String') == 'Expired') {
244 if (!empty($recur->end_date)) {
245 echo "already handled";
246 return;
247 }
248 $recur->contribution_status_id = $contributionStatuses['Completed'];
249 $recur->end_date = $now;
250 $sendNotification = TRUE;
251 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
252 }
253
254 // make sure the contribution status is not done
255 // since order of ipn's is unknown
256 if ($recur->contribution_status_id != $contributionStatuses['Completed']) {
257 $recur->contribution_status_id = $contributionStatuses['In Progress'];
258 }
259 break;
260 }
261
262 $recur->save();
263
264 if ($sendNotification) {
265 $autoRenewMembership = FALSE;
266 if ($recur->id &&
267 isset($ids['membership']) && $ids['membership']
268 ) {
269 $autoRenewMembership = TRUE;
270 }
271 //send recurring Notification email for user
272 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
273 $ids['contact'],
274 $ids['contributionPage'],
275 $recur,
276 $autoRenewMembership
277 );
278 }
279
280 if ($txnType != 'recurring_payment') {
281 return;
282 }
283
284 if (!$first) {
285 //check if this contribution transaction is already processed
286 //if not create a contribution and then get it processed
287 $contribution = new CRM_Contribute_BAO_Contribution();
288 $contribution->trxn_id = $input['trxn_id'];
289 if ($contribution->trxn_id && $contribution->find()) {
290 Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
291 echo "Success: Contribution has already been handled<p>";
292 return;
293 }
294
295 $contribution->contact_id = $recur->contact_id;
296 $contribution->financial_type_id = $objects['contributionType']->id;
297 $contribution->contribution_page_id = $ids['contributionPage'];
298 $contribution->contribution_recur_id = $ids['contributionRecur'];
299 $contribution->currency = $objects['contribution']->currency;
300 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
301 $contribution->amount_level = $objects['contribution']->amount_level;
302 $contribution->campaign_id = $objects['contribution']->campaign_id;
303 $objects['contribution'] = &$contribution;
304 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
305 }
306 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
307 $objects['contribution']->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])) : $now;
308
309 $this->single($input, $ids, $objects, TRUE, $first);
310 }
311
312 /**
313 * @param array $input
314 * @param array $ids
315 * @param array $objects
316 * @param bool $recur
317 * @param bool $first
318 *
319 * @return void
320 */
321 public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
322 $contribution = &$objects['contribution'];
323
324 // make sure the invoice is valid and matches what we have in the contribution record
325 if ((!$recur) || ($recur && $first)) {
326 if ($contribution->invoice_id != $input['invoice']) {
327 Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request.');
328 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
329 return;
330 }
331 }
332 else {
333 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
334 }
335
336 if (!$recur) {
337 if ($contribution->total_amount != $input['amount']) {
338 Civi::log()->debug('PayPalProIPN: Amount values dont match between database and IPN request.');
339 echo "Failure: Amount values dont match between database and IPN request<p>";
340 return;
341 }
342 }
343 else {
344 $contribution->total_amount = $input['amount'];
345 }
346
347 $status = $input['paymentStatus'];
348 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
349 $this->failed($objects);
350 return;
351 }
352 if ($status === 'Pending') {
353 Civi::log()->debug('Returning since contribution status is Pending');
354 return;
355 }
356 elseif ($status == 'Refunded' || $status == 'Reversed') {
357 $this->cancelled($objects);
358 return;
359 }
360 elseif ($status !== 'Completed') {
361 Civi::log()->debug('Returning since contribution status is not handled');
362 return;
363 }
364
365 // check if contribution is already completed, if so we ignore this ipn
366 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
367 if ($contribution->contribution_status_id == $completedStatusId) {
368 Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
369 echo 'Success: Contribution has already been handled<p>';
370 return;
371 }
372
373 $this->completeTransaction($input, $ids, $objects);
374 }
375
376 /**
377 * Gets PaymentProcessorID for PayPal
378 *
379 * @return int
380 */
381 public function getPayPalPaymentProcessorID() {
382 // This is an unreliable method as there could be more than one instance.
383 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
384 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
385 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
386 // & call completetransaction or call fail? (which may not exist yet).
387
388 Civi::log()->warning('Unreliable method used to get payment_processor_id for PayPal Pro IPN - this will cause problems if you have more than one instance');
389
390 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
391 'PayPal', 'id', 'name'
392 );
393 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
394 'is_test' => 0,
395 'options' => ['limit' => 1],
396 'payment_processor_type_id' => $paymentProcessorTypeID,
397 'return' => 'id',
398 ]);
399
400 }
401
402 /**
403 * This is the main function to call. It should be sufficient to instantiate the class
404 * (with the input parameters) & call this & all will be done
405 *
406 * @todo the references to POST throughout this class need to be removed
407 * @return void
408 */
409 public function main() {
410 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
411 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
412 if ($this->_isPaymentExpress) {
413 $this->handlePaymentExpress();
414 return;
415 }
416 $objects = $ids = $input = [];
417 $this->_component = $input['component'] = self::getValue('m');
418 $input['invoice'] = self::getValue('i', TRUE);
419 // get the contribution and contact ids from the GET params
420 $ids['contact'] = self::getValue('c', TRUE);
421 $ids['contribution'] = self::getValue('b', TRUE);
422
423 $this->getInput($input);
424
425 if ($this->_component == 'event') {
426 $ids['event'] = self::getValue('e', TRUE);
427 $ids['participant'] = self::getValue('p', TRUE);
428 $ids['contributionRecur'] = self::getValue('r', FALSE);
429 }
430 else {
431 // get the optional ids
432 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
433 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
434 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
435 $ids['contributionRecur'] = self::getValue('r', FALSE);
436 $ids['contributionPage'] = self::getValue('p', FALSE);
437 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
438 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
439 }
440
441 if (!$ids['membership'] && $ids['contributionRecur']) {
442 $sql = "
443 SELECT m.id
444 FROM civicrm_membership m
445 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
446 WHERE m.contribution_recur_id = %2
447 LIMIT 1";
448 $sqlParams = [
449 1 => [$ids['contribution'], 'Integer'],
450 2 => [$ids['contributionRecur'], 'Integer'],
451 ];
452 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
453 $ids['membership'] = $membershipId;
454 }
455 }
456
457 $paymentProcessorID = CRM_Utils_Array::value('processor_id', $this->_inputParameters);
458 if (!$paymentProcessorID) {
459 $paymentProcessorID = self::getPayPalPaymentProcessorID();
460 }
461
462 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
463 return;
464 }
465
466 self::$_paymentProcessor = &$objects['paymentProcessor'];
467 //?? how on earth would we not have component be one of these?
468 // they are the only valid settings & this IPN file can't even be called without one of them
469 // grepping for this class doesn't find other paths to call this class
470 if ($this->_component == 'contribute' || $this->_component == 'event') {
471 if ($ids['contributionRecur']) {
472 // check if first contribution is completed, else complete first contribution
473 $first = TRUE;
474 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
475 if ($objects['contribution']->contribution_status_id == $completedStatusId) {
476 $first = FALSE;
477 }
478 $this->recur($input, $ids, $objects, $first);
479 return;
480 }
481 }
482 $this->single($input, $ids, $objects, FALSE, FALSE);
483 }
484
485 /**
486 * @param array $input
487 *
488 * @return void
489 * @throws CRM_Core_Exception
490 */
491 public function getInput(&$input) {
492 $billingID = CRM_Core_BAO_LocationType::getBilling();
493
494 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
495 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
496
497 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
498 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
499
500 $lookup = [
501 "first_name" => 'first_name',
502 "last_name" => 'last_name',
503 "street_address-{$billingID}" => 'address_street',
504 "city-{$billingID}" => 'address_city',
505 "state-{$billingID}" => 'address_state',
506 "postal_code-{$billingID}" => 'address_zip',
507 "country-{$billingID}" => 'address_country_code',
508 ];
509 foreach ($lookup as $name => $paypalName) {
510 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
511 $input[$name] = $value ? $value : NULL;
512 }
513
514 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
515 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
516 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
517 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
518 $input['payment_date'] = $input['receive_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
519 $input['total_amount'] = $input['amount'];
520 }
521
522 /**
523 * Handle payment express IPNs.
524 *
525 * For one off IPNS no actual response is required
526 * Recurring is more difficult as we have limited confirmation material
527 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
528 * duplicated
529 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
530 * then the quasi security of the ids array might be required - although better to
531 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
532 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
533 * only contribute is handled
534 */
535 public function handlePaymentExpress() {
536 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
537 // keep discreet
538 // also note that a lot of the complexity above could be removed if we used
539 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
540 // as membership id etc can be derived by the load objects fn
541 $objects = $ids = $input = [];
542 $isFirst = FALSE;
543 $input['invoice'] = self::getValue('i', FALSE);
544 //Avoid return in case of unit test.
545 if (empty($input['invoice']) && empty($this->_inputParameters['is_unit_test'])) {
546 return;
547 }
548 $input['txnType'] = $this->retrieve('txn_type', 'String');
549 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
550 'return' => 'contact_id, id, payment_processor_id',
551 'invoice_id' => $input['invoice'],
552 ]);
553
554 if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
555 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
556 }
557
558 $this->getInput($input, $ids);
559 if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
560 throw new CRM_Core_Exception('This transaction has already been processed');
561 }
562
563 $ids['contact'] = $contributionRecur['contact_id'];
564 $ids['contributionRecur'] = $contributionRecur['id'];
565 $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
566
567 $ids['contribution'] = $result['id'];
568 //@todo hardcoding 'pending' for now
569 $pendingStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
570 if ($result['contribution_status_id'] == $pendingStatusId) {
571 $isFirst = TRUE;
572 }
573 // arg api won't get this - fix it
574 $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", [
575 1 => [
576 $ids['contribution'],
577 'Integer',
578 ],
579 ]);
580 // only handle component at this stage - not terribly sure how a recurring event payment would arise
581 // & suspec main function may be a victom of copy & paste
582 // membership would be an easy add - but not relevant to my customer...
583 $this->_component = $input['component'] = 'contribute';
584 $input['trxn_date'] = date('Y-m-d H:i:s', strtotime(self::retrieve('time_created', 'String')));
585 $paymentProcessorID = $contributionRecur['payment_processor_id'];
586
587 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
588 throw new CRM_Core_Exception('Data did not validate');
589 }
590 $this->recur($input, $ids, $objects, $isFirst);
591 }
592
593 /**
594 * Function check if transaction already exists.
595 * @param string $trxn_id
596 * @return bool|void
597 */
598 public function transactionExists($trxn_id) {
599 if (CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
600 [
601 1 => [$trxn_id, 'String'],
602 ])
603 ) {
604 return TRUE;
605 }
606 }
607
608 }