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 +--------------------------------------------------------------------+
12 use Civi\Api4\Contribution
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 class CRM_Core_Payment_PayPalProIPN
extends CRM_Core_Payment_BaseIPN
{
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 * Store for the variables from the invoice string.
32 protected $_invoiceData = [];
35 * Is this a payment express transaction.
38 protected $_isPaymentExpress = FALSE;
41 * Recurring contribution ID.
45 protected $contributionRecurID;
48 * Recurring contribution object.
50 * @var \CRM_Contribute_BAO_ContributionRecur
52 protected $contributionRecurObject;
55 * Contribution object.
57 * @var \CRM_Contribute_BAO_Contribution
59 protected $contributionObject;
65 protected $contributionID;
68 * Get the recurring contribution ID, if any.
72 * @throws \CRM_Core_Exception
74 public function getContributionRecurID(): ?
int {
75 if (!$this->contributionRecurID
&& $this->getValue('r', FALSE)) {
76 $this->contributionRecurID
= (int) $this->getValue('r', FALSE);
78 return $this->contributionRecurID
;
82 * Get the relevant contribution ID.
84 * This is the contribution being paid or the original in the
89 * @throws \CRM_Core_Exception
91 protected function getContributionID(): int {
92 if (!$this->contributionID
&& $this->getValue('b', TRUE)) {
93 $this->contributionID
= (int) $this->getValue('b', TRUE);
95 return $this->contributionID
;
99 * @param int|null $contributionRecurID
101 public function setContributionRecurID(?
int $contributionRecurID): void
{
102 $this->contributionRecurID
= $contributionRecurID;
106 * Set contribution ID.
108 * @param int $contributionID
110 public function setContributionID(int $contributionID): void
{
111 $this->contributionID
= $contributionID;
117 * Are we dealing with an event an 'anything else' (contribute).
121 protected $_component = 'contribute';
124 * Constructor function.
126 * @param array $inputData
127 * Contents of HTTP REQUEST.
129 * @throws CRM_Core_Exception
131 public function __construct($inputData) {
132 $this->setInputParameters($inputData);
133 $this->setInvoiceData();
134 parent
::__construct();
138 * get the values from the rp_invoice_id string.
140 * @param string $name
141 * E.g. i, values are stored in the string with letter codes.
143 * Throw exception if not found
145 * @throws CRM_Core_Exception
148 public function getValue($name, $abort = TRUE) {
149 if ($abort && empty($this->_invoiceData
[$name])) {
150 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
153 return $this->_invoiceData
[$name] ??
NULL;
158 * Set $this->_invoiceData from the input array
160 public function setInvoiceData() {
161 if (empty($this->_inputParameters
['rp_invoice_id'])) {
162 $this->_isPaymentExpress
= TRUE;
165 $rpInvoiceArray = explode('&', $this->_inputParameters
['rp_invoice_id']);
166 // for clarify let's also store without the single letter unreadable
167 //@todo after more refactoring we might ditch storing the one letter stuff
172 'b' => 'contribution_id',
173 'r' => 'contribution_recur_id',
174 'p' => 'participant_id',
177 foreach ($rpInvoiceArray as $rpInvoiceValue) {
178 $rpValueArray = explode('=', $rpInvoiceValue);
179 $this->_invoiceData
[$rpValueArray[0]] = $rpValueArray[1];
180 $this->_inputParameters
[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
181 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
182 // alphabet with more letters.
183 // the mode will always be resolved before the mystery p is reached
184 if ($rpValueArray[1] === 'contribute') {
185 $mapping['p'] = 'contribution_page_id';
188 if (empty($this->_inputParameters
['component'])) {
189 $this->_isPaymentExpress
= TRUE;
194 * @param string $name
195 * Of variable to return.
196 * @param string $type
200 * @param string $location
205 * @throws CRM_Core_Exception
208 public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
209 $value = CRM_Utils_Type
::validate(
210 CRM_Utils_Array
::value($name, $this->_inputParameters
),
214 if ($abort && $value === NULL) {
215 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
221 * Process recurring contributions.
223 * @param array $input
225 * @throws \API_Exception
226 * @throws \CRM_Core_Exception
227 * @throws \CiviCRM_API3_Exception
228 * @throws \Civi\API\Exception\UnauthorizedException
230 public function recur(array $input): void
{
231 // check if first contribution is completed, else complete first contribution
232 $first = !$this->isContributionCompleted();
233 $recur = $this->getContributionRecurObject();
234 if (!isset($input['txnType'])) {
235 Civi
::log()->debug('PayPalProIPN: Could not find txn_type in input request.');
236 echo 'Failure: Invalid parameters<p>';
240 // make sure the invoice ids match
241 // make sure the invoice is valid and matches what we have in
242 // the contribution record
243 if ($recur->invoice_id
!= $input['invoice']) {
244 Civi
::log()->debug('PayPalProIPN: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id
. ' input is ' . $input['invoice']);
245 echo 'Failure: Invoice values dont match between database and IPN request recur is ' . $recur->invoice_id
. " input is " . $input['invoice'];
249 $now = date('YmdHis');
251 $sendNotification = FALSE;
252 $subscriptionPaymentStatus = NULL;
253 //List of Transaction Type
255 recurring_payment_profile_created RP Profile Created
256 recurring_payment RP Successful Payment
257 recurring_payment_failed RP Failed Payment
258 recurring_payment_profile_cancel RP Profile Cancelled
259 recurring_payment_expired RP Profile Expired
260 recurring_payment_skipped RP Profile Skipped
261 recurring_payment_outstanding_payment RP Successful Outstanding Payment
262 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
263 recurring_payment_suspended RP Profile Suspended
264 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
267 //set transaction type
268 $txnType = $this->retrieve('txn_type', 'String');
269 //Changes for paypal pro recurring payment
271 case 'recurring_payment_profile_created':
272 if (in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $recur->contribution_status_id
), [
273 'Pending', 'In Progress',
275 && !empty($recur->processor_id
)
277 echo 'already handled';
280 $recur->create_date
= $now;
281 $recur->contribution_status_id
= CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', 'Pending');
282 $recur->processor_id
= $this->retrieve('recurring_payment_id', 'String');
283 $recur->trxn_id
= $recur->processor_id
;
284 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
285 $sendNotification = TRUE;
288 case 'recurring_payment':
290 if ($input['paymentStatus'] !== 'Completed') {
291 throw new CRM_Core_Exception('Ignore all IPN payments that are not completed');
294 // In future moving to create pending & then complete, but this OK for now.
295 // Also consider accepting 'Failed' like other processors.
296 $input['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', 'Completed');
297 $input['invoice_id'] = md5(uniqid(rand(), TRUE));
298 $input['original_contribution_id'] = $this->getContributionID();
299 $input['contribution_recur_id'] = $this->getContributionRecurID();
301 civicrm_api3('Contribution', 'repeattransaction', $input);
305 //contribution installment is completed
306 if ($this->retrieve('profile_status', 'String') === 'Expired') {
307 if (!empty($recur->end_date
)) {
308 echo 'already handled';
311 $recur->contribution_status_id
= CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', 'Completed');
312 $recur->end_date
= $now;
313 $sendNotification = TRUE;
314 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
322 if ($sendNotification) {
323 //send recurring Notification email for user
324 CRM_Contribute_BAO_ContributionPage
::recurringNotify(
325 $this->getContributionID(),
326 $subscriptionPaymentStatus,
331 if ($txnType !== 'recurring_payment') {
335 $this->single($input);
339 * @param array $input
342 * @throws \API_Exception
343 * @throws \CRM_Core_Exception
344 * @throws \CiviCRM_API3_Exception
346 protected function single(array $input): void
{
348 // make sure the invoice is valid and matches what we have in the contribution record
349 if (!$this->isContributionCompleted()) {
350 if ($this->getContributionObject()->invoice_id
!== $input['invoice']) {
351 throw new CRM_Core_Exception('PayPalProIPN: Invoice values dont match between database and IPN request.');
353 if (!$this->getContributionRecurID() && $this->getContributionObject()->total_amount
!= $input['amount']) {
354 throw new CRM_Core_Exception('PayPalProIPN: Amount values dont match between database and IPN request.');
358 $status = $input['paymentStatus'];
359 if ($status === 'Denied' ||
$status === 'Failed' ||
$status === 'Voided') {
360 Contribution
::update(FALSE)->setValues([
361 'cancel_date' => 'now',
362 'contribution_status_id:name' => 'Failed',
363 ])->addWhere('id', '=', $this->getContributionID())->execute();
364 Civi
::log()->debug('Setting contribution status to Failed');
367 if ($status === 'Pending') {
368 Civi
::log()->debug('Returning since contribution status is Pending');
371 if ($status === 'Refunded' ||
$status === 'Reversed') {
372 Contribution
::update(FALSE)->setValues([
373 'cancel_date' => 'now',
374 'contribution_status_id:name' => 'Cancelled',
375 ])->addWhere('id', '=', $this->getContributionID())->execute();
376 Civi
::log()->debug('Setting contribution status to Cancelled');
379 if ($status !== 'Completed') {
380 Civi
::log()->debug('Returning since contribution status is not handled');
384 if ($this->isContributionCompleted()) {
385 Civi
::log()->debug('PayPalProIPN: Returning since contribution has already been handled.');
386 echo 'Success: Contribution has already been handled<p>';
390 CRM_Contribute_BAO_Contribution
::completeOrder($input, $this->getContributionRecurID(), $this->getContributionID());
394 * Gets PaymentProcessorID for PayPal
398 public function getPayPalPaymentProcessorID() {
399 // This is an unreliable method as there could be more than one instance.
400 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
401 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
402 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
403 // & call completetransaction or call fail? (which may not exist yet).
405 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');
407 $paymentProcessorTypeID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
408 'PayPal', 'id', 'name'
410 return (int) civicrm_api3('PaymentProcessor', 'getvalue', [
412 'options' => ['limit' => 1],
413 'payment_processor_type_id' => $paymentProcessorTypeID,
420 * This is the main function to call. It should be sufficient to instantiate the class
421 * (with the input parameters) & call this & all will be done
423 * @todo the references to POST throughout this class need to be removed
426 public function main(): void
{
427 CRM_Core_Error
::debug_var('GET', $_GET, TRUE, TRUE);
428 CRM_Core_Error
::debug_var('POST', $_POST, TRUE, TRUE);
431 if ($this->_isPaymentExpress
) {
432 $this->handlePaymentExpress();
435 if ($this->getValue('m') === 'event') {
436 // Validate required params.
437 $this->getValue('e');
438 $this->getValue('p');
440 $input['invoice'] = $this->getValue('i');
441 if ($this->getContributionObject()->contact_id
!== $this->getContactID()) {
442 // If the ids do not match then it is possible the contact id in the IPN has been merged into another contact which is why we use the contact_id from the contribution
443 CRM_Core_Error
::debug_log_message('Contact ID in IPN ' . $this->getContactID() . ' not found but contact_id found in contribution ' . $this->getContributionID() . ' used instead');
444 echo 'WARNING: Could not find contact record: ' . $this->getContactID() . '<p>';
447 $this->getInput($input);
448 $input['payment_processor_id'] = $this->_inputParameters
['processor_id'] ??
$this->getPayPalPaymentProcessorID();
450 if ($this->getContributionRecurID()) {
451 $this->recur($input);
455 $this->single($input);
457 catch (Exception
$e) {
458 Civi
::log()->debug($e->getMessage() . ' input {input}', ['input' => $input]);
459 echo 'Invalid or missing data';
464 * @param array $input
467 * @throws CRM_Core_Exception
469 public function getInput(&$input) {
470 $billingID = CRM_Core_BAO_LocationType
::getBilling();
472 $input['txnType'] = self
::retrieve('txn_type', 'String', 'POST', FALSE);
473 $input['paymentStatus'] = self
::retrieve('payment_status', 'String', 'POST', FALSE);
475 $input['amount'] = self
::retrieve('mc_gross', 'Money', 'POST', FALSE);
476 $input['reasonCode'] = self
::retrieve('ReasonCode', 'String', 'POST', FALSE);
479 "first_name" => 'first_name',
480 "last_name" => 'last_name',
481 "street_address-{$billingID}" => 'address_street',
482 "city-{$billingID}" => 'address_city',
483 "state-{$billingID}" => 'address_state',
484 "postal_code-{$billingID}" => 'address_zip',
485 "country-{$billingID}" => 'address_country_code',
487 foreach ($lookup as $name => $paypalName) {
488 $value = self
::retrieve($paypalName, 'String', 'POST', FALSE);
489 $input[$name] = $value ?
$value : NULL;
492 $input['is_test'] = self
::retrieve('test_ipn', 'Integer', 'POST', FALSE);
493 $input['fee_amount'] = self
::retrieve('mc_fee', 'Money', 'POST', FALSE);
494 $input['net_amount'] = self
::retrieve('settle_amount', 'Money', 'POST', FALSE);
495 $input['trxn_id'] = self
::retrieve('txn_id', 'String', 'POST', FALSE);
496 $input['payment_date'] = $input['receive_date'] = self
::retrieve('payment_date', 'String', 'POST', FALSE);
497 $input['total_amount'] = $input['amount'];
501 * Handle payment express IPNs.
503 * For one off IPNS no actual response is required
504 * Recurring is more difficult as we have limited confirmation material
505 * lets look up invoice id in recur_contribution & rely on the unique
506 * transaction id to ensure no duplicated this may not be acceptable to all
507 * sites - e.g. if they are shipping or delivering something in return then
508 * the quasi security of the ids array might be required - although better to
509 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
510 * but let's assume knowledge on invoice id & schedule is enough for now esp
511 * for donations only contribute is handled
513 * @throws \API_Exception
514 * @throws \CRM_Core_Exception
515 * @throws \CiviCRM_API3_Exception
517 public function handlePaymentExpress(): void
{
518 $input = ['invoice' => $this->getValue('i', FALSE)];
519 //Avoid return in case of unit test.
520 if (empty($input['invoice']) && empty($this->_inputParameters
['is_unit_test'])) {
523 $input['txnType'] = $this->retrieve('txn_type', 'String');
524 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', [
525 'return' => 'contact_id, id, payment_processor_id',
526 'invoice_id' => $input['invoice'],
528 $this->setContributionRecurID((int) $contributionRecur['id']);
530 if ($input['txnType'] !== 'recurring_payment' && $input['txnType'] !== 'recurring_payment_profile_created') {
531 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
534 $this->getInput($input);
535 if ($input['txnType'] === 'recurring_payment' && $this->transactionExists($input['trxn_id'])) {
536 throw new CRM_Core_Exception('This transaction has already been processed');
538 $result = civicrm_api3('contribution', 'getsingle', ['invoice_id' => $input['invoice'], 'contribution_test' => '']);
539 $this->setContributionID((int) $result['id']);
540 $input['trxn_date'] = date('Y-m-d H:i:s', strtotime($this->retrieve('time_created', 'String')));
541 $this->recur($input);
545 * Function check if transaction already exists.
546 * @param string $trxn_id
549 public function transactionExists($trxn_id) {
550 if (CRM_Core_DAO
::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
552 1 => [$trxn_id, 'String'],
560 * Get the recurring contribution object.
562 * @return \CRM_Contribute_BAO_ContributionRecur
563 * @throws \CRM_Core_Exception
565 protected function getContributionRecurObject(): CRM_Contribute_BAO_ContributionRecur
{
566 if (!$this->contributionRecurObject
) {
567 $contributionRecur = new CRM_Contribute_BAO_ContributionRecur();
568 $contributionRecur->id
= $this->getContributionRecurID();
569 if (!$contributionRecur->find(TRUE)) {
570 throw new CRM_Core_Exception('Failure: Could not find contribution recur record');
572 return $this->contributionRecurObject
= $contributionRecur;
574 return $this->contributionRecurObject
;
578 * @return \CRM_Contribute_BAO_Contribution
579 * @throws \CRM_Core_Exception
581 protected function getContributionObject(): CRM_Contribute_BAO_Contribution
{
582 if (!$this->contributionObject
) {
583 // Check if the contribution exists
584 // make sure contribution exists and is valid
585 $contribution = new CRM_Contribute_BAO_Contribution();
586 $contribution->id
= $this->getContributionID();
587 if (!$contribution->find(TRUE)) {
588 throw new CRM_Core_Exception('Failure: Could not find contribution record');
590 // The DAO types it as int but doesn't return it as int.
591 $contribution->contact_id
= (int) $contribution->contact_id
;
592 $this->contributionObject
= $contribution;
594 return $this->contributionObject
;
598 * Get the relevant contact ID.
601 * @throws \CRM_Core_Exception
603 protected function getContactID(): int {
604 return $this->getValue('c', TRUE);
608 * Is the original contribution completed.
611 * @throws \CRM_Core_Exception
613 private function isContributionCompleted(): bool {
614 $status = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $this->getContributionObject()->contribution_status_id
);
615 return $status === 'Completed';