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_PayPalProIPN
extends CRM_Core_Payment_BaseIPN
{
20 * Input parameters from payment processor. Store these so that
21 * the code does not need to keep retrieving from the http request
24 protected $_inputParameters = [];
27 * Store for the variables from the invoice string.
30 protected $_invoiceData = [];
33 * Is this a payment express transaction.
36 protected $_isPaymentExpress = FALSE;
41 * Are we dealing with an event an 'anything else' (contribute).
45 protected $_component = 'contribute';
48 * Constructor function.
50 * @param array $inputData
51 * Contents of HTTP REQUEST.
53 * @throws CRM_Core_Exception
55 public function __construct($inputData) {
56 $this->setInputParameters($inputData);
57 $this->setInvoiceData();
58 parent
::__construct();
62 * get the values from the rp_invoice_id string.
65 * E.g. i, values are stored in the string with letter codes.
67 * Throw exception if not found
69 * @throws CRM_Core_Exception
72 public function getValue($name, $abort = TRUE) {
73 if ($abort && empty($this->_invoiceData
[$name])) {
74 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
77 return $this->_invoiceData
[$name] ??
NULL;
82 * Set $this->_invoiceData from the input array
84 public function setInvoiceData() {
85 if (empty($this->_inputParameters
['rp_invoice_id'])) {
86 $this->_isPaymentExpress
= TRUE;
89 $rpInvoiceArray = explode('&', $this->_inputParameters
['rp_invoice_id']);
90 // for clarify let's also store without the single letter unreadable
91 //@todo after more refactoring we might ditch storing the one letter stuff
96 'b' => 'contribution_id',
97 'r' => 'contribution_recur_id',
98 'p' => 'participant_id',
101 foreach ($rpInvoiceArray as $rpInvoiceValue) {
102 $rpValueArray = explode('=', $rpInvoiceValue);
103 $this->_invoiceData
[$rpValueArray[0]] = $rpValueArray[1];
104 $this->_inputParameters
[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
105 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
106 // alphabet with more letters.
107 // the mode will always be resolved before the mystery p is reached
108 if ($rpValueArray[1] === 'contribute') {
109 $mapping['p'] = 'contribution_page_id';
112 if (empty($this->_inputParameters
['component'])) {
113 $this->_isPaymentExpress
= TRUE;
118 * @param string $name
119 * Of variable to return.
120 * @param string $type
124 * @param string $location
129 * @throws CRM_Core_Exception
132 public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
133 $value = CRM_Utils_Type
::validate(
134 CRM_Utils_Array
::value($name, $this->_inputParameters
),
138 if ($abort && $value === NULL) {
139 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
145 * Process recurring contributions.
147 * @param array $input
149 * @param array $objects
152 * @throws \CRM_Core_Exception
153 * @throws \CiviCRM_API3_Exception
155 public function recur($input, $ids, $objects, $first) {
156 if (!isset($input['txnType'])) {
157 Civi
::log()->debug('PayPalProIPN: Could not find txn_type in input request.');
158 echo 'Failure: Invalid parameters<p>';
162 $recur = &$objects['contributionRecur'];
164 // make sure the invoice ids match
165 // make sure the invoice is valid and matches what we have in
166 // the contribution record
167 if ($recur->invoice_id
!= $input['invoice']) {
168 Civi
::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id
. ' input is ' . $input['invoice']);
169 echo 'Failure: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id
. " input is " . $input['invoice'];
173 $now = date('YmdHis');
175 $sendNotification = FALSE;
176 $subscriptionPaymentStatus = NULL;
177 //List of Transaction Type
179 recurring_payment_profile_created RP Profile Created
180 recurring_payment RP Successful Payment
181 recurring_payment_failed RP Failed Payment
182 recurring_payment_profile_cancel RP Profile Cancelled
183 recurring_payment_expired RP Profile Expired
184 recurring_payment_skipped RP Profile Skipped
185 recurring_payment_outstanding_payment RP Successful Outstanding Payment
186 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
187 recurring_payment_suspended RP Profile Suspended
188 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
191 //set transaction type
192 $txnType = $this->retrieve('txn_type', 'String');
193 //Changes for paypal pro recurring payment
194 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate'));
196 case 'recurring_payment_profile_created':
197 if (in_array($recur->contribution_status_id
, [
198 $contributionStatuses['Pending'],
199 $contributionStatuses['In Progress'],
201 && !empty($recur->processor_id
)
203 echo "already handled";
206 $recur->create_date
= $now;
207 $recur->contribution_status_id
= $contributionStatuses['Pending'];
208 $recur->processor_id
= $this->retrieve('recurring_payment_id', 'String');
209 $recur->trxn_id
= $recur->processor_id
;
210 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
211 $sendNotification = TRUE;
214 case 'recurring_payment':
216 $recur->start_date
= $now;
219 if ($input['paymentStatus'] != 'Completed') {
220 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
223 // In future moving to create pending & then complete, but this OK for now.
224 // Also consider accepting 'Failed' like other processors.
225 $input['contribution_status_id'] = $contributionStatuses['Completed'];
226 $input['invoice_id'] = md5(uniqid(rand(), TRUE));
227 $input['original_contribution_id'] = $ids['contribution'];
228 $input['contribution_recur_id'] = $ids['contributionRecur'];
230 civicrm_api3('Contribution', 'repeattransaction', $input);
234 //contribution installment is completed
235 if ($this->retrieve('profile_status', 'String') == 'Expired') {
236 if (!empty($recur->end_date
)) {
237 echo "already handled";
240 $recur->contribution_status_id
= $contributionStatuses['Completed'];
241 $recur->end_date
= $now;
242 $sendNotification = TRUE;
243 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
246 // make sure the contribution status is not done
247 // since order of ipn's is unknown
248 if ($recur->contribution_status_id
!= $contributionStatuses['Completed']) {
249 $recur->contribution_status_id
= $contributionStatuses['In Progress'];
256 if ($sendNotification) {
257 $autoRenewMembership = FALSE;
259 isset($ids['membership']) && $ids['membership']
261 $autoRenewMembership = TRUE;
263 //send recurring Notification email for user
264 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
266 $ids['contributionPage'],
272 if ($txnType != 'recurring_payment') {
276 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
277 $objects['contribution']->receive_date
= !empty($input['payment_date']) ?
date('YmdHis', strtotime($input['payment_date'])) : $now;
279 $this->single($input, [
280 'related_contact' => $ids['related_contact'] ??
NULL,
281 'participant' => !empty($objects['participant']) ?
$objects['participant']->id
: NULL,
282 'contributionRecur' => !empty($objects['contributionRecur']) ?
$objects['contributionRecur']->id
: NULL,
283 ], $objects, TRUE, $first);
287 * @param array $input
289 * @param array $objects
295 public function single($input, $ids, $objects, $recur = FALSE, $first = FALSE) {
296 $contribution = &$objects['contribution'];
298 // make sure the invoice is valid and matches what we have in the contribution record
299 if ((!$recur) ||
($recur && $first)) {
300 if ($contribution->invoice_id
!= $input['invoice']) {
301 Civi
::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request.');
302 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id
. " and input is " . $input['invoice'];
307 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
311 if ($contribution->total_amount
!= $input['amount']) {
312 Civi
::log()->debug('PayPalProIPN: Amount values dont match between database and IPN request.');
313 echo "Failure: Amount values dont match between database and IPN request<p>";
318 $contribution->total_amount
= $input['amount'];
321 $status = $input['paymentStatus'];
322 if ($status === 'Denied' ||
$status === 'Failed' ||
$status === 'Voided') {
323 $this->failed($objects);
326 if ($status === 'Pending') {
327 Civi
::log()->debug('Returning since contribution status is Pending');
330 elseif ($status === 'Refunded' ||
$status === 'Reversed') {
331 $this->cancelled($objects);
334 elseif ($status !== 'Completed') {
335 Civi
::log()->debug('Returning since contribution status is not handled');
339 // check if contribution is already completed, if so we ignore this ipn
340 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
341 if ($contribution->contribution_status_id
== $completedStatusId) {
342 Civi
::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
343 echo 'Success: Contribution has already been handled<p>';
347 CRM_Contribute_BAO_Contribution
::completeOrder($input, $ids, $objects['contribution']);
351 * Gets PaymentProcessorID for PayPal
355 public function getPayPalPaymentProcessorID() {
356 // This is an unreliable method as there could be more than one instance.
357 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
358 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
359 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
360 // & call completetransaction or call fail? (which may not exist yet).
362 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');
364 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
365 'PayPal', 'id', 'name'
367 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
369 'options' => ['limit' => 1],
370 'payment_processor_type_id' => $paymentProcessorTypeID,
377 * This is the main function to call. It should be sufficient to instantiate the class
378 * (with the input parameters) & call this & all will be done
380 * @todo the references to POST throughout this class need to be removed
383 public function main() {
384 CRM_Core_Error
::debug_var('GET', $_GET, TRUE, TRUE);
385 CRM_Core_Error
::debug_var('POST', $_POST, TRUE, TRUE);
387 if ($this->_isPaymentExpress
) {
388 $this->handlePaymentExpress();
391 $objects = $ids = $input = [];
392 $this->_component
= $input['component'] = self
::getValue('m');
393 $input['invoice'] = self
::getValue('i', TRUE);
394 // get the contribution and contact ids from the GET params
395 $ids['contact'] = self
::getValue('c', TRUE);
396 $ids['contribution'] = self
::getValue('b', TRUE);
398 $this->getInput($input);
400 if ($this->_component
== 'event') {
401 $ids['event'] = self
::getValue('e', TRUE);
402 $ids['participant'] = self
::getValue('p', TRUE);
403 $ids['contributionRecur'] = self
::getValue('r', FALSE);
406 // get the optional ids
407 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
408 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
409 $ids['membership'] = self
::retrieve('membershipID', 'Integer', 'GET', FALSE);
410 $ids['contributionRecur'] = self
::getValue('r', FALSE);
411 $ids['contributionPage'] = self
::getValue('p', FALSE);
412 $ids['related_contact'] = self
::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
413 $ids['onbehalf_dupe_alert'] = self
::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
416 if (!$ids['membership'] && $ids['contributionRecur']) {
419 FROM civicrm_membership m
420 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
421 WHERE m.contribution_recur_id = %2
424 1 => [$ids['contribution'], 'Integer'],
425 2 => [$ids['contributionRecur'], 'Integer'],
427 if ($membershipId = CRM_Core_DAO
::singleValueQuery($sql, $sqlParams)) {
428 $ids['membership'] = $membershipId;
432 $paymentProcessorID = CRM_Utils_Array
::value('processor_id', $this->_inputParameters
);
433 if (!$paymentProcessorID) {
434 $paymentProcessorID = self
::getPayPalPaymentProcessorID();
437 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
441 $input['payment_processor_id'] = $paymentProcessorID;
443 if ($ids['contributionRecur']) {
444 // check if first contribution is completed, else complete first contribution
446 $completedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
447 if ($objects['contribution']->contribution_status_id
== $completedStatusId) {
450 $this->recur($input, $ids, $objects, $first);
454 $this->single($input, [
455 'related_contact' => $ids['related_contact'] ??
NULL,
456 'participant' => !empty($objects['participant']) ?
$objects['participant']->id
: NULL,
457 'contributionRecur' => !empty($objects['contributionRecur']) ?
$objects['contributionRecur']->id
: NULL,
458 ], $objects, FALSE, FALSE);
460 catch (CRM_Core_Exception
$e) {
461 Civi
::log()->debug($e->getMessage());
462 echo 'Invalid or missing data';
467 * @param array $input
470 * @throws CRM_Core_Exception
472 public function getInput(&$input) {
473 $billingID = CRM_Core_BAO_LocationType
::getBilling();
475 $input['txnType'] = self
::retrieve('txn_type', 'String', 'POST', FALSE);
476 $input['paymentStatus'] = self
::retrieve('payment_status', 'String', 'POST', FALSE);
478 $input['amount'] = self
::retrieve('mc_gross', 'Money', 'POST', FALSE);
479 $input['reasonCode'] = self
::retrieve('ReasonCode', 'String', 'POST', FALSE);
482 "first_name" => 'first_name',
483 "last_name" => 'last_name',
484 "street_address-{$billingID}" => 'address_street',
485 "city-{$billingID}" => 'address_city',
486 "state-{$billingID}" => 'address_state',
487 "postal_code-{$billingID}" => 'address_zip',
488 "country-{$billingID}" => 'address_country_code',
490 foreach ($lookup as $name => $paypalName) {
491 $value = self
::retrieve($paypalName, 'String', 'POST', FALSE);
492 $input[$name] = $value ?
$value : NULL;
495 $input['is_test'] = self
::retrieve('test_ipn', 'Integer', 'POST', FALSE);
496 $input['fee_amount'] = self
::retrieve('mc_fee', 'Money', 'POST', FALSE);
497 $input['net_amount'] = self
::retrieve('settle_amount', 'Money', 'POST', FALSE);
498 $input['trxn_id'] = self
::retrieve('txn_id', 'String', 'POST', FALSE);
499 $input['payment_date'] = $input['receive_date'] = self
::retrieve('payment_date', 'String', 'POST', FALSE);
500 $input['total_amount'] = $input['amount'];
504 * Handle payment express IPNs.
506 * For one off IPNS no actual response is required
507 * Recurring is more difficult as we have limited confirmation material
508 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
510 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
511 * then the quasi security of the ids array might be required - although better to
512 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
513 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
514 * only contribute is handled
516 public function handlePaymentExpress() {
517 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
519 // also note that a lot of the complexity above could be removed if we used
520 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
521 // as membership id etc can be derived by the load objects fn
522 $objects = $ids = $input = [];
524 $input['invoice'] = self
::getValue('i', FALSE);
525 //Avoid return in case of unit test.
526 if (empty($input['invoice']) && empty($this->_inputParameters
['is_unit_test'])) {
529 $input['txnType'] = $this->retrieve('txn_type', 'String');
530 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
531 'return' => 'contact_id, id, payment_processor_id',
532 'invoice_id' => $input['invoice'],
535 if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
536 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
539 $this->getInput($input, $ids);
540 if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
541 throw new CRM_Core_Exception('This transaction has already been processed');
544 $ids['contact'] = $contributionRecur['contact_id'];
545 $ids['contributionRecur'] = $contributionRecur['id'];
546 $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
548 $ids['contribution'] = $result['id'];
549 //@todo hardcoding 'pending' for now
550 $pendingStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
551 if ($result['contribution_status_id'] == $pendingStatusId) {
554 // arg api won't get this - fix it
555 $ids['contributionPage'] = CRM_Core_DAO
::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", [
557 $ids['contribution'],
561 // only handle component at this stage - not terribly sure how a recurring event payment would arise
562 // & suspec main function may be a victom of copy & paste
563 // membership would be an easy add - but not relevant to my customer...
564 $this->_component
= $input['component'] = 'contribute';
565 $input['trxn_date'] = date('Y-m-d H:i:s', strtotime(self
::retrieve('time_created', 'String')));
566 $paymentProcessorID = $contributionRecur['payment_processor_id'];
568 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
569 throw new CRM_Core_Exception('Data did not validate');
571 $this->recur($input, $ids, $objects, $isFirst);
575 * Function check if transaction already exists.
576 * @param string $trxn_id
579 public function transactionExists($trxn_id) {
580 if (CRM_Core_DAO
::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
582 1 => [$trxn_id, 'String'],