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 throw new CRM_Core_Exception("PayPalIPN: Could not find an entry for $name");
64 * @param array $objects
69 * @throws \CRM_Core_Exception
70 * @throws \CiviCRM_API3_Exception
72 public function recur($input, $ids, $objects, $first) {
73 if (!isset($input['txnType'])) {
74 Civi
::log()->debug('PayPalIPN: Could not find txn_type in input request');
75 echo "Failure: Invalid parameters<p>";
79 if ($input['txnType'] === 'subscr_payment' &&
80 $input['paymentStatus'] !== 'Completed'
82 Civi
::log()->debug('PayPalIPN: Ignore all IPN payments that are not completed');
83 echo 'Failure: Invalid parameters<p>';
87 $recur = &$objects['contributionRecur'];
89 // make sure the invoice ids match
90 // make sure the invoice is valid and matches what we have in the contribution record
91 if ($recur->invoice_id
!= $input['invoice']) {
92 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request (RecurID: ' . $recur->id
. ').');
93 echo "Failure: Invoice values dont match between database and IPN request<p>";
97 $now = date('YmdHis');
99 $sendNotification = FALSE;
100 $subscriptionPaymentStatus = NULL;
101 // set transaction type
102 $txnType = $this->retrieve('txn_type', 'String');
103 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate'));
105 case 'subscr_signup':
106 $recur->create_date
= $now;
107 // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
109 $statusID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
110 $recur->id
, 'contribution_status_id'
112 if ($statusID != $contributionStatuses['In Progress']) {
113 $recur->contribution_status_id
= $contributionStatuses['Pending'];
115 $recur->processor_id
= $this->retrieve('subscr_id', 'String');
116 $recur->trxn_id
= $recur->processor_id
;
117 $sendNotification = TRUE;
118 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
122 if ($recur->contribution_status_id
!= $contributionStatuses['Cancelled']) {
123 $recur->contribution_status_id
= $contributionStatuses['Completed'];
125 $recur->end_date
= $now;
126 $sendNotification = TRUE;
127 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
130 case 'subscr_cancel':
131 $recur->contribution_status_id
= $contributionStatuses['Cancelled'];
132 $recur->cancel_date
= $now;
135 case 'subscr_failed':
136 $recur->contribution_status_id
= $contributionStatuses['Failed'];
137 $recur->modified_date
= $now;
140 case 'subscr_modify':
141 Civi
::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id
. ').');
142 echo "Failure: We do not handle modifications to subscriptions right now<p>";
145 case 'subscr_payment':
147 $recur->start_date
= $now;
150 $recur->modified_date
= $now;
153 // make sure the contribution status is not done
154 // since order of ipn's is unknown
155 if ($recur->contribution_status_id
!= $contributionStatuses['Completed']) {
156 $recur->contribution_status_id
= $contributionStatuses['In Progress'];
163 if ($sendNotification) {
164 $autoRenewMembership = FALSE;
166 isset($ids['membership']) && $ids['membership']
168 $autoRenewMembership = TRUE;
171 //send recurring Notification email for user
172 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
174 $ids['contributionPage'],
180 if ($txnType != 'subscr_payment') {
185 // check if this contribution transaction is already processed
186 // if not create a contribution and then get it processed
187 $contribution = new CRM_Contribute_BAO_Contribution();
188 $contribution->trxn_id
= $input['trxn_id'];
189 if ($contribution->trxn_id
&& $contribution->find()) {
190 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id
. ')');
191 echo "Success: Contribution has already been handled<p>";
195 if ($input['paymentStatus'] != 'Completed') {
196 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
199 // In future moving to create pending & then complete, but this OK for now.
200 // Also consider accepting 'Failed' like other processors.
201 $input['contribution_status_id'] = $contributionStatuses['Completed'];
202 $input['original_contribution_id'] = $ids['contribution'];
203 $input['contribution_recur_id'] = $ids['contributionRecur'];
205 civicrm_api3('Contribution', 'repeattransaction', $input);
209 $this->single($input, $ids, $objects,
215 * @param array $input
217 * @param array $objects
222 * @throws \CRM_Core_Exception
223 * @throws \CiviCRM_API3_Exception
225 public function single($input, $ids, $objects, $recur = FALSE, $first = FALSE) {
226 $contribution = &$objects['contribution'];
228 // make sure the invoice is valid and matches what we have in the contribution record
229 if ((!$recur) ||
($recur && $first)) {
230 if ($contribution->invoice_id
!= $input['invoice']) {
231 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
232 echo "Failure: Invoice values dont match between database and IPN request<p>";
237 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
241 if ($contribution->total_amount
!= $input['amount']) {
242 Civi
::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
243 echo "Failure: Amount values dont match between database and IPN request<p>";
248 $contribution->total_amount
= $input['amount'];
251 $status = $input['paymentStatus'];
252 if ($status === 'Denied' ||
$status === 'Failed' ||
$status === 'Voided') {
253 $this->failed($objects);
256 if ($status === 'Pending') {
257 Civi
::log()->debug('Returning since contribution status is Pending');
260 elseif ($status === 'Refunded' ||
$status === 'Reversed') {
261 $this->cancelled($objects);
264 elseif ($status !== 'Completed') {
265 Civi
::log()->debug('Returning since contribution status is not handled');
269 // check if contribution is already completed, if so we ignore this ipn
270 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
271 if ($contribution->contribution_status_id
== $completedStatusId) {
272 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id
. ').');
273 echo 'Success: Contribution has already been handled<p>';
277 $this->completeTransaction($input, $ids, $objects);
283 * @throws \CRM_Core_Exception
284 * @throws \CiviCRM_API3_Exception
286 public function main() {
288 $objects = $ids = $input = [];
289 $component = $this->retrieve('module', 'String');
290 $input['component'] = $component;
292 $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE);
293 $contributionID = $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE);
294 $membershipID = $this->retrieve('membershipID', 'Integer', FALSE);
295 $contributionRecurID = $this->retrieve('contributionRecurID', 'Integer', FALSE);
297 $this->getInput($input);
299 if ($component == 'event') {
300 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
301 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
304 // get the optional ids
305 $ids['membership'] = $membershipID;
306 $ids['contributionRecur'] = $contributionRecurID;
307 $ids['contributionPage'] = $this->retrieve('contributionPageID', 'Integer', FALSE);
308 $ids['related_contact'] = $this->retrieve('relatedContactID', 'Integer', FALSE);
309 $ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE);
312 $paymentProcessorID = $this->getPayPalPaymentProcessorID($input, $ids);
314 Civi
::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').');
316 // Debugging related to possible missing membership linkage
317 if ($contributionRecurID && $this->retrieve('membershipID', 'Integer', FALSE)) {
318 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution($contributionRecurID);
319 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
320 'contribution_id' => $templateContribution['id'],
321 'membership_id' => $membershipID,
323 $lineItems = civicrm_api3('LineItem', 'get', [
324 'contribution_id' => $templateContribution['id'],
325 'entity_id' => $membershipID,
326 'entity_table' => 'civicrm_membership',
328 Civi
::log()->debug('PayPalIPN: Received payment for membership ' . (int) $membershipID
329 . '. Original contribution was ' . (int) $contributionID . '. The template for this contribution is '
330 . $templateContribution['id'] . ' it is linked to ' . $membershipPayment['count']
331 . 'payments for this membership. It has ' . $lineItems['count'] . ' line items linked to this membership.'
332 . ' it is expected the original contribution will be linked by both entities to the membership.'
334 if (empty($membershipPayment['count']) && empty($lineItems['count'])) {
335 Civi
::log()->debug('PayPalIPN: Will attempt to compensate');
336 $input['membership_id'] = $this->retrieve('membershipID', 'Integer', FALSE);
338 if ($contributionRecurID) {
339 $recurLinks = civicrm_api3('ContributionRecur', 'get', [
340 'membership_id' => $membershipID,
341 'contribution_recur_id' => $contributionRecurID,
343 Civi
::log()->debug('PayPalIPN: Membership should be linked to contribution recur record ' . $contributionRecurID
344 . ' ' . $recurLinks['count'] . 'links found'
348 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
352 self
::$_paymentProcessor = &$objects['paymentProcessor'];
353 if ($component == 'contribute') {
354 if ($ids['contributionRecur']) {
355 // check if first contribution is completed, else complete first contribution
357 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
358 if ($objects['contribution']->contribution_status_id
== $completedStatusId) {
361 $this->recur($input, $ids, $objects, $first);
365 $this->single($input, $ids, $objects);
367 catch (CRM_Core_Exception
$e) {
368 Civi
::log()->debug($e->getMessage());
369 echo 'Invalid or missing data';
374 * @param array $input
376 * @throws \CRM_Core_Exception
378 public function getInput(&$input) {
379 $billingID = CRM_Core_BAO_LocationType
::getBilling();
380 $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
381 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
382 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
383 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
384 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
387 "first_name" => 'first_name',
388 "last_name" => 'last_name',
389 "street_address-{$billingID}" => 'address_street',
390 "city-{$billingID}" => 'address_city',
391 "state-{$billingID}" => 'address_state',
392 "postal_code-{$billingID}" => 'address_zip',
393 "country-{$billingID}" => 'address_country_code',
395 foreach ($lookup as $name => $paypalName) {
396 $value = $this->retrieve($paypalName, 'String', FALSE);
397 $input[$name] = $value ?
$value : NULL;
400 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
401 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
402 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
403 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
405 $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
406 if (!empty($paymentDate)) {
407 $receiveDateTime = new DateTime($paymentDate);
409 * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST
410 * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system
412 $input['receive_date'] = CRM_Utils_Date
::convertDateToLocalTime($receiveDateTime);
417 * Gets PaymentProcessorID for PayPal
419 * @param array $input
423 * @throws \CRM_Core_Exception
424 * @throws \CiviCRM_API3_Exception
426 public function getPayPalPaymentProcessorID($input, $ids) {
427 // First we try and retrieve from POST params
428 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
429 if (!empty($paymentProcessorID)) {
430 return $paymentProcessorID;
433 // Then we try and get it from recurring contribution ID
434 if (!empty($ids['contributionRecur'])) {
435 $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', [
436 'id' => $ids['contributionRecur'],
437 'return' => ['payment_processor_id'],
439 if (!empty($contributionRecur['payment_processor_id'])) {
440 return $contributionRecur['payment_processor_id'];
444 // This is an unreliable method as there could be more than one instance.
445 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
446 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
447 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
448 // & call completetransaction or call fail? (which may not exist yet).
450 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');
451 // Then we try and retrieve based on business email ID
452 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name');
454 'user_name' => $this->retrieve('business', 'String', FALSE),
455 'payment_processor_type_id' => $paymentProcessorTypeID,
456 'is_test' => empty($input['is_test']) ?
0 : 1,
457 'options' => ['limit' => 1],
460 $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams);
461 if (empty($paymentProcessorID)) {
462 throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
464 return $paymentProcessorID;