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