3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2020
34 class CRM_Core_Payment_PayPalIPN
extends CRM_Core_Payment_BaseIPN
{
36 public static $_paymentProcessor = NULL;
39 * Input parameters from payment processor. Store these so that
40 * the code does not need to keep retrieving from the http request
43 protected $_inputParameters = [];
46 * Constructor function.
48 * @param array $inputData
49 * Contents of HTTP REQUEST.
51 * @throws CRM_Core_Exception
53 public function __construct($inputData) {
55 $params = (!empty($inputData['custom'])) ?
56 array_merge($inputData, json_decode($inputData['custom'], TRUE)) :
58 $this->setInputParameters($params);
59 parent
::__construct();
68 * @throws \CRM_Core_Exception
70 public function retrieve($name, $type, $abort = TRUE) {
71 $value = CRM_Utils_Type
::validate(CRM_Utils_Array
::value($name, $this->_inputParameters
), $type, FALSE);
72 if ($abort && $value === NULL) {
73 Civi
::log()->debug("PayPalIPN: Could not find an entry for $name");
74 echo "Failure: Missing Parameter<p>" . CRM_Utils_Type
::escape($name, 'String');
75 throw new CRM_Core_Exception("PayPalIPN: Could not find an entry for $name");
83 * @param array $objects
88 * @throws \CRM_Core_Exception
89 * @throws \CiviCRM_API3_Exception
91 public function recur(&$input, &$ids, &$objects, $first) {
92 if (!isset($input['txnType'])) {
93 Civi
::log()->debug('PayPalIPN: Could not find txn_type in input request');
94 echo "Failure: Invalid parameters<p>";
98 if ($input['txnType'] == 'subscr_payment' &&
99 $input['paymentStatus'] != 'Completed'
101 Civi
::log()->debug('PayPalIPN: Ignore all IPN payments that are not completed');
102 echo "Failure: Invalid parameters<p>";
106 $recur = &$objects['contributionRecur'];
108 // make sure the invoice ids match
109 // make sure the invoice is valid and matches what we have in the contribution record
110 if ($recur->invoice_id
!= $input['invoice']) {
111 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request (RecurID: ' . $recur->id
. ').');
112 echo "Failure: Invoice values dont match between database and IPN request<p>";
116 $now = date('YmdHis');
118 // fix dates that already exist
119 $dates = ['create', 'start', 'end', 'cancel', 'modified'];
120 foreach ($dates as $date) {
121 $name = "{$date}_date";
123 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
126 $sendNotification = FALSE;
127 $subscriptionPaymentStatus = NULL;
128 // set transaction type
129 $txnType = $this->retrieve('txn_type', 'String');
130 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate'));
132 case 'subscr_signup':
133 $recur->create_date
= $now;
134 // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
136 $statusID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
137 $recur->id
, 'contribution_status_id'
139 if ($statusID != $contributionStatuses['In Progress']) {
140 $recur->contribution_status_id
= $contributionStatuses['Pending'];
142 $recur->processor_id
= $this->retrieve('subscr_id', 'String');
143 $recur->trxn_id
= $recur->processor_id
;
144 $sendNotification = TRUE;
145 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
149 if ($recur->contribution_status_id
!= $contributionStatuses['Cancelled']) {
150 $recur->contribution_status_id
= $contributionStatuses['Completed'];
152 $recur->end_date
= $now;
153 $sendNotification = TRUE;
154 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
157 case 'subscr_cancel':
158 $recur->contribution_status_id
= $contributionStatuses['Cancelled'];
159 $recur->cancel_date
= $now;
162 case 'subscr_failed':
163 $recur->contribution_status_id
= $contributionStatuses['Failed'];
164 $recur->modified_date
= $now;
167 case 'subscr_modify':
168 Civi
::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id
. ').');
169 echo "Failure: We do not handle modifications to subscriptions right now<p>";
172 case 'subscr_payment':
174 $recur->start_date
= $now;
177 $recur->modified_date
= $now;
180 // make sure the contribution status is not done
181 // since order of ipn's is unknown
182 if ($recur->contribution_status_id
!= $contributionStatuses['Completed']) {
183 $recur->contribution_status_id
= $contributionStatuses['In Progress'];
190 if ($sendNotification) {
191 $autoRenewMembership = FALSE;
193 isset($ids['membership']) && $ids['membership']
195 $autoRenewMembership = TRUE;
198 //send recurring Notification email for user
199 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
201 $ids['contributionPage'],
207 if ($txnType != 'subscr_payment') {
212 // check if this contribution transaction is already processed
213 // if not create a contribution and then get it processed
214 $contribution = new CRM_Contribute_BAO_Contribution();
215 $contribution->trxn_id
= $input['trxn_id'];
216 if ($contribution->trxn_id
&& $contribution->find()) {
217 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id
. ')');
218 echo "Success: Contribution has already been handled<p>";
222 if ($input['paymentStatus'] != 'Completed') {
223 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
226 // In future moving to create pending & then complete, but this OK for now.
227 // Also consider accepting 'Failed' like other processors.
228 $input['contribution_status_id'] = $contributionStatuses['Completed'];
229 $input['original_contribution_id'] = $ids['contribution'];
230 $input['contribution_recur_id'] = $ids['contributionRecur'];
232 civicrm_api3('Contribution', 'repeattransaction', $input);
236 $this->single($input, $ids, $objects,
242 * @param array $input
244 * @param array $objects
250 public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
251 $contribution = &$objects['contribution'];
253 // make sure the invoice is valid and matches what we have in the contribution record
254 if ((!$recur) ||
($recur && $first)) {
255 if ($contribution->invoice_id
!= $input['invoice']) {
256 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
257 echo "Failure: Invoice values dont match between database and IPN request<p>";
262 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
266 if ($contribution->total_amount
!= $input['amount']) {
267 Civi
::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
268 echo "Failure: Amount values dont match between database and IPN request<p>";
273 $contribution->total_amount
= $input['amount'];
276 $transaction = new CRM_Core_Transaction();
278 $status = $input['paymentStatus'];
279 if ($status == 'Denied' ||
$status == 'Failed' ||
$status == 'Voided') {
280 return $this->failed($objects, $transaction);
282 elseif ($status == 'Pending') {
283 return $this->pending($objects, $transaction);
285 elseif ($status == 'Refunded' ||
$status == 'Reversed') {
286 return $this->cancelled($objects, $transaction);
288 elseif ($status != 'Completed') {
289 return $this->unhandled($objects, $transaction);
292 // check if contribution is already completed, if so we ignore this ipn
293 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
294 if ($contribution->contribution_status_id
== $completedStatusId) {
295 $transaction->commit();
296 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id
. ').');
297 echo "Success: Contribution has already been handled<p>";
301 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
307 * @throws \CRM_Core_Exception
308 * @throws \CiviCRM_API3_Exception
310 public function main() {
311 $objects = $ids = $input = [];
312 $component = $this->retrieve('module', 'String');
313 $input['component'] = $component;
315 $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE);
316 $contributionID = $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE);
317 $membershipID = $this->retrieve('membershipID', 'Integer', FALSE);
318 $contributionRecurID = $this->retrieve('contributionRecurID', 'Integer', FALSE);
320 $this->getInput($input, $ids);
322 if ($component == 'event') {
323 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
324 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
327 // get the optional ids
328 $ids['membership'] = $membershipID;
329 $ids['contributionRecur'] = $contributionRecurID;
330 $ids['contributionPage'] = $this->retrieve('contributionPageID', 'Integer', FALSE);
331 $ids['related_contact'] = $this->retrieve('relatedContactID', 'Integer', FALSE);
332 $ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE);
335 $paymentProcessorID = $this->getPayPalPaymentProcessorID($input, $ids);
337 Civi
::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').');
339 // Debugging related to possible missing membership linkage
340 if ($contributionRecurID && $this->retrieve('membershipID', 'Integer', FALSE)) {
341 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution($contributionRecurID);
342 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
343 'contribution_id' => $templateContribution['id'],
344 'membership_id' => $membershipID,
346 $lineItems = civicrm_api3('LineItem', 'get', [
347 'contribution_id' => $templateContribution['id'],
348 'entity_id' => $membershipID,
349 'entity_table' => 'civicrm_membership',
351 Civi
::log()->debug('PayPalIPN: Received payment for membership ' . (int) $membershipID
352 . '. Original contribution was ' . (int) $contributionID . '. The template for this contribution is '
353 . $templateContribution['id'] . ' it is linked to ' . $membershipPayment['count']
354 . 'payments for this membership. It has ' . $lineItems['count'] . ' line items linked to this membership.'
355 . ' it is expected the original contribution will be linked by both entities to the membership.'
357 if (empty($membershipPayment['count']) && empty($lineItems['count'])) {
358 Civi
::log()->debug('PayPalIPN: Will attempt to compensate');
359 $input['membership_id'] = $this->retrieve('membershipID', 'Integer', FALSE);
361 if ($contributionRecurID) {
362 $recurLinks = civicrm_api3('ContributionRecur', 'get', [
363 'membership_id' => $membershipID,
364 'contribution_recur_id' => $contributionRecurID,
366 Civi
::log()->debug('PayPalIPN: Membership should be linked to contribution recur record ' . $contributionRecurID
367 . ' ' . $recurLinks['count'] . 'links found'
371 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
375 self
::$_paymentProcessor = &$objects['paymentProcessor'];
376 if ($component == 'contribute') {
377 if ($ids['contributionRecur']) {
378 // check if first contribution is completed, else complete first contribution
380 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
381 if ($objects['contribution']->contribution_status_id
== $completedStatusId) {
384 $this->recur($input, $ids, $objects, $first);
388 $this->single($input, $ids, $objects, FALSE, FALSE);
392 * @param array $input
395 * @throws \CRM_Core_Exception
397 public function getInput(&$input, &$ids) {
398 if (!$this->getBillingID($ids)) {
402 $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
403 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
404 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
405 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
406 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
408 $billingID = $ids['billing'];
410 "first_name" => 'first_name',
411 "last_name" => 'last_name',
412 "street_address-{$billingID}" => 'address_street',
413 "city-{$billingID}" => 'address_city',
414 "state-{$billingID}" => 'address_state',
415 "postal_code-{$billingID}" => 'address_zip',
416 "country-{$billingID}" => 'address_country_code',
418 foreach ($lookup as $name => $paypalName) {
419 $value = $this->retrieve($paypalName, 'String', FALSE);
420 $input[$name] = $value ?
$value : NULL;
423 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
424 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
425 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
426 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
428 $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
429 if (!empty($paymentDate)) {
430 $receiveDateTime = new DateTime($paymentDate);
432 * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST
433 * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system
435 $input['receive_date'] = CRM_Utils_Date
::convertDateToLocalTime($receiveDateTime);
440 * Gets PaymentProcessorID for PayPal
442 * @param array $input
446 * @throws \CRM_Core_Exception
447 * @throws \CiviCRM_API3_Exception
449 public function getPayPalPaymentProcessorID($input, $ids) {
450 // First we try and retrieve from POST params
451 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
452 if (!empty($paymentProcessorID)) {
453 return $paymentProcessorID;
456 // Then we try and get it from recurring contribution ID
457 if (!empty($ids['contributionRecur'])) {
458 $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
459 'id' => $ids['contributionRecur'],
460 'return' => ['payment_processor_id'],
462 if (!empty($contributionRecur['payment_processor_id'])) {
463 return $contributionRecur['payment_processor_id'];
467 // This is an unreliable method as there could be more than one instance.
468 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
469 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
470 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
471 // & call completetransaction or call fail? (which may not exist yet).
473 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');
474 // Then we try and retrieve based on business email ID
475 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name');
477 'user_name' => $this->retrieve('business', 'String', FALSE),
478 'payment_processor_type_id' => $paymentProcessorTypeID,
479 'is_test' => empty($input['is_test']) ?
0 : 1,
480 'options' => ['limit' => 1],
483 $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams);
484 if (empty($paymentProcessorID)) {
485 throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
487 return $paymentProcessorID;