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