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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Core_Payment_PayPalIPN
extends CRM_Core_Payment_BaseIPN
{
19 public static $_paymentProcessor = 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 * 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 Civi
::log()->debug("PayPalIPN: Could not find an entry for $name");
57 echo "Failure: Missing Parameter<p>" . CRM_Utils_Type
::escape($name, 'String');
58 throw new CRM_Core_Exception("PayPalIPN: Could not find an entry for $name");
66 * @param array $objects
71 * @throws \CRM_Core_Exception
72 * @throws \CiviCRM_API3_Exception
74 public function recur($input, $ids, $objects, $first) {
75 if (!isset($input['txnType'])) {
76 Civi
::log()->debug('PayPalIPN: Could not find txn_type in input request');
77 echo "Failure: Invalid parameters<p>";
81 if ($input['txnType'] === 'subscr_payment' &&
82 $input['paymentStatus'] !== 'Completed'
84 Civi
::log()->debug('PayPalIPN: Ignore all IPN payments that are not completed');
85 echo 'Failure: Invalid parameters<p>';
89 $recur = &$objects['contributionRecur'];
91 // make sure the invoice ids match
92 // make sure the invoice is valid and matches what we have in the contribution record
93 if ($recur->invoice_id
!= $input['invoice']) {
94 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request (RecurID: ' . $recur->id
. ').');
95 echo "Failure: Invoice values dont match between database and IPN request<p>";
99 $now = date('YmdHis');
101 // fix dates that already exist
102 $dates = ['create', 'start', 'end', 'cancel', 'modified'];
103 foreach ($dates as $date) {
104 $name = "{$date}_date";
106 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
109 $sendNotification = FALSE;
110 $subscriptionPaymentStatus = NULL;
111 // set transaction type
112 $txnType = $this->retrieve('txn_type', 'String');
113 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate'));
115 case 'subscr_signup':
116 $recur->create_date
= $now;
117 // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
119 $statusID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
120 $recur->id
, 'contribution_status_id'
122 if ($statusID != $contributionStatuses['In Progress']) {
123 $recur->contribution_status_id
= $contributionStatuses['Pending'];
125 $recur->processor_id
= $this->retrieve('subscr_id', 'String');
126 $recur->trxn_id
= $recur->processor_id
;
127 $sendNotification = TRUE;
128 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
132 if ($recur->contribution_status_id
!= $contributionStatuses['Cancelled']) {
133 $recur->contribution_status_id
= $contributionStatuses['Completed'];
135 $recur->end_date
= $now;
136 $sendNotification = TRUE;
137 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
140 case 'subscr_cancel':
141 $recur->contribution_status_id
= $contributionStatuses['Cancelled'];
142 $recur->cancel_date
= $now;
145 case 'subscr_failed':
146 $recur->contribution_status_id
= $contributionStatuses['Failed'];
147 $recur->modified_date
= $now;
150 case 'subscr_modify':
151 Civi
::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id
. ').');
152 echo "Failure: We do not handle modifications to subscriptions right now<p>";
155 case 'subscr_payment':
157 $recur->start_date
= $now;
160 $recur->modified_date
= $now;
163 // make sure the contribution status is not done
164 // since order of ipn's is unknown
165 if ($recur->contribution_status_id
!= $contributionStatuses['Completed']) {
166 $recur->contribution_status_id
= $contributionStatuses['In Progress'];
173 if ($sendNotification) {
174 $autoRenewMembership = FALSE;
176 isset($ids['membership']) && $ids['membership']
178 $autoRenewMembership = TRUE;
181 //send recurring Notification email for user
182 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
184 $ids['contributionPage'],
190 if ($txnType != 'subscr_payment') {
195 // check if this contribution transaction is already processed
196 // if not create a contribution and then get it processed
197 $contribution = new CRM_Contribute_BAO_Contribution();
198 $contribution->trxn_id
= $input['trxn_id'];
199 if ($contribution->trxn_id
&& $contribution->find()) {
200 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id
. ')');
201 echo "Success: Contribution has already been handled<p>";
205 if ($input['paymentStatus'] != 'Completed') {
206 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
209 // In future moving to create pending & then complete, but this OK for now.
210 // Also consider accepting 'Failed' like other processors.
211 $input['contribution_status_id'] = $contributionStatuses['Completed'];
212 $input['original_contribution_id'] = $ids['contribution'];
213 $input['contribution_recur_id'] = $ids['contributionRecur'];
215 civicrm_api3('Contribution', 'repeattransaction', $input);
219 $this->single($input, $ids, $objects,
225 * @param array $input
227 * @param array $objects
233 public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
234 $contribution = &$objects['contribution'];
236 // make sure the invoice is valid and matches what we have in the contribution record
237 if ((!$recur) ||
($recur && $first)) {
238 if ($contribution->invoice_id
!= $input['invoice']) {
239 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
240 echo "Failure: Invoice values dont match between database and IPN request<p>";
245 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
249 if ($contribution->total_amount
!= $input['amount']) {
250 Civi
::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
251 echo "Failure: Amount values dont match between database and IPN request<p>";
256 $contribution->total_amount
= $input['amount'];
259 $transaction = new CRM_Core_Transaction();
261 $status = $input['paymentStatus'];
262 if ($status == 'Denied' ||
$status == 'Failed' ||
$status == 'Voided') {
263 return $this->failed($objects, $transaction);
265 if ($status === 'Pending') {
266 Civi
::log()->debug('Returning since contribution status is Pending');
269 elseif ($status == 'Refunded' ||
$status == 'Reversed') {
270 return $this->cancelled($objects, $transaction);
272 elseif ($status !== 'Completed') {
273 Civi
::log()->debug('Returning since contribution status is not handled');
277 // check if contribution is already completed, if so we ignore this ipn
278 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
279 if ($contribution->contribution_status_id
== $completedStatusId) {
280 $transaction->commit();
281 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id
. ').');
282 echo 'Success: Contribution has already been handled<p>';
286 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
292 * @throws \CRM_Core_Exception
293 * @throws \CiviCRM_API3_Exception
295 public function main() {
296 $objects = $ids = $input = [];
297 $component = $this->retrieve('module', 'String');
298 $input['component'] = $component;
300 $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE);
301 $contributionID = $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE);
302 $membershipID = $this->retrieve('membershipID', 'Integer', FALSE);
303 $contributionRecurID = $this->retrieve('contributionRecurID', 'Integer', FALSE);
305 $this->getInput($input, $ids);
307 if ($component == 'event') {
308 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
309 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
312 // get the optional ids
313 $ids['membership'] = $membershipID;
314 $ids['contributionRecur'] = $contributionRecurID;
315 $ids['contributionPage'] = $this->retrieve('contributionPageID', 'Integer', FALSE);
316 $ids['related_contact'] = $this->retrieve('relatedContactID', 'Integer', FALSE);
317 $ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE);
320 $paymentProcessorID = $this->getPayPalPaymentProcessorID($input, $ids);
322 Civi
::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').');
324 // Debugging related to possible missing membership linkage
325 if ($contributionRecurID && $this->retrieve('membershipID', 'Integer', FALSE)) {
326 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution($contributionRecurID);
327 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
328 'contribution_id' => $templateContribution['id'],
329 'membership_id' => $membershipID,
331 $lineItems = civicrm_api3('LineItem', 'get', [
332 'contribution_id' => $templateContribution['id'],
333 'entity_id' => $membershipID,
334 'entity_table' => 'civicrm_membership',
336 Civi
::log()->debug('PayPalIPN: Received payment for membership ' . (int) $membershipID
337 . '. Original contribution was ' . (int) $contributionID . '. The template for this contribution is '
338 . $templateContribution['id'] . ' it is linked to ' . $membershipPayment['count']
339 . 'payments for this membership. It has ' . $lineItems['count'] . ' line items linked to this membership.'
340 . ' it is expected the original contribution will be linked by both entities to the membership.'
342 if (empty($membershipPayment['count']) && empty($lineItems['count'])) {
343 Civi
::log()->debug('PayPalIPN: Will attempt to compensate');
344 $input['membership_id'] = $this->retrieve('membershipID', 'Integer', FALSE);
346 if ($contributionRecurID) {
347 $recurLinks = civicrm_api3('ContributionRecur', 'get', [
348 'membership_id' => $membershipID,
349 'contribution_recur_id' => $contributionRecurID,
351 Civi
::log()->debug('PayPalIPN: Membership should be linked to contribution recur record ' . $contributionRecurID
352 . ' ' . $recurLinks['count'] . 'links found'
356 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
360 self
::$_paymentProcessor = &$objects['paymentProcessor'];
361 if ($component == 'contribute') {
362 if ($ids['contributionRecur']) {
363 // check if first contribution is completed, else complete first contribution
365 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
366 if ($objects['contribution']->contribution_status_id
== $completedStatusId) {
369 $this->recur($input, $ids, $objects, $first);
373 $this->single($input, $ids, $objects, FALSE, FALSE);
377 * @param array $input
380 * @throws \CRM_Core_Exception
382 public function getInput(&$input, &$ids) {
383 $billingID = $ids['billing'] = CRM_Core_BAO_LocationType
::getBilling();
384 $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
385 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
386 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
387 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
388 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
391 "first_name" => 'first_name',
392 "last_name" => 'last_name',
393 "street_address-{$billingID}" => 'address_street',
394 "city-{$billingID}" => 'address_city',
395 "state-{$billingID}" => 'address_state',
396 "postal_code-{$billingID}" => 'address_zip',
397 "country-{$billingID}" => 'address_country_code',
399 foreach ($lookup as $name => $paypalName) {
400 $value = $this->retrieve($paypalName, 'String', FALSE);
401 $input[$name] = $value ?
$value : NULL;
404 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
405 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
406 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
407 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
409 $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
410 if (!empty($paymentDate)) {
411 $receiveDateTime = new DateTime($paymentDate);
413 * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST
414 * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system
416 $input['receive_date'] = CRM_Utils_Date
::convertDateToLocalTime($receiveDateTime);
421 * Gets PaymentProcessorID for PayPal
423 * @param array $input
427 * @throws \CRM_Core_Exception
428 * @throws \CiviCRM_API3_Exception
430 public function getPayPalPaymentProcessorID($input, $ids) {
431 // First we try and retrieve from POST params
432 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
433 if (!empty($paymentProcessorID)) {
434 return $paymentProcessorID;
437 // Then we try and get it from recurring contribution ID
438 if (!empty($ids['contributionRecur'])) {
439 $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
440 'id' => $ids['contributionRecur'],
441 'return' => ['payment_processor_id'],
443 if (!empty($contributionRecur['payment_processor_id'])) {
444 return $contributionRecur['payment_processor_id'];
448 // This is an unreliable method as there could be more than one instance.
449 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
450 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
451 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
452 // & call completetransaction or call fail? (which may not exist yet).
454 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');
455 // Then we try and retrieve based on business email ID
456 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name');
458 'user_name' => $this->retrieve('business', 'String', FALSE),
459 'payment_processor_type_id' => $paymentProcessorTypeID,
460 'is_test' => empty($input['is_test']) ?
0 : 1,
461 'options' => ['limit' => 1],
464 $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams);
465 if (empty($paymentProcessorID)) {
466 throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
468 return $paymentProcessorID;