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
33 class CRM_Core_Payment_PayPalProIPN
extends CRM_Core_Payment_BaseIPN
{
35 public static $_paymentProcessor = NULL;
38 * Input parameters from payment processor. Store these so that
39 * the code does not need to keep retrieving from the http request
42 protected $_inputParameters = [];
45 * Store for the variables from the invoice string.
48 protected $_invoiceData = [];
51 * Is this a payment express transaction.
54 protected $_isPaymentExpress = FALSE;
57 * Are we dealing with an event an 'anything else' (contribute)
58 * @var string component
60 protected $_component = 'contribute';
63 * Constructor function.
65 * @param array $inputData
66 * Contents of HTTP REQUEST.
68 * @throws CRM_Core_Exception
70 public function __construct($inputData) {
71 $this->setInputParameters($inputData);
72 $this->setInvoiceData();
73 parent
::__construct();
77 * get the values from the rp_invoice_id string.
80 * E.g. i, values are stored in the string with letter codes.
82 * Throw exception if not found
84 * @throws CRM_Core_Exception
87 public function getValue($name, $abort = TRUE) {
88 if ($abort && empty($this->_invoiceData
[$name])) {
89 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
92 return CRM_Utils_Array
::value($name, $this->_invoiceData
);
97 * Set $this->_invoiceData from the input array
99 public function setInvoiceData() {
100 if (empty($this->_inputParameters
['rp_invoice_id'])) {
101 $this->_isPaymentExpress
= TRUE;
104 $rpInvoiceArray = explode('&', $this->_inputParameters
['rp_invoice_id']);
105 // for clarify let's also store without the single letter unreadable
106 //@todo after more refactoring we might ditch storing the one letter stuff
111 'b' => 'contribution_id',
112 'r' => 'contribution_recur_id',
113 'p' => 'participant_id',
116 foreach ($rpInvoiceArray as $rpInvoiceValue) {
117 $rpValueArray = explode('=', $rpInvoiceValue);
118 $this->_invoiceData
[$rpValueArray[0]] = $rpValueArray[1];
119 $this->_inputParameters
[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
120 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
121 // alphabet with more letters.
122 // the mode will always be resolved before the mystery p is reached
123 if ($rpValueArray[1] == 'contribute') {
124 $mapping['p'] = 'contribution_page_id';
127 if (empty($this->_inputParameters
['component'])) {
128 $this->_isPaymentExpress
= TRUE;
133 * @param string $name
134 * Of variable to return.
135 * @param string $type
139 * @param string $location
144 * @throws CRM_Core_Exception
147 public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
148 $value = CRM_Utils_Type
::validate(
149 CRM_Utils_Array
::value($name, $this->_inputParameters
),
153 if ($abort && $value === NULL) {
154 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
160 * Process recurring contributions.
161 * @param array $input
163 * @param array $objects
167 public function recur(&$input, &$ids, &$objects, $first) {
168 if (!isset($input['txnType'])) {
169 Civi
::log()->debug('PayPalProIPN: Could not find txn_type in input request.');
170 echo "Failure: Invalid parameters<p>";
174 $recur = &$objects['contributionRecur'];
176 // make sure the invoice ids match
177 // make sure the invoice is valid and matches what we have in
178 // the contribution record
179 if ($recur->invoice_id
!= $input['invoice']) {
180 Civi
::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id
. ' input is ' . $input['invoice']);
181 echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id
. " input is " . $input['invoice'];
185 $now = date('YmdHis');
187 // fix dates that already exist
188 $dates = ['create', 'start', 'end', 'cancel', 'modified'];
189 foreach ($dates as $date) {
190 $name = "{$date}_date";
192 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
196 $sendNotification = FALSE;
197 $subscriptionPaymentStatus = NULL;
198 //List of Transaction Type
200 recurring_payment_profile_created RP Profile Created
201 recurring_payment RP Successful Payment
202 recurring_payment_failed RP Failed Payment
203 recurring_payment_profile_cancel RP Profile Cancelled
204 recurring_payment_expired RP Profile Expired
205 recurring_payment_skipped RP Profile Skipped
206 recurring_payment_outstanding_payment RP Successful Outstanding Payment
207 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
208 recurring_payment_suspended RP Profile Suspended
209 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
212 //set transaction type
213 $txnType = $this->retrieve('txn_type', 'String');
214 //Changes for paypal pro recurring payment
215 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate'));
217 case 'recurring_payment_profile_created':
218 if (in_array($recur->contribution_status_id
, [
219 $contributionStatuses['Pending'],
220 $contributionStatuses['In Progress'],
222 && !empty($recur->processor_id
)
224 echo "already handled";
227 $recur->create_date
= $now;
228 $recur->contribution_status_id
= $contributionStatuses['Pending'];
229 $recur->processor_id
= $this->retrieve('recurring_payment_id', 'String');
230 $recur->trxn_id
= $recur->processor_id
;
231 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
232 $sendNotification = TRUE;
235 case 'recurring_payment':
237 $recur->start_date
= $now;
240 if ($input['paymentStatus'] != 'Completed') {
241 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
244 // In future moving to create pending & then complete, but this OK for now.
245 // Also consider accepting 'Failed' like other processors.
246 $input['contribution_status_id'] = $contributionStatuses['Completed'];
247 $input['invoice_id'] = md5(uniqid(rand(), TRUE));
248 $input['original_contribution_id'] = $ids['contribution'];
249 $input['contribution_recur_id'] = $ids['contributionRecur'];
251 civicrm_api3('Contribution', 'repeattransaction', $input);
255 //contribution installment is completed
256 if ($this->retrieve('profile_status', 'String') == 'Expired') {
257 if (!empty($recur->end_date
)) {
258 echo "already handled";
261 $recur->contribution_status_id
= $contributionStatuses['Completed'];
262 $recur->end_date
= $now;
263 $sendNotification = TRUE;
264 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
267 // make sure the contribution status is not done
268 // since order of ipn's is unknown
269 if ($recur->contribution_status_id
!= $contributionStatuses['Completed']) {
270 $recur->contribution_status_id
= $contributionStatuses['In Progress'];
277 if ($sendNotification) {
278 $autoRenewMembership = FALSE;
280 isset($ids['membership']) && $ids['membership']
282 $autoRenewMembership = TRUE;
284 //send recurring Notification email for user
285 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
287 $ids['contributionPage'],
293 if ($txnType != 'recurring_payment') {
298 //check if this contribution transaction is already processed
299 //if not create a contribution and then get it processed
300 $contribution = new CRM_Contribute_BAO_Contribution();
301 $contribution->trxn_id
= $input['trxn_id'];
302 if ($contribution->trxn_id
&& $contribution->find()) {
303 Civi
::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
304 echo "Success: Contribution has already been handled<p>";
308 $contribution->contact_id
= $recur->contact_id
;
309 $contribution->financial_type_id
= $objects['contributionType']->id
;
310 $contribution->contribution_page_id
= $ids['contributionPage'];
311 $contribution->contribution_recur_id
= $ids['contributionRecur'];
312 $contribution->currency
= $objects['contribution']->currency
;
313 $contribution->payment_instrument_id
= $objects['contribution']->payment_instrument_id
;
314 $contribution->amount_level
= $objects['contribution']->amount_level
;
315 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
316 $objects['contribution'] = &$contribution;
317 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
319 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
320 $objects['contribution']->receive_date
= !empty($input['payment_date']) ?
date('YmdHis', strtotime($input['payment_date'])) : $now;
322 $this->single($input, $ids, $objects, TRUE, $first);
326 * @param array $input
328 * @param array $objects
334 public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
335 $contribution = &$objects['contribution'];
337 // make sure the invoice is valid and matches what we have in the contribution record
338 if ((!$recur) ||
($recur && $first)) {
339 if ($contribution->invoice_id
!= $input['invoice']) {
340 Civi
::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request.');
341 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id
. " and input is " . $input['invoice'];
346 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
350 if ($contribution->total_amount
!= $input['amount']) {
351 Civi
::log()->debug('PayPalProIPN: Amount values dont match between database and IPN request.');
352 echo "Failure: Amount values dont match between database and IPN request<p>";
357 $contribution->total_amount
= $input['amount'];
360 $transaction = new CRM_Core_Transaction();
362 $status = $input['paymentStatus'];
363 if ($status == 'Denied' ||
$status == 'Failed' ||
$status == 'Voided') {
364 $this->failed($objects, $transaction);
367 elseif ($status == 'Pending') {
368 $this->pending($objects, $transaction);
371 elseif ($status == 'Refunded' ||
$status == 'Reversed') {
372 $this->cancelled($objects, $transaction);
375 elseif ($status != 'Completed') {
376 $this->unhandled($objects, $transaction);
380 // check if contribution is already completed, if so we ignore this ipn
381 $completedStatusId = CRM_Core_Pseudoconstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
382 if ($contribution->contribution_status_id
== $completedStatusId) {
383 $transaction->commit();
384 Civi
::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
385 echo "Success: Contribution has already been handled<p>";
389 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
393 * Gets PaymentProcessorID for PayPal
397 public function getPayPalPaymentProcessorID() {
398 // This is an unreliable method as there could be more than one instance.
399 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
400 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
401 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
402 // & call completetransaction or call fail? (which may not exist yet).
404 Civi
::log()->warning('Unreliable method used to get payment_processor_id for PayPal Pro IPN - this will cause problems if you have more than one instance');
406 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
407 'PayPal', 'id', 'name'
409 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
411 'options' => ['limit' => 1],
412 'payment_processor_type_id' => $paymentProcessorTypeID,
419 * This is the main function to call. It should be sufficient to instantiate the class
420 * (with the input parameters) & call this & all will be done
422 * @todo the references to POST throughout this class need to be removed
425 public function main() {
426 CRM_Core_Error
::debug_var('GET', $_GET, TRUE, TRUE);
427 CRM_Core_Error
::debug_var('POST', $_POST, TRUE, TRUE);
428 if ($this->_isPaymentExpress
) {
429 $this->handlePaymentExpress();
432 $objects = $ids = $input = [];
433 $this->_component
= $input['component'] = self
::getValue('m');
434 $input['invoice'] = self
::getValue('i', TRUE);
435 // get the contribution and contact ids from the GET params
436 $ids['contact'] = self
::getValue('c', TRUE);
437 $ids['contribution'] = self
::getValue('b', TRUE);
439 $this->getInput($input, $ids);
441 if ($this->_component
== 'event') {
442 $ids['event'] = self
::getValue('e', TRUE);
443 $ids['participant'] = self
::getValue('p', TRUE);
444 $ids['contributionRecur'] = self
::getValue('r', FALSE);
447 // get the optional ids
448 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
449 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
450 $ids['membership'] = self
::retrieve('membershipID', 'Integer', 'GET', FALSE);
451 $ids['contributionRecur'] = self
::getValue('r', FALSE);
452 $ids['contributionPage'] = self
::getValue('p', FALSE);
453 $ids['related_contact'] = self
::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
454 $ids['onbehalf_dupe_alert'] = self
::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
457 if (!$ids['membership'] && $ids['contributionRecur']) {
460 FROM civicrm_membership m
461 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
462 WHERE m.contribution_recur_id = %2
465 1 => [$ids['contribution'], 'Integer'],
466 2 => [$ids['contributionRecur'], 'Integer'],
468 if ($membershipId = CRM_Core_DAO
::singleValueQuery($sql, $sqlParams)) {
469 $ids['membership'] = $membershipId;
473 $paymentProcessorID = self
::getPayPalPaymentProcessorID();
475 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
479 self
::$_paymentProcessor = &$objects['paymentProcessor'];
480 //?? how on earth would we not have component be one of these?
481 // they are the only valid settings & this IPN file can't even be called without one of them
482 // grepping for this class doesn't find other paths to call this class
483 if ($this->_component
== 'contribute' ||
$this->_component
== 'event') {
484 if ($ids['contributionRecur']) {
485 // check if first contribution is completed, else complete first contribution
487 $completedStatusId = CRM_Core_Pseudoconstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
488 if ($objects['contribution']->contribution_status_id
== $completedStatusId) {
491 $this->recur($input, $ids, $objects, $first);
495 $this->single($input, $ids, $objects, FALSE, FALSE);
499 * @param array $input
503 * @throws CRM_Core_Exception
505 public function getInput(&$input, &$ids) {
506 if (!$this->getBillingID($ids)) {
510 $input['txnType'] = self
::retrieve('txn_type', 'String', 'POST', FALSE);
511 $input['paymentStatus'] = self
::retrieve('payment_status', 'String', 'POST', FALSE);
513 $input['amount'] = self
::retrieve('mc_gross', 'Money', 'POST', FALSE);
514 $input['reasonCode'] = self
::retrieve('ReasonCode', 'String', 'POST', FALSE);
516 $billingID = $ids['billing'];
518 "first_name" => 'first_name',
519 "last_name" => 'last_name',
520 "street_address-{$billingID}" => 'address_street',
521 "city-{$billingID}" => 'address_city',
522 "state-{$billingID}" => 'address_state',
523 "postal_code-{$billingID}" => 'address_zip',
524 "country-{$billingID}" => 'address_country_code',
526 foreach ($lookup as $name => $paypalName) {
527 $value = self
::retrieve($paypalName, 'String', 'POST', FALSE);
528 $input[$name] = $value ?
$value : NULL;
531 $input['is_test'] = self
::retrieve('test_ipn', 'Integer', 'POST', FALSE);
532 $input['fee_amount'] = self
::retrieve('mc_fee', 'Money', 'POST', FALSE);
533 $input['net_amount'] = self
::retrieve('settle_amount', 'Money', 'POST', FALSE);
534 $input['trxn_id'] = self
::retrieve('txn_id', 'String', 'POST', FALSE);
535 $input['payment_date'] = $input['receive_date'] = self
::retrieve('payment_date', 'String', 'POST', FALSE);
536 $input['total_amount'] = $input['amount'];
540 * Handle payment express IPNs.
542 * For one off IPNS no actual response is required
543 * Recurring is more difficult as we have limited confirmation material
544 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
546 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
547 * then the quasi security of the ids array might be required - although better to
548 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
549 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
550 * only contribute is handled
552 public function handlePaymentExpress() {
553 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
555 // also note that a lot of the complexity above could be removed if we used
556 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
557 // as membership id etc can be derived by the load objects fn
558 $objects = $ids = $input = [];
560 $input['invoice'] = self
::getValue('i', FALSE);
561 //Avoid return in case of unit test.
562 if (empty($input['invoice']) && empty($this->_inputParameters
['is_unit_test'])) {
565 $input['txnType'] = $this->retrieve('txn_type', 'String');
566 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
567 'return' => 'contact_id, id, payment_processor_id',
568 'invoice_id' => $input['invoice'],
571 if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
572 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
575 $this->getInput($input, $ids);
576 if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
577 throw new CRM_Core_Exception('This transaction has already been processed');
580 $ids['contact'] = $contributionRecur['contact_id'];
581 $ids['contributionRecur'] = $contributionRecur['id'];
582 $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
584 $ids['contribution'] = $result['id'];
585 //@todo hardcoding 'pending' for now
586 $pendingStatusId = CRM_Core_Pseudoconstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
587 if ($result['contribution_status_id'] == $pendingStatusId) {
590 // arg api won't get this - fix it
591 $ids['contributionPage'] = CRM_Core_DAO
::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", [
593 $ids['contribution'],
597 // only handle component at this stage - not terribly sure how a recurring event payment would arise
598 // & suspec main function may be a victom of copy & paste
599 // membership would be an easy add - but not relevant to my customer...
600 $this->_component
= $input['component'] = 'contribute';
601 $input['trxn_date'] = date('Y-m-d-H-i-s', strtotime(self
::retrieve('time_created', 'String')));
602 $paymentProcessorID = $contributionRecur['payment_processor_id'];
604 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
605 throw new CRM_Core_Exception('Data did not validate');
607 $this->recur($input, $ids, $objects, $isFirst);
611 * Function check if transaction already exists.
612 * @param string $trxn_id
615 public function transactionExists($trxn_id) {
616 if (CRM_Core_DAO
::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
618 1 => [$trxn_id, 'String'],