Merge pull request #18934 from eileenmcnaughton/aip
[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 use Civi\Api4\Contribution;
13
14 /**
15 *
16 * @package CRM
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 */
19 class CRM_Core_Payment_PayPalProIPN extends CRM_Core_Payment_BaseIPN {
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 *
149 * @param array $input
150 * @param array $ids
151 * @param array $objects
152 * @param bool $first
153 *
154 * @throws \CRM_Core_Exception
155 * @throws \CiviCRM_API3_Exception
156 */
157 public function recur($input, $ids, $objects, $first) {
158 if (!isset($input['txnType'])) {
159 Civi::log()->debug('PayPalProIPN: Could not find txn_type in input request.');
160 echo 'Failure: Invalid parameters<p>';
161 return;
162 }
163
164 $recur = &$objects['contributionRecur'];
165
166 // make sure the invoice ids match
167 // make sure the invoice is valid and matches what we have in
168 // the contribution record
169 if ($recur->invoice_id != $input['invoice']) {
170 Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . ' input is ' . $input['invoice']);
171 echo 'Failure: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id . " input is " . $input['invoice'];
172 return;
173 }
174
175 $now = date('YmdHis');
176
177 $sendNotification = FALSE;
178 $subscriptionPaymentStatus = NULL;
179 //List of Transaction Type
180 /*
181 recurring_payment_profile_created RP Profile Created
182 recurring_payment RP Successful Payment
183 recurring_payment_failed RP Failed Payment
184 recurring_payment_profile_cancel RP Profile Cancelled
185 recurring_payment_expired RP Profile Expired
186 recurring_payment_skipped RP Profile Skipped
187 recurring_payment_outstanding_payment RP Successful Outstanding Payment
188 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
189 recurring_payment_suspended RP Profile Suspended
190 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
191 */
192
193 //set transaction type
194 $txnType = $this->retrieve('txn_type', 'String');
195 //Changes for paypal pro recurring payment
196 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate'));
197 switch ($txnType) {
198 case 'recurring_payment_profile_created':
199 if (in_array($recur->contribution_status_id, [
200 $contributionStatuses['Pending'],
201 $contributionStatuses['In Progress'],
202 ])
203 && !empty($recur->processor_id)
204 ) {
205 echo "already handled";
206 return;
207 }
208 $recur->create_date = $now;
209 $recur->contribution_status_id = $contributionStatuses['Pending'];
210 $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
211 $recur->trxn_id = $recur->processor_id;
212 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
213 $sendNotification = TRUE;
214 break;
215
216 case 'recurring_payment':
217 if ($first) {
218 $recur->start_date = $now;
219 }
220 else {
221 if ($input['paymentStatus'] != 'Completed') {
222 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
223 }
224
225 // In future moving to create pending & then complete, but this OK for now.
226 // Also consider accepting 'Failed' like other processors.
227 $input['contribution_status_id'] = $contributionStatuses['Completed'];
228 $input['invoice_id'] = md5(uniqid(rand(), TRUE));
229 $input['original_contribution_id'] = $ids['contribution'];
230 $input['contribution_recur_id'] = $ids['contributionRecur'];
231
232 civicrm_api3('Contribution', 'repeattransaction', $input);
233 return;
234 }
235
236 //contribution installment is completed
237 if ($this->retrieve('profile_status', 'String') == 'Expired') {
238 if (!empty($recur->end_date)) {
239 echo "already handled";
240 return;
241 }
242 $recur->contribution_status_id = $contributionStatuses['Completed'];
243 $recur->end_date = $now;
244 $sendNotification = TRUE;
245 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
246 }
247
248 // make sure the contribution status is not done
249 // since order of ipn's is unknown
250 if ($recur->contribution_status_id != $contributionStatuses['Completed']) {
251 $recur->contribution_status_id = $contributionStatuses['In Progress'];
252 }
253 break;
254 }
255
256 $recur->save();
257
258 if ($sendNotification) {
259 $autoRenewMembership = FALSE;
260 if ($recur->id &&
261 isset($ids['membership']) && $ids['membership']
262 ) {
263 $autoRenewMembership = TRUE;
264 }
265 //send recurring Notification email for user
266 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
267 $ids['contact'],
268 $ids['contributionPage'],
269 $recur,
270 $autoRenewMembership
271 );
272 }
273
274 if ($txnType != 'recurring_payment') {
275 return;
276 }
277
278 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
279 $objects['contribution']->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])) : $now;
280
281 $this->single($input, [
282 'related_contact' => $ids['related_contact'] ?? NULL,
283 'participant' => $ids['participant'] ?? NULL,
284 'contributionRecur' => $recur->id ?? NULL,
285 ], $objects, TRUE, $first);
286 }
287
288 /**
289 * @param array $input
290 * @param array $ids
291 * @param array $objects
292 * @param bool $recur
293 * @param bool $first
294 *
295 * @return void
296 */
297 public function single($input, $ids, $objects, $recur = FALSE, $first = FALSE) {
298 $contribution = &$objects['contribution'];
299
300 // make sure the invoice is valid and matches what we have in the contribution record
301 if ((!$recur) || ($recur && $first)) {
302 if ($contribution->invoice_id != $input['invoice']) {
303 Civi::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request.');
304 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
305 return;
306 }
307 }
308 else {
309 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
310 }
311
312 if (!$recur) {
313 if ($contribution->total_amount != $input['amount']) {
314 Civi::log()->debug('PayPalProIPN: Amount values dont match between database and IPN request.');
315 echo "Failure: Amount values dont match between database and IPN request<p>";
316 return;
317 }
318 }
319 else {
320 $contribution->total_amount = $input['amount'];
321 }
322
323 $status = $input['paymentStatus'];
324 if ($status === 'Denied' || $status === 'Failed' || $status === 'Voided') {
325 $this->failed($objects);
326 return;
327 }
328 if ($status === 'Pending') {
329 Civi::log()->debug('Returning since contribution status is Pending');
330 return;
331 }
332 if ($status === 'Refunded' || $status === 'Reversed') {
333 Contribution::update(FALSE)->setValues([
334 'cancel_date' => 'now',
335 'contribution_status_id:name' => 'Cancelled',
336 ])->addWhere('id', '=', $contribution->id)->execute();
337 Civi::log()->debug("Setting contribution status to Cancelled");
338 return;
339 }
340 elseif ($status !== 'Completed') {
341 Civi::log()->debug('Returning since contribution status is not handled');
342 return;
343 }
344
345 // check if contribution is already completed, if so we ignore this ipn
346 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
347 if ($contribution->contribution_status_id == $completedStatusId) {
348 Civi::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
349 echo 'Success: Contribution has already been handled<p>';
350 return;
351 }
352
353 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects['contribution']);
354 }
355
356 /**
357 * Gets PaymentProcessorID for PayPal
358 *
359 * @return int
360 */
361 public function getPayPalPaymentProcessorID() {
362 // This is an unreliable method as there could be more than one instance.
363 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
364 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
365 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
366 // & call completetransaction or call fail? (which may not exist yet).
367
368 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');
369
370 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
371 'PayPal', 'id', 'name'
372 );
373 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
374 'is_test' => 0,
375 'options' => ['limit' => 1],
376 'payment_processor_type_id' => $paymentProcessorTypeID,
377 'return' => 'id',
378 ]);
379
380 }
381
382 /**
383 * This is the main function to call. It should be sufficient to instantiate the class
384 * (with the input parameters) & call this & all will be done
385 *
386 * @todo the references to POST throughout this class need to be removed
387 * @return void
388 */
389 public function main() {
390 CRM_Core_Error::debug_var('GET', $_GET, TRUE, TRUE);
391 CRM_Core_Error::debug_var('POST', $_POST, TRUE, TRUE);
392 try {
393 if ($this->_isPaymentExpress) {
394 $this->handlePaymentExpress();
395 return;
396 }
397 $objects = $ids = $input = [];
398 $this->_component = $input['component'] = self::getValue('m');
399 $input['invoice'] = self::getValue('i', TRUE);
400 // get the contribution and contact ids from the GET params
401 $ids['contact'] = self::getValue('c', TRUE);
402 $ids['contribution'] = self::getValue('b', TRUE);
403
404 $this->getInput($input);
405
406 if ($this->_component == 'event') {
407 $ids['event'] = self::getValue('e', TRUE);
408 $ids['participant'] = self::getValue('p', TRUE);
409 $ids['contributionRecur'] = self::getValue('r', FALSE);
410 }
411 else {
412 // get the optional ids
413 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
414 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
415 $ids['membership'] = self::retrieve('membershipID', 'Integer', 'GET', FALSE);
416 $ids['contributionRecur'] = self::getValue('r', FALSE);
417 $ids['contributionPage'] = self::getValue('p', FALSE);
418 $ids['related_contact'] = self::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
419 $ids['onbehalf_dupe_alert'] = self::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
420 }
421
422 if (!$ids['membership'] && $ids['contributionRecur']) {
423 $sql = "
424 SELECT m.id
425 FROM civicrm_membership m
426 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
427 WHERE m.contribution_recur_id = %2
428 LIMIT 1";
429 $sqlParams = [
430 1 => [$ids['contribution'], 'Integer'],
431 2 => [$ids['contributionRecur'], 'Integer'],
432 ];
433 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
434 $ids['membership'] = $membershipId;
435 }
436 }
437
438 $paymentProcessorID = CRM_Utils_Array::value('processor_id', $this->_inputParameters);
439 if (!$paymentProcessorID) {
440 $paymentProcessorID = self::getPayPalPaymentProcessorID();
441 }
442
443 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
444 return;
445 }
446
447 $input['payment_processor_id'] = $paymentProcessorID;
448
449 if ($ids['contributionRecur']) {
450 // check if first contribution is completed, else complete first contribution
451 $first = TRUE;
452 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
453 if ($objects['contribution']->contribution_status_id == $completedStatusId) {
454 $first = FALSE;
455 }
456 $this->recur($input, $ids, $objects, $first);
457 return;
458 }
459
460 $this->single($input, [
461 'related_contact' => $ids['related_contact'] ?? NULL,
462 'participant' => $ids['participant'] ?? NULL,
463 'contributionRecur' => $ids['contributionRecur'] ?? NULL,
464 ], $objects, FALSE, FALSE);
465 }
466 catch (CRM_Core_Exception $e) {
467 Civi::log()->debug($e->getMessage());
468 echo 'Invalid or missing data';
469 }
470 }
471
472 /**
473 * @param array $input
474 *
475 * @return void
476 * @throws CRM_Core_Exception
477 */
478 public function getInput(&$input) {
479 $billingID = CRM_Core_BAO_LocationType::getBilling();
480
481 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
482 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
483
484 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
485 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
486
487 $lookup = [
488 "first_name" => 'first_name',
489 "last_name" => 'last_name',
490 "street_address-{$billingID}" => 'address_street',
491 "city-{$billingID}" => 'address_city',
492 "state-{$billingID}" => 'address_state',
493 "postal_code-{$billingID}" => 'address_zip',
494 "country-{$billingID}" => 'address_country_code',
495 ];
496 foreach ($lookup as $name => $paypalName) {
497 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
498 $input[$name] = $value ? $value : NULL;
499 }
500
501 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
502 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
503 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
504 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
505 $input['payment_date'] = $input['receive_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
506 $input['total_amount'] = $input['amount'];
507 }
508
509 /**
510 * Handle payment express IPNs.
511 *
512 * For one off IPNS no actual response is required
513 * Recurring is more difficult as we have limited confirmation material
514 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
515 * duplicated
516 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
517 * then the quasi security of the ids array might be required - although better to
518 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
519 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
520 * only contribute is handled
521 */
522 public function handlePaymentExpress() {
523 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
524 // keep discreet
525 // also note that a lot of the complexity above could be removed if we used
526 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
527 // as membership id etc can be derived by the load objects fn
528 $objects = $ids = $input = [];
529 $isFirst = FALSE;
530 $input['invoice'] = self::getValue('i', FALSE);
531 //Avoid return in case of unit test.
532 if (empty($input['invoice']) && empty($this->_inputParameters['is_unit_test'])) {
533 return;
534 }
535 $input['txnType'] = $this->retrieve('txn_type', 'String');
536 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
537 'return' => 'contact_id, id, payment_processor_id',
538 'invoice_id' => $input['invoice'],
539 ]);
540
541 if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
542 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
543 }
544
545 $this->getInput($input, $ids);
546 if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
547 throw new CRM_Core_Exception('This transaction has already been processed');
548 }
549
550 $ids['contact'] = $contributionRecur['contact_id'];
551 $ids['contributionRecur'] = $contributionRecur['id'];
552 $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
553
554 $ids['contribution'] = $result['id'];
555 //@todo hardcoding 'pending' for now
556 $pendingStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
557 if ($result['contribution_status_id'] == $pendingStatusId) {
558 $isFirst = TRUE;
559 }
560 // arg api won't get this - fix it
561 $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", [
562 1 => [
563 $ids['contribution'],
564 'Integer',
565 ],
566 ]);
567 // only handle component at this stage - not terribly sure how a recurring event payment would arise
568 // & suspec main function may be a victom of copy & paste
569 // membership would be an easy add - but not relevant to my customer...
570 $this->_component = $input['component'] = 'contribute';
571 $input['trxn_date'] = date('Y-m-d H:i:s', strtotime(self::retrieve('time_created', 'String')));
572 $paymentProcessorID = $contributionRecur['payment_processor_id'];
573
574 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
575 throw new CRM_Core_Exception('Data did not validate');
576 }
577 $this->recur($input, $ids, $objects, $isFirst);
578 }
579
580 /**
581 * Function check if transaction already exists.
582 * @param string $trxn_id
583 * @return bool|void
584 */
585 public function transactionExists($trxn_id) {
586 if (CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
587 [
588 1 => [$trxn_id, 'String'],
589 ])
590 ) {
591 return TRUE;
592 }
593 }
594
595 }