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_PayPalIPN
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 * Constructor function.
31 * @param array $inputData
32 * Contents of HTTP REQUEST.
34 * @throws CRM_Core_Exception
36 public function __construct($inputData) {
38 $params = (!empty($inputData['custom'])) ?
39 array_merge($inputData, json_decode($inputData['custom'], TRUE)) :
41 $this->setInputParameters($params);
42 parent
::__construct();
51 * @throws \CRM_Core_Exception
53 public function retrieve($name, $type, $abort = TRUE) {
54 $value = CRM_Utils_Type
::validate(CRM_Utils_Array
::value($name, $this->_inputParameters
), $type, FALSE);
55 if ($abort && $value === NULL) {
56 throw new CRM_Core_Exception("PayPalIPN: Could not find an entry for $name");
63 * @param CRM_Contribute_BAO_ContributionRecur $recur
64 * @param CRM_Contribute_BAO_Contribution $contribution
69 * @throws \CRM_Core_Exception
70 * @throws \CiviCRM_API3_Exception
72 public function recur($input, $recur, $contribution, $first) {
74 // make sure the invoice ids match
75 // make sure the invoice is valid and matches what we have in the contribution record
76 if ($recur->invoice_id
!= $input['invoice']) {
77 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request (RecurID: ' . $recur->id
. ').');
78 throw new CRM_Core_Exception("Failure: Invoice values dont match between database and IPN request");
81 $now = date('YmdHis');
83 // set transaction type
84 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate'));
85 switch ($this->getTrxnType()) {
87 $recur->create_date
= $now;
88 // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
90 $statusID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
91 $recur->id
, 'contribution_status_id'
93 if ($statusID != $contributionStatuses['In Progress']) {
94 $recur->contribution_status_id
= $contributionStatuses['Pending'];
96 $recur->processor_id
= $this->retrieve('subscr_id', 'String');
97 $recur->trxn_id
= $recur->processor_id
;
102 if ($recur->contribution_status_id
!= $contributionStatuses['Cancelled']) {
103 $recur->contribution_status_id
= $contributionStatuses['Completed'];
105 $recur->end_date
= $now;
109 case 'subscr_cancel':
110 $recur->contribution_status_id
= $contributionStatuses['Cancelled'];
111 $recur->cancel_date
= $now;
115 case 'subscr_failed':
116 $recur->contribution_status_id
= $contributionStatuses['Failed'];
117 $recur->modified_date
= $now;
121 case 'subscr_modify':
122 Civi
::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id
. ').');
123 echo "Failure: We do not handle modifications to subscriptions right now<p>";
128 if ($this->getTrxnType() !== 'subscr_payment') {
131 if ($input['paymentStatus'] !== 'Completed') {
132 Civi
::log()->debug('PayPalIPN: Ignore all IPN payments that are not completed');
133 echo 'Failure: Invalid parameters<p>';
137 $recur->start_date
= $now;
140 $recur->modified_date
= $now;
143 // make sure the contribution status is not done
144 // since order of ipn's is unknown
145 if ($recur->contribution_status_id
!= $contributionStatuses['Completed']) {
146 $recur->contribution_status_id
= $contributionStatuses['In Progress'];
151 // check if this contribution transaction is already processed
152 // if not create a contribution and then get it processed
153 $contribution = new CRM_Contribute_BAO_Contribution();
154 $contribution->trxn_id
= $input['trxn_id'];
155 if ($contribution->trxn_id
&& $contribution->find()) {
156 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id
. ')');
157 echo 'Success: Contribution has already been handled<p>';
161 if ($input['paymentStatus'] !== 'Completed') {
162 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
165 // In future moving to create pending & then complete, but this OK for now.
166 // Also consider accepting 'Failed' like other processors.
167 $input['contribution_status_id'] = $contributionStatuses['Completed'];
168 $input['original_contribution_id'] = $contribution->id
;
169 $input['contribution_recur_id'] = $recur->id
;
171 civicrm_api3('Contribution', 'repeattransaction', $input);
175 $this->single($input, $contribution, TRUE);
179 * @param array $input
180 * @param \CRM_Contribute_BAO_Contribution $contribution
184 * @throws \CRM_Core_Exception
185 * @throws \CiviCRM_API3_Exception
187 public function single($input, $contribution, $recur = FALSE) {
189 // make sure the invoice is valid and matches what we have in the contribution record
190 if ($contribution->invoice_id
!= $input['invoice']) {
191 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
192 echo "Failure: Invoice values dont match between database and IPN request<p>";
197 if ($contribution->total_amount
!= $input['amount']) {
198 Civi
::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
199 echo "Failure: Amount values dont match between database and IPN request<p>";
204 $contribution->total_amount
= $input['amount'];
207 // check if contribution is already completed, if so we ignore this ipn
208 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
209 if ($contribution->contribution_status_id
== $completedStatusId) {
210 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id
. ').');
211 echo 'Success: Contribution has already been handled<p>';
215 CRM_Contribute_BAO_Contribution
::completeOrder($input, $this->getContributionRecurID(), $contribution->id ??
NULL);
221 * @throws \API_Exception
222 * @throws \CiviCRM_API3_Exception
223 * @throws \Civi\API\Exception\UnauthorizedException
225 public function main() {
228 $component = $this->retrieve('module', 'String');
229 $input['component'] = $component;
231 $contributionID = $this->getContributionID();
232 $membershipID = $this->retrieve('membershipID', 'Integer', FALSE);
234 $this->getInput($input);
236 $paymentProcessorID = $this->getPayPalPaymentProcessorID($input, $this->getContributionRecurID());
238 Civi
::log()->debug('PayPalIPN: Received (ContactID: ' . $this->getContactID() . '; trxn_id: ' . $input['trxn_id'] . ').');
240 // Debugging related to possible missing membership linkage
241 if ($this->getContributionRecurID() && $this->retrieve('membershipID', 'Integer', FALSE)) {
242 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution($this->getContributionRecurID());
243 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
244 'contribution_id' => $templateContribution['id'],
245 'membership_id' => $membershipID,
247 $lineItems = civicrm_api3('LineItem', 'get', [
248 'contribution_id' => $templateContribution['id'],
249 'entity_id' => $membershipID,
250 'entity_table' => 'civicrm_membership',
252 Civi
::log()->debug('PayPalIPN: Received payment for membership ' . (int) $membershipID
253 . '. Original contribution was ' . (int) $contributionID . '. The template for this contribution is '
254 . $templateContribution['id'] . ' it is linked to ' . $membershipPayment['count']
255 . 'payments for this membership. It has ' . $lineItems['count'] . ' line items linked to this membership.'
256 . ' it is expected the original contribution will be linked by both entities to the membership.'
258 if (empty($membershipPayment['count']) && empty($lineItems['count'])) {
259 Civi
::log()->debug('PayPalIPN: Will attempt to compensate');
260 $input['membership_id'] = $this->retrieve('membershipID', 'Integer', FALSE);
263 $contribution = $this->getContribution();
265 $input['payment_processor_id'] = $paymentProcessorID;
267 if ($this->getContributionRecurID()) {
268 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
269 $contributionRecur->id
= $this->getContributionRecurID();
270 if (!$contributionRecur->find(TRUE)) {
271 throw new CRM_Core_Exception('Could not find contribution recur record');
273 // check if first contribution is completed, else complete first contribution
275 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
276 if ($contribution->contribution_status_id
== $completedStatusId) {
279 $this->recur($input, $contributionRecur, $contribution, $first);
280 if ($this->getFirstOrLastInSeriesStatus()) {
281 //send recurring Notification email for user
282 CRM_Contribute_BAO_ContributionPage
::recurringNotify(
284 $this->getFirstOrLastInSeriesStatus(),
291 $status = $input['paymentStatus'];
292 if ($status === 'Denied' ||
$status === 'Failed' ||
$status === 'Voided') {
293 Contribution
::update(FALSE)->setValues([
294 'cancel_date' => 'now',
295 'contribution_status_id:name' => 'Failed',
296 ])->addWhere('id', '=', $contributionID)->execute();
297 Civi
::log()->debug("Setting contribution status to Failed");
300 if ($status === 'Pending') {
301 Civi
::log()->debug('Returning since contribution status is Pending');
304 if ($status === 'Refunded' ||
$status === 'Reversed') {
305 Contribution
::update(FALSE)->setValues([
306 'cancel_date' => 'now',
307 'contribution_status_id:name' => 'Cancelled',
308 ])->addWhere('id', '=', $contributionID)->execute();
309 Civi
::log()->debug("Setting contribution status to Cancelled");
312 if ($status !== 'Completed') {
313 Civi
::log()->debug('Returning since contribution status is not handled');
316 $this->single($input, $contribution);
318 catch (CRM_Core_Exception
$e) {
319 Civi
::log()->debug($e->getMessage() . ' input {input}', ['input' => $input]);
320 echo 'Invalid or missing data';
325 * @param array $input
327 * @throws \CRM_Core_Exception
329 public function getInput(&$input) {
330 $billingID = CRM_Core_BAO_LocationType
::getBilling();
331 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
332 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
333 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
334 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
337 "first_name" => 'first_name',
338 "last_name" => 'last_name',
339 "street_address-{$billingID}" => 'address_street',
340 "city-{$billingID}" => 'address_city',
341 "state-{$billingID}" => 'address_state',
342 "postal_code-{$billingID}" => 'address_zip',
343 "country-{$billingID}" => 'address_country_code',
345 foreach ($lookup as $name => $paypalName) {
346 $value = $this->retrieve($paypalName, 'String', FALSE);
347 $input[$name] = $value ?
$value : NULL;
350 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
351 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
352 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
353 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
355 $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
356 if (!empty($paymentDate)) {
357 $receiveDateTime = new DateTime($paymentDate);
359 * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST
360 * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system
362 $input['receive_date'] = CRM_Utils_Date
::convertDateToLocalTime($receiveDateTime);
367 * Get PaymentProcessorID for PayPal
369 * @param array $input
370 * @param int|null $contributionRecurID
373 * @throws \CRM_Core_Exception
374 * @throws \CiviCRM_API3_Exception
376 public function getPayPalPaymentProcessorID(array $input, ?
int $contributionRecurID): int {
377 // First we try and retrieve from POST params
378 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
379 if (!empty($paymentProcessorID)) {
380 return $paymentProcessorID;
383 // Then we try and get it from recurring contribution ID
384 if ($contributionRecurID) {
385 $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
386 'id' => $contributionRecurID,
387 'return' => ['payment_processor_id'],
389 if (!empty($contributionRecur['payment_processor_id'])) {
390 return $contributionRecur['payment_processor_id'];
394 // This is an unreliable method as there could be more than one instance.
395 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
396 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
397 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
398 // & call completetransaction or call fail? (which may not exist yet).
400 Civi
::log()->warning('Unreliable method used to get payment_processor_id for PayPal IPN - this will cause problems if you have more than one instance');
401 // Then we try and retrieve based on business email ID
402 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name');
404 'user_name' => $this->retrieve('business', 'String', FALSE),
405 'payment_processor_type_id' => $paymentProcessorTypeID,
406 'is_test' => empty($input['is_test']) ?
0 : 1,
407 'options' => ['limit' => 1],
410 $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams);
411 if (empty($paymentProcessorID)) {
412 throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
414 return (int) $paymentProcessorID;
419 * @throws \CRM_Core_Exception
421 protected function getTrxnType() {
422 return $this->retrieve('txn_type', 'String');
426 * Get status code for first or last recurring in the series.
428 * If this is the first or last then return the status code, else
431 * @return string|null
432 * @throws \CRM_Core_Exception
434 protected function getFirstOrLastInSeriesStatus(): ?
string {
435 $subscriptionPaymentStatus = NULL;
436 if ($this->getTrxnType() === 'subscr_signup') {
437 return CRM_Core_Payment
::RECURRING_PAYMENT_START
;
439 if ($this->getTrxnType() === 'subscr_eot') {
440 return CRM_Core_Payment
::RECURRING_PAYMENT_END
;
446 * Get the recurring contribution ID.
450 * @throws \CRM_Core_Exception
452 protected function getContributionRecurID(): ?
int {
453 $id = $this->retrieve('contributionRecurID', 'Integer', FALSE);
454 return $id ?
(int) $id : NULL;
458 * Get Contribution ID.
462 * @throws \CRM_Core_Exception
464 protected function getContributionID(): int {
465 return (int) $this->retrieve('contributionID', 'Integer', TRUE);
469 * Get contact id from parameters.
473 * @throws \CRM_Core_Exception
475 protected function getContactID(): int {
476 return (int) $this->retrieve('contactID', 'Integer', TRUE);
480 * Get the contribution object.
482 * @return \CRM_Contribute_BAO_Contribution
483 * @throws \CRM_Core_Exception
485 protected function getContribution(): CRM_Contribute_BAO_Contribution
{
486 $contribution = new CRM_Contribute_BAO_Contribution();
487 $contribution->id
= $this->getContributionID();
488 if (!$contribution->find(TRUE)) {
489 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: "]);
491 if ($contribution->contact_id
!== $this->getContactID()) {
492 CRM_Core_Error
::debug_log_message("Contact ID in IPN not found but contact_id found in contribution.");
494 return $contribution;