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
;
15 * Class CRM_Core_Payment_BaseIPN.
17 class CRM_Core_Payment_BaseIPN
{
19 public static $_now = NULL;
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 * Only used by AuthorizeNetIPN.
35 protected $_isRecurring = FALSE;
38 * Only used by AuthorizeNetIPN.
44 protected $_isFirstOrLastRecurringPayment = FALSE;
49 public function __construct() {
50 self
::$_now = date('YmdHis');
54 * Store input array on the class.
56 * @param array $parameters
58 * @throws CRM_Core_Exception
60 public function setInputParameters($parameters) {
61 if (!is_array($parameters)) {
62 throw new CRM_Core_Exception('Invalid input parameters');
64 $this->_inputParameters
= $parameters;
68 * Validate incoming data.
70 * This function is intended to ensure that incoming data matches
71 * It provides a form of pseudo-authentication - by checking the calling fn already knows
72 * the correct contact id & contribution id (this can be problematic when that has changed in
73 * the meantime for transactions that are delayed & contacts are merged in-between. e.g
74 * Paypal allows you to resend Instant Payment Notifications if you, for example, moved site
75 * and didn't update your IPN URL.
78 * Interpreted values from the values returned through the IPN.
80 * More interpreted values (ids) from the values returned through the IPN.
81 * @param array $objects
82 * An empty array that will be populated with loaded object.
83 * @param bool $required
84 * Boolean Return FALSE if the relevant objects don't exist.
85 * @param int $paymentProcessorID
86 * Id of the payment processor ID in use.
90 public function validateData($input, &$ids, &$objects, $required = TRUE, $paymentProcessorID = NULL) {
92 // Check if the contribution exists
93 // make sure contribution exists and is valid
94 $contribution = new CRM_Contribute_BAO_Contribution();
95 $contribution->id
= $ids['contribution'];
96 if (!$contribution->find(TRUE)) {
97 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)]);
100 // make sure contact exists and is valid
101 // use the contact id from the contribution record as the id in the IPN may not be valid anymore.
102 $contact = new CRM_Contact_BAO_Contact();
103 $contact->id
= $contribution->contact_id
;
104 $contact->find(TRUE);
105 if ($contact->id
!= $ids['contact']) {
106 // 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
107 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");
108 echo "WARNING: Could not find contact record: {$ids['contact']}<p>";
109 $ids['contact'] = $contribution->contact_id
;
112 if (!empty($ids['contributionRecur'])) {
113 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
114 $contributionRecur->id
= $ids['contributionRecur'];
115 if (!$contributionRecur->find(TRUE)) {
116 CRM_Core_Error
::debug_log_message("Could not find contribution recur record: {$ids['ContributionRecur']} in IPN request: " . print_r($input, TRUE));
117 echo "Failure: Could not find contribution recur record: {$ids['ContributionRecur']}<p>";
122 $objects['contact'] = &$contact;
123 $objects['contribution'] = &$contribution;
125 // CRM-19478: handle oddity when p=null is set in place of contribution page ID,
126 if (!empty($ids['contributionPage']) && !is_numeric($ids['contributionPage'])) {
127 // We don't need to worry if about removing contribution page id as it will be set later in
128 // CRM_Contribute_BAO_Contribution::loadRelatedObjects(..) using $objects['contribution']->contribution_page_id
129 unset($ids['contributionPage']);
132 if (!$this->loadObjects($input, $ids, $objects, $required, $paymentProcessorID)) {
139 * Load objects related to contribution.
141 * @input array information from Payment processor
143 * @param array $input
145 * @param array $objects
146 * @param bool $required
147 * @param int $paymentProcessorID
150 * @throws \CRM_Core_Exception
152 public function loadObjects($input, &$ids, &$objects, $required, $paymentProcessorID) {
153 $contribution = &$objects['contribution'];
154 $ids['paymentProcessor'] = $paymentProcessorID;
155 $success = $contribution->loadRelatedObjects($input, $ids);
156 if ($required && empty($contribution->_relatedObjects
['paymentProcessor'])) {
157 throw new CRM_Core_Exception("Could not find payment processor for contribution record: " . $contribution->id
);
159 $objects = array_merge($objects, $contribution->_relatedObjects
);
164 * Set contribution to failed.
166 * @param array $objects
169 * @throws \CiviCRM_API3_Exception|\CRM_Core_Exception
171 public function failed($objects) {
172 $contribution = &$objects['contribution'];
174 if (!empty($objects['membership'])) {
175 $memberships = &$objects['membership'];
176 if (is_numeric($memberships)) {
177 $memberships = [$objects['membership']];
181 $addLineItems = empty($contribution->id
);
182 $participant = &$objects['participant'];
183 $contribution->contribution_status_id
= CRM_Core_PseudoConstant
::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Failed');
184 $contribution->save();
186 // Add line items for recurring payments.
187 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
188 CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($objects['contributionRecur']->id
, $contribution);
191 if (!empty($memberships)) {
192 foreach ($memberships as $membership) {
193 // @fixme Should we cancel only Pending memberships? per cancelled()
194 $this->cancelMembership($membership, $membership->status_id
, FALSE);
199 $this->cancelParticipant($participant->id
);
202 Civi
::log()->debug("Setting contribution status to Failed");
207 * Handled pending contribution status.
211 * @param array $objects
212 * @param object $transaction
216 public function pending(&$objects, &$transaction) {
217 CRM_Core_Error
::deprecatedFunctionWarning('This function will be removed at some point');
218 $transaction->commit();
219 Civi
::log()->debug('Returning since contribution status is Pending');
220 echo 'Success: Returning since contribution status is pending<p>';
225 * Process cancelled payment outcome.
227 * @deprecated The intended replacement code is
229 * Contribution::update(FALSE)->setValues([
230 * 'cancel_date' => 'now',
231 * 'contribution_status_id:name' => 'Cancelled',
232 * ])->addWhere('id', '=', $contribution->id)->execute();
234 * @param array $objects
237 * @throws \CiviCRM_API3_Exception|\CRM_Core_Exception
239 public function cancelled($objects) {
240 CRM_Core_Error
::deprecatedFunctionWarning('Use Contribution create api to cancel the contribution');
241 $contribution = &$objects['contribution'];
243 if (empty($contribution->id
)) {
244 // This code is believed to be unreachable.
245 // this entire function is due to be deprecated in the near future so
246 // this code will live in a deprecated function until it gets removed.
247 $addLineItems = TRUE;
249 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
250 'labelColumn' => 'name',
253 $contribution->contribution_status_id
= $contributionStatuses['Cancelled'];
254 $contribution->cancel_date
= self
::$_now;
255 $contribution->save();
256 // Add line items for recurring payments.
257 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
&& $addLineItems) {
258 CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($objects['contributionRecur']->id
, $contribution);
261 if (!empty($objects['membership'])) {
262 $memberships = &$objects['membership'];
263 if (is_numeric($memberships)) {
264 $memberships = [$objects['membership']];
267 if (!empty($memberships)) {
268 foreach ($memberships as $membership) {
270 $this->cancelMembership($membership, $membership->status_id
);
274 $participant = &$objects['participant'];
277 $this->cancelParticipant($participant->id
);
281 Contribution
::update(FALSE)->setValues([
282 'cancel_date' => 'now',
283 'contribution_status_id:name' => 'Cancelled',
284 ])->addWhere('id', '=', $contribution->id
)->execute();
287 Civi
::log()->debug("Setting contribution status to Cancelled");
292 * Rollback unhandled outcomes.
296 * @param array $objects
297 * @param CRM_Core_Transaction $transaction
301 public function unhandled(&$objects, &$transaction) {
302 CRM_Core_Error
::deprecatedFunctionWarning('This function will be removed at some point');
303 $transaction->rollback();
304 Civi
::log()->debug('Returning since contribution status is not handled');
305 echo 'Failure: contribution status is not handled<p>';
310 * Logic to cancel a participant record when the related contribution changes to failed/cancelled.
311 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
315 * @param $participantID
317 * @throws \CiviCRM_API3_Exception
319 private function cancelParticipant($participantID) {
320 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
321 $participantParams['id'] = $participantID;
322 $participantParams['status_id'] = 'Cancelled';
323 civicrm_api3('Participant', 'create', $participantParams);
327 * Logic to cancel a membership record when the related contribution changes to failed/cancelled.
328 * @todo This is part of a bigger refactor for dev/core/issues/927 - "duplicate" functionality exists in CRM_Contribute_BAO_Contribution::cancel()
329 * @param \CRM_Member_BAO_Membership $membership
330 * @param int $membershipStatusID
331 * @param boolean $onlyCancelPendingMembership
332 * Do we only cancel pending memberships? OR memberships in any status? (see CRM-18688)
333 * @fixme Historically failed() cancelled membership in any status, cancelled() cancelled only pending memberships so we retain that behaviour for now.
336 private function cancelMembership($membership, $membershipStatusID, $onlyCancelPendingMembership = TRUE) {
337 CRM_Core_Error
::deprecatedFunctionWarning('use the api');
338 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
339 // Cancel only Pending memberships
340 $pendingMembershipStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
341 if (($membershipStatusID == $pendingMembershipStatusId) ||
($onlyCancelPendingMembership == FALSE)) {
342 $cancelledMembershipStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Cancelled');
344 $membership->status_id
= $cancelledMembershipStatusId;
347 $params = ['status_id' => $cancelledMembershipStatusId];
348 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $params);
350 // @todo Convert the above to API
351 // $membershipParams = [
352 // 'id' => $membership->id,
353 // 'status_id' => $cancelledMembershipStatusId,
355 // civicrm_api3('Membership', 'create', $membershipParams);
356 // CRM_Member_BAO_Membership::updateRelatedMemberships($membershipParams['id'], ['status_id' => $cancelledMembershipStatusId]);
364 * Jumbled up function.
366 * The purpose of this function is to transition a pending transaction to Completed including updating any
369 * It has been overloaded to also add recurring transactions to the database, cloning the original transaction and
370 * updating related entities.
372 * It is recommended to avoid calling this function directly and call the api functions:
373 * - contribution.completetransaction
374 * - contribution.repeattransaction
376 * These functions are the focus of testing efforts and more accurately reflect the division of roles
377 * (the job of the IPN class is to determine the outcome, transaction id, invoice id & to validate the source
378 * and from there it should be possible to pass off transaction management.)
380 * This function has been problematic for some time but there are now several tests via the api_v3_Contribution test
381 * and the Paypal & Authorize.net IPN tests so any refactoring should be done in conjunction with those.
383 * This function needs to have the 'body' moved to the CRM_Contribute_BAO_Contribute class and to undergo
384 * refactoring to separate the complete transaction and repeat transaction functionality into separate functions with
385 * a shared function that updates related components.
387 * Note that it is not necessary payment processor extension to implement an IPN class now. In general the code on the
388 * IPN class is better accessed through the api which de-jumbles it a bit.
390 * e.g the payment class can have a function like (based on Omnipay extension):
392 * public function handlePaymentNotification() {
393 * $response = $this->getValidatedOutcome();
394 * if ($response->isSuccessful()) {
396 * // @todo check if it is a repeat transaction & call repeattransaction instead.
397 * civicrm_api3('contribution', 'completetransaction', array('id' => $this->transaction_id));
399 * catch (CiviCRM_API3_Exception $e) {
400 * if (!stristr($e->getMessage(), 'Contribution already completed')) {
401 * $this->handleError('error', $this->transaction_id . $e->getMessage(), 'ipn_completion', 9000, 'An error may
402 * have occurred. Please check your receipt is correct');
403 * $this->redirectOrExit('success');
405 * elseif ($this->transaction_id) {
406 * civicrm_api3('contribution', 'create', array('id' => $this->transaction_id, 'contribution_status_id' =>
410 * @param array $input
412 * @param array $objects
414 * @throws \CRM_Core_Exception
415 * @throws \CiviCRM_API3_Exception
417 public function completeTransaction($input, $ids, $objects) {
418 CRM_Core_Error
::deprecatedFunctionWarning('Use Payment.create api');
419 CRM_Contribute_BAO_Contribution
::completeOrder($input, [
420 'related_contact' => $ids['related_contact'] ??
NULL,
421 'participant' => !empty($objects['participant']) ?
$objects['participant']->id
: NULL,
422 'contributionRecur' => !empty($objects['contributionRecur']) ?
$objects['contributionRecur']->id
: NULL,
423 ], $objects['contribution']);
428 * Get site billing ID.
434 public function getBillingID(&$ids) {
435 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_LocationType::getBilling()');
436 $ids['billing'] = CRM_Core_BAO_LocationType
::getBilling();
437 if (!$ids['billing']) {
438 CRM_Core_Error
::debug_log_message(ts('Please set a location type of %1', [1 => 'Billing']));
439 echo "Failure: Could not find billing location type<p>";
448 * @todo confirm this function is not being used by any payment processor outside core & remove.
450 * Note that the compose message part has been moved to contribution
451 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it
453 * @param array $input
454 * Incoming data from Payment processor.
456 * Related object IDs.
457 * @param array $objects
459 * @throws \CiviCRM_API3_Exception
461 public function sendMail($input, $ids, $objects) {
462 CRM_Core_Error
::deprecatedFunctionWarning('this should be done via completetransaction api');
463 civicrm_api3('Contribution', 'sendconfirmation', [
464 'id' => $objects['contribution']->id
,