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