3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
12 use Civi\Api4\Contribution
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 class CRM_Core_Payment_PayPalProIPN
extends CRM_Core_Payment_BaseIPN
{
22 * Input parameters from payment processor. Store these so that
23 * the code does not need to keep retrieving from the http request
26 protected $_inputParameters = [];
29 * Store for the variables from the invoice string.
32 protected $_invoiceData = [];
35 * Is this a payment express transaction.
38 protected $_isPaymentExpress = FALSE;
41 * Recurring contribution ID.
45 protected $contributionRecurID;
48 * Recurring contribution object.
50 * @var \CRM_Contribute_BAO_ContributionRecur
52 protected $contributionRecurObject;
60 protected $contributionID;
63 * Get the recurring contribution ID, if any.
67 * @throws \CRM_Core_Exception
69 public function getContributionRecurID(): ?
int {
70 if (!$this->contributionRecurID
&& $this->getValue('r', FALSE)) {
71 $this->contributionRecurID
= (int) $this->getValue('r', FALSE);
73 return $this->contributionRecurID
;
77 * Get the relevant contribution ID.
79 * This is the contribution being paid or the original in the
84 * @throws \CRM_Core_Exception
86 protected function getContributionID(): int {
87 if (!$this->contributionID
&& $this->getValue('b', TRUE)) {
88 $this->contributionID
= (int) $this->getValue('b', TRUE);
90 return $this->contributionID
;
94 * @param int|null $contributionRecurID
96 public function setContributionRecurID(?
int $contributionRecurID): void
{
97 $this->contributionRecurID
= $contributionRecurID;
101 * Set contribution ID.
103 * @param int $contributionID
105 public function setContributionID(int $contributionID): void
{
106 $this->contributionID
= $contributionID;
112 * Are we dealing with an event an 'anything else' (contribute).
116 protected $_component = 'contribute';
119 * Constructor function.
121 * @param array $inputData
122 * Contents of HTTP REQUEST.
124 * @throws CRM_Core_Exception
126 public function __construct($inputData) {
127 $this->setInputParameters($inputData);
128 $this->setInvoiceData();
129 parent
::__construct();
133 * get the values from the rp_invoice_id string.
135 * @param string $name
136 * E.g. i, values are stored in the string with letter codes.
138 * Throw exception if not found
140 * @throws CRM_Core_Exception
143 public function getValue($name, $abort = TRUE) {
144 if ($abort && empty($this->_invoiceData
[$name])) {
145 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
148 return $this->_invoiceData
[$name] ??
NULL;
153 * Set $this->_invoiceData from the input array
155 public function setInvoiceData() {
156 if (empty($this->_inputParameters
['rp_invoice_id'])) {
157 $this->_isPaymentExpress
= TRUE;
160 $rpInvoiceArray = explode('&', $this->_inputParameters
['rp_invoice_id']);
161 // for clarify let's also store without the single letter unreadable
162 //@todo after more refactoring we might ditch storing the one letter stuff
167 'b' => 'contribution_id',
168 'r' => 'contribution_recur_id',
169 'p' => 'participant_id',
172 foreach ($rpInvoiceArray as $rpInvoiceValue) {
173 $rpValueArray = explode('=', $rpInvoiceValue);
174 $this->_invoiceData
[$rpValueArray[0]] = $rpValueArray[1];
175 $this->_inputParameters
[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
176 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
177 // alphabet with more letters.
178 // the mode will always be resolved before the mystery p is reached
179 if ($rpValueArray[1] === 'contribute') {
180 $mapping['p'] = 'contribution_page_id';
183 if (empty($this->_inputParameters
['component'])) {
184 $this->_isPaymentExpress
= TRUE;
189 * @param string $name
190 * Of variable to return.
191 * @param string $type
195 * @param string $location
200 * @throws CRM_Core_Exception
203 public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
204 $value = CRM_Utils_Type
::validate(
205 CRM_Utils_Array
::value($name, $this->_inputParameters
),
209 if ($abort && $value === NULL) {
210 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
216 * Process recurring contributions.
218 * @param array $input
219 * @param \CRM_Contribute_BAO_ContributionRecur $recur
220 * @param \CRM_Contribute_BAO_Contribution $contribution
223 * @throws \API_Exception
224 * @throws \CRM_Core_Exception
225 * @throws \CiviCRM_API3_Exception
226 * @throws \Civi\API\Exception\UnauthorizedException
228 public function recur($input, $recur, $contribution, $first) {
229 if (!isset($input['txnType'])) {
230 Civi
::log()->debug('PayPalProIPN: Could not find txn_type in input request.');
231 echo 'Failure: Invalid parameters<p>';
235 // make sure the invoice ids match
236 // make sure the invoice is valid and matches what we have in
237 // the contribution record
238 if ($recur->invoice_id
!= $input['invoice']) {
239 Civi
::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id
. ' input is ' . $input['invoice']);
240 echo 'Failure: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id
. " input is " . $input['invoice'];
244 $now = date('YmdHis');
246 $sendNotification = FALSE;
247 $subscriptionPaymentStatus = NULL;
248 //List of Transaction Type
250 recurring_payment_profile_created RP Profile Created
251 recurring_payment RP Successful Payment
252 recurring_payment_failed RP Failed Payment
253 recurring_payment_profile_cancel RP Profile Cancelled
254 recurring_payment_expired RP Profile Expired
255 recurring_payment_skipped RP Profile Skipped
256 recurring_payment_outstanding_payment RP Successful Outstanding Payment
257 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
258 recurring_payment_suspended RP Profile Suspended
259 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
262 //set transaction type
263 $txnType = $this->retrieve('txn_type', 'String');
264 //Changes for paypal pro recurring payment
265 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate'));
267 case 'recurring_payment_profile_created':
268 if (in_array($recur->contribution_status_id
, [
269 $contributionStatuses['Pending'],
270 $contributionStatuses['In Progress'],
272 && !empty($recur->processor_id
)
274 echo "already handled";
277 $recur->create_date
= $now;
278 $recur->contribution_status_id
= $contributionStatuses['Pending'];
279 $recur->processor_id
= $this->retrieve('recurring_payment_id', 'String');
280 $recur->trxn_id
= $recur->processor_id
;
281 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
282 $sendNotification = TRUE;
285 case 'recurring_payment':
287 $recur->start_date
= $now;
290 if ($input['paymentStatus'] !== 'Completed') {
291 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
294 // In future moving to create pending & then complete, but this OK for now.
295 // Also consider accepting 'Failed' like other processors.
296 $input['contribution_status_id'] = $contributionStatuses['Completed'];
297 $input['invoice_id'] = md5(uniqid(rand(), TRUE));
298 $input['original_contribution_id'] = $this->getContributionID();
299 $input['contribution_recur_id'] = $this->getContributionRecurID();
301 civicrm_api3('Contribution', 'repeattransaction', $input);
305 //contribution installment is completed
306 if ($this->retrieve('profile_status', 'String') == 'Expired') {
307 if (!empty($recur->end_date
)) {
308 echo "already handled";
311 $recur->contribution_status_id
= $contributionStatuses['Completed'];
312 $recur->end_date
= $now;
313 $sendNotification = TRUE;
314 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
317 // make sure the contribution status is not done
318 // since order of ipn's is unknown
319 if ($recur->contribution_status_id
!= $contributionStatuses['Completed']) {
320 $recur->contribution_status_id
= $contributionStatuses['In Progress'];
327 if ($sendNotification) {
328 //send recurring Notification email for user
329 CRM_Contribute_BAO_ContributionPage
::recurringNotify(
330 $this->getContributionID(),
331 $subscriptionPaymentStatus,
336 if ($txnType !== 'recurring_payment') {
340 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
341 $contribution->receive_date
= !empty($input['payment_date']) ?
date('YmdHis', strtotime($input['payment_date'])) : $now;
343 $this->single($input, $contribution, TRUE, $first);
347 * @param array $input
348 * @param \CRM_Contribute_BAO_Contribution $contribution
353 * @throws \API_Exception
354 * @throws \CRM_Core_Exception
355 * @throws \CiviCRM_API3_Exception
356 * @throws \Civi\API\Exception\UnauthorizedException
358 public function single($input, $contribution, $recur = FALSE, $first = FALSE) {
360 // make sure the invoice is valid and matches what we have in the contribution record
361 if ((!$recur) ||
($recur && $first)) {
362 if ($contribution->invoice_id
!= $input['invoice']) {
363 Civi
::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request.');
364 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id
. " and input is " . $input['invoice'];
369 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
373 if ($contribution->total_amount
!= $input['amount']) {
374 Civi
::log()->debug('PayPalProIPN: Amount values dont match between database and IPN request.');
375 echo "Failure: Amount values dont match between database and IPN request<p>";
380 $contribution->total_amount
= $input['amount'];
383 $status = $input['paymentStatus'];
384 if ($status === 'Denied' ||
$status === 'Failed' ||
$status === 'Voided') {
385 Contribution
::update(FALSE)->setValues([
386 'cancel_date' => 'now',
387 'contribution_status_id:name' => 'Failed',
388 ])->addWhere('id', '=', $contribution->id
)->execute();
389 Civi
::log()->debug("Setting contribution status to Failed");
392 if ($status === 'Pending') {
393 Civi
::log()->debug('Returning since contribution status is Pending');
396 if ($status === 'Refunded' ||
$status === 'Reversed') {
397 Contribution
::update(FALSE)->setValues([
398 'cancel_date' => 'now',
399 'contribution_status_id:name' => 'Cancelled',
400 ])->addWhere('id', '=', $contribution->id
)->execute();
401 Civi
::log()->debug("Setting contribution status to Cancelled");
404 elseif ($status !== 'Completed') {
405 Civi
::log()->debug('Returning since contribution status is not handled');
409 // check if contribution is already completed, if so we ignore this ipn
410 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
411 if ($contribution->contribution_status_id
== $completedStatusId) {
412 Civi
::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
413 echo 'Success: Contribution has already been handled<p>';
417 CRM_Contribute_BAO_Contribution
::completeOrder($input, $this->getContributionRecurID(), $contribution->id ??
NULL);
421 * Gets PaymentProcessorID for PayPal
425 public function getPayPalPaymentProcessorID() {
426 // This is an unreliable method as there could be more than one instance.
427 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
428 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
429 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
430 // & call completetransaction or call fail? (which may not exist yet).
432 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');
434 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
435 'PayPal', 'id', 'name'
437 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
439 'options' => ['limit' => 1],
440 'payment_processor_type_id' => $paymentProcessorTypeID,
447 * This is the main function to call. It should be sufficient to instantiate the class
448 * (with the input parameters) & call this & all will be done
450 * @todo the references to POST throughout this class need to be removed
453 public function main() {
454 CRM_Core_Error
::debug_var('GET', $_GET, TRUE, TRUE);
455 CRM_Core_Error
::debug_var('POST', $_POST, TRUE, TRUE);
458 if ($this->_isPaymentExpress
) {
459 $this->handlePaymentExpress();
462 $this->_component
= $input['component'] = self
::getValue('m');
463 $input['invoice'] = self
::getValue('i', TRUE);
464 // get the contribution and contact ids from the GET params
465 $ids['contact'] = self
::getValue('c', TRUE);
466 $ids['contribution'] = $this->getContributionID();
468 $this->getInput($input);
470 if ($this->_component
== 'event') {
471 $ids['event'] = self
::getValue('e', TRUE);
472 $ids['participant'] = self
::getValue('p', TRUE);
473 $ids['contributionRecur'] = $this->getContributionRecurID();
476 // get the optional ids
477 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
478 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
479 $ids['membership'] = self
::retrieve('membershipID', 'Integer', 'GET', FALSE);
480 $ids['contributionRecur'] = $this->getContributionRecurID();
481 $ids['contributionPage'] = self
::getValue('p', FALSE);
482 $ids['related_contact'] = self
::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
483 $ids['onbehalf_dupe_alert'] = self
::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
486 if (!$ids['membership'] && $this->getContributionRecurID()) {
489 FROM civicrm_membership m
490 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
491 WHERE m.contribution_recur_id = %2
494 1 => [$ids['contribution'], 'Integer'],
495 2 => [$this->getContributionRecurID(), 'Integer'],
497 if ($membershipId = CRM_Core_DAO
::singleValueQuery($sql, $sqlParams)) {
498 $ids['membership'] = $membershipId;
502 $paymentProcessorID = CRM_Utils_Array
::value('processor_id', $this->_inputParameters
);
503 if (!$paymentProcessorID) {
504 $paymentProcessorID = self
::getPayPalPaymentProcessorID();
507 // Check if the contribution exists
508 // make sure contribution exists and is valid
509 $contribution = new CRM_Contribute_BAO_Contribution();
510 $contribution->id
= $ids['contribution'];
511 if (!$contribution->find(TRUE)) {
512 throw new CRM_Core_Exception('Failure: Could not find contribution record for ' . (int) $contribution->id
, NULL, ['context' => "Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE)]);
515 // make sure contact exists and is valid
516 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
517 $contact = new CRM_Contact_BAO_Contact();
518 $contact->id
= $contribution->contact_id
;
519 $contact->find(TRUE);
520 if ($contact->id
!= $ids['contact']) {
521 // If the ids do not match then it is possible the contact id in the IPN has been merged into another contact which is why we use the contact_id from the contribution
522 CRM_Core_Error
::debug_log_message("Contact ID in IPN {$ids['contact']} not found but contact_id found in contribution {$contribution->contact_id} used instead");
523 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
524 $ids['contact'] = $contribution->contact_id
;
527 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
528 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
529 // We don't need to worry if about removing contribution page id as it will be set later in
530 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
531 unset($ids['contributionPage']);
534 $ids['paymentProcessor'] = $paymentProcessorID;
535 $contribution->loadRelatedObjects($input, $ids);
537 $input['payment_processor_id'] = $paymentProcessorID;
539 if ($this->getContributionRecurID()) {
540 $contributionRecur = $this->getContributionRecurObject();
541 // check if first contribution is completed, else complete first contribution
543 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
544 if ($contribution->contribution_status_id
== $completedStatusId) {
547 $this->recur($input, $contributionRecur, $contribution, $first);
551 $this->single($input, $contribution, FALSE, FALSE);
553 catch (CRM_Core_Exception
$e) {
554 Civi
::log()->debug($e->getMessage() . ' input {input}', ['input' => $input]);
555 echo 'Invalid or missing data';
560 * @param array $input
563 * @throws CRM_Core_Exception
565 public function getInput(&$input) {
566 $billingID = CRM_Core_BAO_LocationType
::getBilling();
568 $input['txnType'] = self
::retrieve('txn_type', 'String', 'POST', FALSE);
569 $input['paymentStatus'] = self
::retrieve('payment_status', 'String', 'POST', FALSE);
571 $input['amount'] = self
::retrieve('mc_gross', 'Money', 'POST', FALSE);
572 $input['reasonCode'] = self
::retrieve('ReasonCode', 'String', 'POST', FALSE);
575 "first_name" => 'first_name',
576 "last_name" => 'last_name',
577 "street_address-{$billingID}" => 'address_street',
578 "city-{$billingID}" => 'address_city',
579 "state-{$billingID}" => 'address_state',
580 "postal_code-{$billingID}" => 'address_zip',
581 "country-{$billingID}" => 'address_country_code',
583 foreach ($lookup as $name => $paypalName) {
584 $value = self
::retrieve($paypalName, 'String', 'POST', FALSE);
585 $input[$name] = $value ?
$value : NULL;
588 $input['is_test'] = self
::retrieve('test_ipn', 'Integer', 'POST', FALSE);
589 $input['fee_amount'] = self
::retrieve('mc_fee', 'Money', 'POST', FALSE);
590 $input['net_amount'] = self
::retrieve('settle_amount', 'Money', 'POST', FALSE);
591 $input['trxn_id'] = self
::retrieve('txn_id', 'String', 'POST', FALSE);
592 $input['payment_date'] = $input['receive_date'] = self
::retrieve('payment_date', 'String', 'POST', FALSE);
593 $input['total_amount'] = $input['amount'];
597 * Handle payment express IPNs.
599 * For one off IPNS no actual response is required
600 * Recurring is more difficult as we have limited confirmation material
601 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
603 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
604 * then the quasi security of the ids array might be required - although better to
605 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
606 * but let's assume knowledge on invoice id & schedule is enough for now esp
607 * for donations only contribute is handled
609 * @throws \CRM_Core_Exception
611 public function handlePaymentExpress() {
612 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
614 // also note that a lot of the complexity above could be removed if we used
615 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
616 // as membership id etc can be derived by the load objects fn
617 $objects = $ids = $input = [];
619 $input['invoice'] = self
::getValue('i', FALSE);
620 //Avoid return in case of unit test.
621 if (empty($input['invoice']) && empty($this->_inputParameters
['is_unit_test'])) {
624 $input['txnType'] = $this->retrieve('txn_type', 'String');
625 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
626 'return' => 'contact_id, id, payment_processor_id',
627 'invoice_id' => $input['invoice'],
629 $this->setContributionRecurID((int) $contributionRecur['id']);
631 if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
632 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
635 $this->getInput($input, $ids);
636 if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
637 throw new CRM_Core_Exception('This transaction has already been processed');
640 $ids['contact'] = $contributionRecur['contact_id'];
641 $ids['contributionRecur'] = $this->getContributionRecurID();
642 $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
644 $this->setContributionID((int) $result['id']);
645 $ids['contribution'] = $this->getContributionID();
646 //@todo hardcoding 'pending' for now
647 $pendingStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
648 if ($result['contribution_status_id'] == $pendingStatusId) {
651 // arg api won't get this - fix it
652 $ids['contributionPage'] = CRM_Core_DAO
::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", [
654 $ids['contribution'],
658 // only handle component at this stage - not terribly sure how a recurring event payment would arise
659 // & suspec main function may be a victom of copy & paste
660 // membership would be an easy add - but not relevant to my customer...
661 $this->_component
= $input['component'] = 'contribute';
662 $input['trxn_date'] = date('Y-m-d H:i:s', strtotime(self
::retrieve('time_created', 'String')));
663 $paymentProcessorID = $contributionRecur['payment_processor_id'];
665 // Check if the contribution exists
666 // make sure contribution exists and is valid
667 $contribution = new CRM_Contribute_BAO_Contribution();
668 $contribution->id
= $this->getContributionID();
669 if (!$contribution->find(TRUE)) {
670 throw new CRM_Core_Exception('Failure: Could not find contribution record for ' . (int) $contribution->id
, NULL, ['context' => "Could not find contribution record: {$contribution->id} in IPN request: " . print_r($input, TRUE)]);
673 $objects['contribution'] = &$contribution;
675 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
676 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
677 // We don't need to worry if about removing contribution page id as it will be set later in
678 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
679 unset($ids['contributionPage']);
682 $contribution = &$objects['contribution'];
683 $ids['paymentProcessor'] = $paymentProcessorID;
684 $contribution->loadRelatedObjects($input, $ids);
685 $objects = array_merge($objects, $contribution->_relatedObjects
);
687 $this->recur($input, $this->getContributionRecurObject(), $objects['contribution'], $isFirst);
691 * Function check if transaction already exists.
692 * @param string $trxn_id
695 public function transactionExists($trxn_id) {
696 if (CRM_Core_DAO
::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
698 1 => [$trxn_id, 'String'],
706 * Get the recurring contribution object.
708 * @return \CRM_Contribute_BAO_ContributionRecur
709 * @throws \CRM_Core_Exception
711 protected function getContributionRecurObject(): CRM_Contribute_BAO_ContributionRecur
{
712 if (!$this->contributionRecurObject
) {
713 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
714 $contributionRecur->id
= $this->getContributionRecurID();
715 if (!$contributionRecur->find(TRUE)) {
716 throw new CRM_Core_Exception('Failure: Could not find contribution recur record');
718 return $this->contributionRecurObject
= $contributionRecur;
720 return $this->contributionRecurObject
;