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
18 class CRM_Core_Payment_PayPalIPN
extends CRM_Core_Payment_BaseIPN
{
20 public static $_paymentProcessor = NULL;
23 * Input parameters from payment processor. Store these so that
24 * the code does not need to keep retrieving from the http request
27 protected $_inputParameters = [];
30 * Constructor function.
32 * @param array $inputData
33 * Contents of HTTP REQUEST.
35 * @throws CRM_Core_Exception
37 public function __construct($inputData) {
39 $params = (!empty($inputData['custom'])) ?
40 array_merge($inputData, json_decode($inputData['custom'], TRUE)) :
42 $this->setInputParameters($params);
43 parent
::__construct();
52 * @throws \CRM_Core_Exception
54 public function retrieve($name, $type, $abort = TRUE) {
55 $value = CRM_Utils_Type
::validate(CRM_Utils_Array
::value($name, $this->_inputParameters
), $type, FALSE);
56 if ($abort && $value === NULL) {
57 Civi
::log()->debug("PayPalIPN: Could not find an entry for $name");
58 echo "Failure: Missing Parameter<p>" . CRM_Utils_Type
::escape($name, 'String');
59 throw new CRM_Core_Exception("PayPalIPN: Could not find an entry for $name");
67 * @param array $objects
72 * @throws \CRM_Core_Exception
73 * @throws \CiviCRM_API3_Exception
75 public function recur($input, $ids, $objects, $first) {
76 if (!isset($input['txnType'])) {
77 Civi
::log()->debug('PayPalIPN: Could not find txn_type in input request');
78 echo "Failure: Invalid parameters<p>";
82 if ($input['txnType'] === 'subscr_payment' &&
83 $input['paymentStatus'] !== 'Completed'
85 Civi
::log()->debug('PayPalIPN: Ignore all IPN payments that are not completed');
86 echo 'Failure: Invalid parameters<p>';
90 $recur = &$objects['contributionRecur'];
92 // make sure the invoice ids match
93 // make sure the invoice is valid and matches what we have in the contribution record
94 if ($recur->invoice_id
!= $input['invoice']) {
95 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request (RecurID: ' . $recur->id
. ').');
96 echo "Failure: Invoice values dont match between database and IPN request<p>";
100 $now = date('YmdHis');
102 // fix dates that already exist
103 $dates = ['create', 'start', 'end', 'cancel', 'modified'];
104 foreach ($dates as $date) {
105 $name = "{$date}_date";
107 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
110 $sendNotification = FALSE;
111 $subscriptionPaymentStatus = NULL;
112 // set transaction type
113 $txnType = $this->retrieve('txn_type', 'String');
114 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate'));
116 case 'subscr_signup':
117 $recur->create_date
= $now;
118 // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
120 $statusID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
121 $recur->id
, 'contribution_status_id'
123 if ($statusID != $contributionStatuses['In Progress']) {
124 $recur->contribution_status_id
= $contributionStatuses['Pending'];
126 $recur->processor_id
= $this->retrieve('subscr_id', 'String');
127 $recur->trxn_id
= $recur->processor_id
;
128 $sendNotification = TRUE;
129 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
133 if ($recur->contribution_status_id
!= $contributionStatuses['Cancelled']) {
134 $recur->contribution_status_id
= $contributionStatuses['Completed'];
136 $recur->end_date
= $now;
137 $sendNotification = TRUE;
138 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
141 case 'subscr_cancel':
142 $recur->contribution_status_id
= $contributionStatuses['Cancelled'];
143 $recur->cancel_date
= $now;
146 case 'subscr_failed':
147 $recur->contribution_status_id
= $contributionStatuses['Failed'];
148 $recur->modified_date
= $now;
151 case 'subscr_modify':
152 Civi
::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id
. ').');
153 echo "Failure: We do not handle modifications to subscriptions right now<p>";
156 case 'subscr_payment':
158 $recur->start_date
= $now;
161 $recur->modified_date
= $now;
164 // make sure the contribution status is not done
165 // since order of ipn's is unknown
166 if ($recur->contribution_status_id
!= $contributionStatuses['Completed']) {
167 $recur->contribution_status_id
= $contributionStatuses['In Progress'];
174 if ($sendNotification) {
175 $autoRenewMembership = FALSE;
177 isset($ids['membership']) && $ids['membership']
179 $autoRenewMembership = TRUE;
182 //send recurring Notification email for user
183 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
185 $ids['contributionPage'],
191 if ($txnType != 'subscr_payment') {
196 // check if this contribution transaction is already processed
197 // if not create a contribution and then get it processed
198 $contribution = new CRM_Contribute_BAO_Contribution();
199 $contribution->trxn_id
= $input['trxn_id'];
200 if ($contribution->trxn_id
&& $contribution->find()) {
201 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id
. ')');
202 echo "Success: Contribution has already been handled<p>";
206 if ($input['paymentStatus'] != 'Completed') {
207 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
210 // In future moving to create pending & then complete, but this OK for now.
211 // Also consider accepting 'Failed' like other processors.
212 $input['contribution_status_id'] = $contributionStatuses['Completed'];
213 $input['original_contribution_id'] = $ids['contribution'];
214 $input['contribution_recur_id'] = $ids['contributionRecur'];
216 civicrm_api3('Contribution', 'repeattransaction', $input);
220 $this->single($input, $ids, $objects,
226 * @param array $input
228 * @param array $objects
234 public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
235 $contribution = &$objects['contribution'];
237 // make sure the invoice is valid and matches what we have in the contribution record
238 if ((!$recur) ||
($recur && $first)) {
239 if ($contribution->invoice_id
!= $input['invoice']) {
240 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
241 echo "Failure: Invoice values dont match between database and IPN request<p>";
246 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
250 if ($contribution->total_amount
!= $input['amount']) {
251 Civi
::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
252 echo "Failure: Amount values dont match between database and IPN request<p>";
257 $contribution->total_amount
= $input['amount'];
260 $transaction = new CRM_Core_Transaction();
262 $status = $input['paymentStatus'];
263 if ($status == 'Denied' ||
$status == 'Failed' ||
$status == 'Voided') {
264 return $this->failed($objects, $transaction);
266 elseif ($status == 'Pending') {
267 return $this->pending($objects, $transaction);
269 elseif ($status == 'Refunded' ||
$status == 'Reversed') {
270 return $this->cancelled($objects, $transaction);
272 elseif ($status != 'Completed') {
273 return $this->unhandled($objects, $transaction);
276 // check if contribution is already completed, if so we ignore this ipn
277 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
278 if ($contribution->contribution_status_id
== $completedStatusId) {
279 $transaction->commit();
280 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id
. ').');
281 echo "Success: Contribution has already been handled<p>";
285 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
291 * @throws \CRM_Core_Exception
292 * @throws \CiviCRM_API3_Exception
294 public function main() {
295 $objects = $ids = $input = [];
296 $component = $this->retrieve('module', 'String');
297 $input['component'] = $component;
299 $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE);
300 $contributionID = $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE);
301 $membershipID = $this->retrieve('membershipID', 'Integer', FALSE);
302 $contributionRecurID = $this->retrieve('contributionRecurID', 'Integer', FALSE);
304 $this->getInput($input, $ids);
306 if ($component == 'event') {
307 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
308 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
311 // get the optional ids
312 $ids['membership'] = $membershipID;
313 $ids['contributionRecur'] = $contributionRecurID;
314 $ids['contributionPage'] = $this->retrieve('contributionPageID', 'Integer', FALSE);
315 $ids['related_contact'] = $this->retrieve('relatedContactID', 'Integer', FALSE);
316 $ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE);
319 $paymentProcessorID = $this->getPayPalPaymentProcessorID($input, $ids);
321 Civi
::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').');
323 // Debugging related to possible missing membership linkage
324 if ($contributionRecurID && $this->retrieve('membershipID', 'Integer', FALSE)) {
325 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution($contributionRecurID);
326 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
327 'contribution_id' => $templateContribution['id'],
328 'membership_id' => $membershipID,
330 $lineItems = civicrm_api3('LineItem', 'get', [
331 'contribution_id' => $templateContribution['id'],
332 'entity_id' => $membershipID,
333 'entity_table' => 'civicrm_membership',
335 Civi
::log()->debug('PayPalIPN: Received payment for membership ' . (int) $membershipID
336 . '. Original contribution was ' . (int) $contributionID . '. The template for this contribution is '
337 . $templateContribution['id'] . ' it is linked to ' . $membershipPayment['count']
338 . 'payments for this membership. It has ' . $lineItems['count'] . ' line items linked to this membership.'
339 . ' it is expected the original contribution will be linked by both entities to the membership.'
341 if (empty($membershipPayment['count']) && empty($lineItems['count'])) {
342 Civi
::log()->debug('PayPalIPN: Will attempt to compensate');
343 $input['membership_id'] = $this->retrieve('membershipID', 'Integer', FALSE);
345 if ($contributionRecurID) {
346 $recurLinks = civicrm_api3('ContributionRecur', 'get', [
347 'membership_id' => $membershipID,
348 'contribution_recur_id' => $contributionRecurID,
350 Civi
::log()->debug('PayPalIPN: Membership should be linked to contribution recur record ' . $contributionRecurID
351 . ' ' . $recurLinks['count'] . 'links found'
355 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
359 self
::$_paymentProcessor = &$objects['paymentProcessor'];
360 if ($component == 'contribute') {
361 if ($ids['contributionRecur']) {
362 // check if first contribution is completed, else complete first contribution
364 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
365 if ($objects['contribution']->contribution_status_id
== $completedStatusId) {
368 $this->recur($input, $ids, $objects, $first);
372 $this->single($input, $ids, $objects, FALSE, FALSE);
376 * @param array $input
379 * @throws \CRM_Core_Exception
381 public function getInput(&$input, &$ids) {
382 if (!$this->getBillingID($ids)) {
386 $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
387 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
388 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
389 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
390 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
392 $billingID = $ids['billing'];
394 "first_name" => 'first_name',
395 "last_name" => 'last_name',
396 "street_address-{$billingID}" => 'address_street',
397 "city-{$billingID}" => 'address_city',
398 "state-{$billingID}" => 'address_state',
399 "postal_code-{$billingID}" => 'address_zip',
400 "country-{$billingID}" => 'address_country_code',
402 foreach ($lookup as $name => $paypalName) {
403 $value = $this->retrieve($paypalName, 'String', FALSE);
404 $input[$name] = $value ?
$value : NULL;
407 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
408 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
409 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
410 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
412 $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
413 if (!empty($paymentDate)) {
414 $receiveDateTime = new DateTime($paymentDate);
416 * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST
417 * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system
419 $input['receive_date'] = CRM_Utils_Date
::convertDateToLocalTime($receiveDateTime);
424 * Gets PaymentProcessorID for PayPal
426 * @param array $input
430 * @throws \CRM_Core_Exception
431 * @throws \CiviCRM_API3_Exception
433 public function getPayPalPaymentProcessorID($input, $ids) {
434 // First we try and retrieve from POST params
435 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
436 if (!empty($paymentProcessorID)) {
437 return $paymentProcessorID;
440 // Then we try and get it from recurring contribution ID
441 if (!empty($ids['contributionRecur'])) {
442 $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
443 'id' => $ids['contributionRecur'],
444 'return' => ['payment_processor_id'],
446 if (!empty($contributionRecur['payment_processor_id'])) {
447 return $contributionRecur['payment_processor_id'];
451 // This is an unreliable method as there could be more than one instance.
452 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
453 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
454 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
455 // & call completetransaction or call fail? (which may not exist yet).
457 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');
458 // Then we try and retrieve based on business email ID
459 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name');
461 'user_name' => $this->retrieve('business', 'String', FALSE),
462 'payment_processor_type_id' => $paymentProcessorTypeID,
463 'is_test' => empty($input['is_test']) ?
0 : 1,
464 'options' => ['limit' => 1],
467 $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams);
468 if (empty($paymentProcessorID)) {
469 throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
471 return $paymentProcessorID;