3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
34 class CRM_Core_Payment_PayPalIPN
extends CRM_Core_Payment_BaseIPN
{
36 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 = array();
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 = array('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 = array();
312 $component = $this->retrieve('module', 'String');
313 $input['component'] = $component;
315 $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE);
316 $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE);
318 $this->getInput($input, $ids);
320 if ($component == 'event') {
321 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
322 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
325 // get the optional ids
326 $ids['membership'] = $this->retrieve('membershipID', 'Integer', FALSE);
327 $ids['contributionRecur'] = $this->retrieve('contributionRecurID', 'Integer', FALSE);
328 $ids['contributionPage'] = $this->retrieve('contributionPageID', 'Integer', FALSE);
329 $ids['related_contact'] = $this->retrieve('relatedContactID', 'Integer', FALSE);
330 $ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE);
333 $paymentProcessorID = self
::getPayPalPaymentProcessorID($input, $ids);
335 Civi
::log()->debug('PayPalIPN: Received (ContactID: ' . $ids['contact'] . '; trxn_id: ' . $input['trxn_id'] . ').');
337 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
341 self
::$_paymentProcessor = &$objects['paymentProcessor'];
342 if ($component == 'contribute') {
343 if ($ids['contributionRecur']) {
344 // check if first contribution is completed, else complete first contribution
346 $completedStatusId = CRM_Core_Pseudoconstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
347 if ($objects['contribution']->contribution_status_id
== $completedStatusId) {
350 $this->recur($input, $ids, $objects, $first);
354 $this->single($input, $ids, $objects, FALSE, FALSE);
358 * @param array $input
361 * @throws \CRM_Core_Exception
363 public function getInput(&$input, &$ids) {
364 if (!$this->getBillingID($ids)) {
368 $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
369 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
370 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
371 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
372 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
374 $billingID = $ids['billing'];
376 "first_name" => 'first_name',
377 "last_name" => 'last_name',
378 "street_address-{$billingID}" => 'address_street',
379 "city-{$billingID}" => 'address_city',
380 "state-{$billingID}" => 'address_state',
381 "postal_code-{$billingID}" => 'address_zip',
382 "country-{$billingID}" => 'address_country_code',
384 foreach ($lookup as $name => $paypalName) {
385 $value = $this->retrieve($paypalName, 'String', FALSE);
386 $input[$name] = $value ?
$value : NULL;
389 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
390 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
391 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
392 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);
394 $paymentDate = $this->retrieve('payment_date', 'String', FALSE);
395 if (!empty($paymentDate)) {
396 $receiveDateTime = new DateTime($paymentDate);
398 * The `payment_date` that Paypal sends back is in their timezone. Example return: 08:23:05 Jan 11, 2019 PST
399 * Subsequently, we need to account for that, otherwise the recieve time will be incorrect for the local system
401 $systemTimeZone = new DateTimeZone(CRM_Core_Config
::singleton()->userSystem
->getTimeZoneString());
402 $receiveDateTime->setTimezone($systemTimeZone);
403 $input['receive_date'] = $receiveDateTime->format('YmdHis');
409 * Gets PaymentProcessorID for PayPal
411 * @param array $input
415 * @throws \CRM_Core_Exception
416 * @throws \CiviCRM_API3_Exception
418 public function getPayPalPaymentProcessorID($input, $ids) {
419 // First we try and retrieve from POST params
420 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
421 if (!empty($paymentProcessorID)) {
422 return $paymentProcessorID;
425 // Then we try and get it from recurring contribution ID
426 if (!empty($ids['contributionRecur'])) {
427 $contributionRecur = civicrm_api3('ContributionRecur', 'getsingle', array(
428 'id' => $ids['contributionRecur'],
429 'return' => ['payment_processor_id'],
431 if (!empty($contributionRecur['payment_processor_id'])) {
432 return $contributionRecur['payment_processor_id'];
436 // This is an unreliable method as there could be more than one instance.
437 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
438 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
439 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
440 // & call completetransaction or call fail? (which may not exist yet).
442 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');
443 // Then we try and retrieve based on business email ID
444 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name');
446 'user_name' => $this->retrieve('business', 'String', FALSE),
447 'payment_processor_type_id' => $paymentProcessorTypeID,
448 'is_test' => empty($input['is_test']) ?
0 : 1,
449 'options' => ['limit' => 1],
452 $paymentProcessorID = civicrm_api3('PaymentProcessor', 'getvalue', $processorParams);
453 if (empty($paymentProcessorID)) {
454 Throw new CRM_Core_Exception('PayPalIPN: Could not get Payment Processor ID');
456 return $paymentProcessorID;