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 $sendNotification = FALSE;
102 $subscriptionPaymentStatus = NULL;
103 // set transaction type
104 $txnType = $this->retrieve('txn_type', 'String');
105 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate'));
107 case 'subscr_signup':
108 $recur->create_date
= $now;
109 // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
111 $statusID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
112 $recur->id
, 'contribution_status_id'
114 if ($statusID != $contributionStatuses['In Progress']) {
115 $recur->contribution_status_id
= $contributionStatuses['Pending'];
117 $recur->processor_id
= $this->retrieve('subscr_id', 'String');
118 $recur->trxn_id
= $recur->processor_id
;
119 $sendNotification = TRUE;
120 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
124 if ($recur->contribution_status_id
!= $contributionStatuses['Cancelled']) {
125 $recur->contribution_status_id
= $contributionStatuses['Completed'];
127 $recur->end_date
= $now;
128 $sendNotification = TRUE;
129 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
132 case 'subscr_cancel':
133 $recur->contribution_status_id
= $contributionStatuses['Cancelled'];
134 $recur->cancel_date
= $now;
137 case 'subscr_failed':
138 $recur->contribution_status_id
= $contributionStatuses['Failed'];
139 $recur->modified_date
= $now;
142 case 'subscr_modify':
143 Civi
::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id
. ').');
144 echo "Failure: We do not handle modifications to subscriptions right now<p>";
147 case 'subscr_payment':
149 $recur->start_date
= $now;
152 $recur->modified_date
= $now;
155 // make sure the contribution status is not done
156 // since order of ipn's is unknown
157 if ($recur->contribution_status_id
!= $contributionStatuses['Completed']) {
158 $recur->contribution_status_id
= $contributionStatuses['In Progress'];
165 if ($sendNotification) {
166 $autoRenewMembership = FALSE;
168 isset($ids['membership']) && $ids['membership']
170 $autoRenewMembership = TRUE;
173 //send recurring Notification email for user
174 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
176 $ids['contributionPage'],
182 if ($txnType != 'subscr_payment') {
187 // check if this contribution transaction is already processed
188 // if not create a contribution and then get it processed
189 $contribution = new CRM_Contribute_BAO_Contribution();
190 $contribution->trxn_id
= $input['trxn_id'];
191 if ($contribution->trxn_id
&& $contribution->find()) {
192 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id
. ')');
193 echo "Success: Contribution has already been handled<p>";
197 if ($input['paymentStatus'] != 'Completed') {
198 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
201 // In future moving to create pending & then complete, but this OK for now.
202 // Also consider accepting 'Failed' like other processors.
203 $input['contribution_status_id'] = $contributionStatuses['Completed'];
204 $input['original_contribution_id'] = $ids['contribution'];
205 $input['contribution_recur_id'] = $ids['contributionRecur'];
207 civicrm_api3('Contribution', 'repeattransaction', $input);
211 $this->single($input, $ids, $objects,
217 * @param array $input
219 * @param array $objects
224 * @throws \CRM_Core_Exception
225 * @throws \CiviCRM_API3_Exception
227 public function single($input, $ids, $objects, $recur = FALSE, $first = FALSE) {
228 $contribution = &$objects['contribution'];
230 // make sure the invoice is valid and matches what we have in the contribution record
231 if ((!$recur) ||
($recur && $first)) {
232 if ($contribution->invoice_id
!= $input['invoice']) {
233 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
234 echo "Failure: Invoice values dont match between database and IPN request<p>";
239 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
243 if ($contribution->total_amount
!= $input['amount']) {
244 Civi
::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
245 echo "Failure: Amount values dont match between database and IPN request<p>";
250 $contribution->total_amount
= $input['amount'];
253 $status = $input['paymentStatus'];
254 if ($status === 'Denied' ||
$status === 'Failed' ||
$status === 'Voided') {
255 $this->failed($objects);
258 if ($status === 'Pending') {
259 Civi
::log()->debug('Returning since contribution status is Pending');
262 elseif ($status === 'Refunded' ||
$status === 'Reversed') {
263 $this->cancelled($objects);
266 elseif ($status !== 'Completed') {
267 Civi
::log()->debug('Returning since contribution status is not handled');
271 // check if contribution is already completed, if so we ignore this ipn
272 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
273 if ($contribution->contribution_status_id
== $completedStatusId) {
274 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id
. ').');
275 echo 'Success: Contribution has already been handled<p>';
279 $this->completeTransaction($input, $ids, $objects);
285 * @throws \CRM_Core_Exception
286 * @throws \CiviCRM_API3_Exception
288 public function main() {
289 $objects = $ids = $input = [];
290 $component = $this->retrieve('module', 'String');
291 $input['component'] = $component;
293 $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE);
294 $contributionID = $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE);
295 $membershipID = $this->retrieve('membershipID', 'Integer', FALSE);
296 $contributionRecurID = $this->retrieve('contributionRecurID', 'Integer', FALSE);
298 $this->getInput($input);
300 if ($component == 'event') {
301 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
302 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
305 // get the optional ids
306 $ids['membership'] = $membershipID;
307 $ids['contributionRecur'] = $contributionRecurID;
308 $ids['contributionPage'] = $this->retrieve('contributionPageID', 'Integer', FALSE);
309 $ids['related_contact'] = $this->retrieve('relatedContactID', 'Integer', FALSE);
310 $ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE);
313 $paymentProcessorID = $this->getPayPalPaymentProcessorID($input, $ids);
315 Civi
::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').');
317 // Debugging related to possible missing membership linkage
318 if ($contributionRecurID && $this->retrieve('membershipID', 'Integer', FALSE)) {
319 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution($contributionRecurID);
320 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
321 'contribution_id' => $templateContribution['id'],
322 'membership_id' => $membershipID,
324 $lineItems = civicrm_api3('LineItem', 'get', [
325 'contribution_id' => $templateContribution['id'],
326 'entity_id' => $membershipID,
327 'entity_table' => 'civicrm_membership',
329 Civi
::log()->debug('PayPalIPN: Received payment for membership ' . (int) $membershipID
330 . '. Original contribution was ' . (int) $contributionID . '. The template for this contribution is '
331 . $templateContribution['id'] . ' it is linked to ' . $membershipPayment['count']
332 . 'payments for this membership. It has ' . $lineItems['count'] . ' line items linked to this membership.'
333 . ' it is expected the original contribution will be linked by both entities to the membership.'
335 if (empty($membershipPayment['count']) && empty($lineItems['count'])) {
336 Civi
::log()->debug('PayPalIPN: Will attempt to compensate');
337 $input['membership_id'] = $this->retrieve('membershipID', 'Integer', FALSE);
339 if ($contributionRecurID) {
340 $recurLinks = civicrm_api3('ContributionRecur', 'get', [
341 'membership_id' => $membershipID,
342 'contribution_recur_id' => $contributionRecurID,
344 Civi
::log()->debug('PayPalIPN: Membership should be linked to contribution recur record ' . $contributionRecurID
345 . ' ' . $recurLinks['count'] . 'links found'
349 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
353 self
::$_paymentProcessor = &$objects['paymentProcessor'];
354 if ($component == 'contribute') {
355 if ($ids['contributionRecur']) {
356 // check if first contribution is completed, else complete first contribution
358 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
359 if ($objects['contribution']->contribution_status_id
== $completedStatusId) {
362 $this->recur($input, $ids, $objects, $first);
366 $this->single($input, $ids, $objects);
370 * @param array $input
372 * @throws \CRM_Core_Exception
374 public function getInput(&$input) {
375 $billingID = CRM_Core_BAO_LocationType
::getBilling();
376 $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
377 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
378 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
379 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
380 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
383 "first_name" => 'first_name',
384 "last_name" => 'last_name',
385 "street_address-{$billingID}" => 'address_street',
386 "city-{$billingID}" => 'address_city',
387 "state-{$billingID}" => 'address_state',
388 "postal_code-{$billingID}" => 'address_zip',
389 "country-{$billingID}" => 'address_country_code',
391 foreach ($lookup as $name => $paypalName) {
392 $value = $this->retrieve($paypalName, 'String', FALSE);
393 $input[$name] = $value ?
$value : NULL;
396 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
397 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
398 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
399 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
401 $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
402 if (!empty($paymentDate)) {
403 $receiveDateTime = new DateTime($paymentDate);
405 * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST
406 * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system
408 $input['receive_date'] = CRM_Utils_Date
::convertDateToLocalTime($receiveDateTime);
413 * Gets PaymentProcessorID for PayPal
415 * @param array $input
419 * @throws \CRM_Core_Exception
420 * @throws \CiviCRM_API3_Exception
422 public function getPayPalPaymentProcessorID($input, $ids) {
423 // First we try and retrieve from POST params
424 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
425 if (!empty($paymentProcessorID)) {
426 return $paymentProcessorID;
429 // Then we try and get it from recurring contribution ID
430 if (!empty($ids['contributionRecur'])) {
431 $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
432 'id' => $ids['contributionRecur'],
433 'return' => ['payment_processor_id'],
435 if (!empty($contributionRecur['payment_processor_id'])) {
436 return $contributionRecur['payment_processor_id'];
440 // This is an unreliable method as there could be more than one instance.
441 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
442 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
443 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
444 // & call completetransaction or call fail? (which may not exist yet).
446 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');
447 // Then we try and retrieve based on business email ID
448 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name');
450 'user_name' => $this->retrieve('business', 'String', FALSE),
451 'payment_processor_type_id' => $paymentProcessorTypeID,
452 'is_test' => empty($input['is_test']) ?
0 : 1,
453 'options' => ['limit' => 1],
456 $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams);
457 if (empty($paymentProcessorID)) {
458 throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
460 return $paymentProcessorID;