3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
35 class CRM_Core_Payment_PayPalProIPN
extends CRM_Core_Payment_BaseIPN
{
37 static $_paymentProcessor = NULL;
40 * Input parameters from payment processor. Store these so that
41 * the code does not need to keep retrieving from the http request
44 protected $_inputParameters = array();
47 * Store for the variables from the invoice string
50 protected $_invoiceData = array();
53 * Is this a payment express transaction
55 protected $_isPaymentExpress = FALSE;
58 * Are we dealing with an event an 'anything else' (contribute)
59 * @var string component
61 protected $_component = 'contribute';
64 * Constructor function
66 * @param array $inputData
67 * Contents of HTTP REQUEST.
69 * @throws CRM_Core_Exception
71 public function __construct($inputData) {
72 $this->setInputParameters($inputData);
73 $this->setInvoiceData();
74 parent
::__construct();
78 * get the values from the rp_invoice_id string
81 * E.g. i, values are stored in the string with letter codes.
83 * Throw exception if not found
85 * @throws CRM_Core_Exception
88 public function getValue($name, $abort = TRUE) {
89 if ($abort && empty($this->_invoiceData
[$name])) {
90 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
93 return CRM_Utils_Array
::value($name, $this->_invoiceData
);
98 * Set $this->_invoiceData from the input array
100 public function setInvoiceData() {
101 if (empty($this->_inputParameters
['rp_invoice_id'])) {
102 $this->_isPaymentExpress
= TRUE;
105 $rpInvoiceArray = explode('&', $this->_inputParameters
['rp_invoice_id']);
106 // for clarify let's also store without the single letter unreadable
107 //@todo after more refactoring we might ditch storing the one letter stuff
112 'b' => 'contribution_id',
113 'r' => 'contribution_recur_id',
114 'p' => 'participant_id',
117 foreach ($rpInvoiceArray as $rpInvoiceValue) {
118 $rpValueArray = explode('=', $rpInvoiceValue);
119 $this->_invoiceData
[$rpValueArray[0]] = $rpValueArray[1];
120 $this->_inputParameters
[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
121 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
122 // alphabet with more letters.
123 // the mode will always be resolved before the mystery p is reached
124 if ($rpValueArray[1] == 'contribute') {
125 $mapping['p'] = 'contribution_page_id';
128 if (empty($this->_inputParameters
['component'])) {
129 $this->_isPaymentExpress
= TRUE;
134 * @param string $name
135 * Of variable to return.
136 * @param string $type
140 * @param string $location
145 * @throws CRM_Core_Exception
148 public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
149 $value = CRM_Utils_Type
::validate(
150 CRM_Utils_Array
::value($name, $this->_inputParameters
),
154 if ($abort && $value === NULL) {
155 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
161 * Process recurring contributions
162 * @param array $input
164 * @param array $objects
168 public function recur(&$input, &$ids, &$objects, $first) {
169 if (!isset($input['txnType'])) {
170 CRM_Core_Error
::debug_log_message("Could not find txn_type in input request");
171 echo "Failure: Invalid parameters<p>";
175 if ($input['txnType'] == 'recurring_payment' &&
176 $input['paymentStatus'] != 'Completed'
178 CRM_Core_Error
::debug_log_message("Ignore all IPN payments that are not completed");
179 echo "Failure: Invalid parameters<p>";
183 $recur = &$objects['contributionRecur'];
185 // make sure the invoice ids match
186 // make sure the invoice is valid and matches what we have in
187 // the contribution record
188 if ($recur->invoice_id
!= $input['invoice']) {
189 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id
. " input is " . $input['invoice']);
190 echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id
. " input is " . $input['invoice'];
194 $now = date('YmdHis');
196 // fix dates that already exist
197 $dates = array('create', 'start', 'end', 'cancel', 'modified');
198 foreach ($dates as $date) {
199 $name = "{$date}_date";
201 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
205 $sendNotification = FALSE;
206 $subscriptionPaymentStatus = NULL;
207 //List of Transaction Type
209 recurring_payment_profile_created RP Profile Created
210 recurring_payment RP Sucessful Payment
211 recurring_payment_failed RP Failed Payment
212 recurring_payment_profile_cancel RP Profile Cancelled
213 recurring_payment_expired RP Profile Expired
214 recurring_payment_skipped RP Profile Skipped
215 recurring_payment_outstanding_payment RP Sucessful Outstanding Payment
216 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
217 recurring_payment_suspended RP Profile Suspended
218 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
221 //set transaction type
222 $txnType = $this->retrieve('txn_type', 'String');
223 //Changes for paypal pro recurring payment
224 $contributionStatuses = civicrm_api3('contribution', 'getoptions', array('field' => 'contribution_status_id'));
225 $contributionStatuses = $contributionStatuses['values'];
227 case 'recurring_payment_profile_created':
228 if (in_array($recur->contribution_status_id
, array(
229 array_search('Pending', $contributionStatuses),
230 array_search('In Progress', $contributionStatuses),
232 && !empty($recur->processor_id
)
234 echo "already handled";
237 $recur->create_date
= $now;
238 $recur->contribution_status_id
= 2;
239 $recur->processor_id
= $this->retrieve('recurring_payment_id', 'String');
240 $recur->trxn_id
= $recur->processor_id
;
241 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
242 $sendNotification = TRUE;
245 case 'recurring_payment':
247 $recur->start_date
= $now;
250 $recur->modified_date
= $now;
253 //contribution installment is completed
254 if ($this->retrieve('profile_status', 'String') == 'Expired') {
255 if (!empty($recur->end_date
)) {
256 echo "already handled";
259 $recur->contribution_status_id
= 1;
260 $recur->end_date
= $now;
261 $sendNotification = TRUE;
262 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
265 // make sure the contribution status is not done
266 // since order of ipn's is unknown
267 if ($recur->contribution_status_id
!= 1) {
268 $recur->contribution_status_id
= 5;
275 if ($sendNotification) {
276 $autoRenewMembership = FALSE;
278 isset($ids['membership']) && $ids['membership']
280 $autoRenewMembership = TRUE;
282 //send recurring Notification email for user
283 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
285 $ids['contributionPage'],
291 if ($txnType != 'recurring_payment') {
296 //check if this contribution transaction is already processed
297 //if not create a contribution and then get it processed
298 $contribution = new CRM_Contribute_BAO_Contribution();
299 $contribution->trxn_id
= $input['trxn_id'];
300 if ($contribution->trxn_id
&& $contribution->find()) {
301 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
302 echo "Success: Contribution has already been handled<p>";
306 $contribution->contact_id
= $recur->contact_id
;
307 $contribution->financial_type_id
= $objects['contributionType']->id
;
308 $contribution->contribution_page_id
= $ids['contributionPage'];
309 $contribution->contribution_recur_id
= $ids['contributionRecur'];
310 $contribution->currency
= $objects['contribution']->currency
;
311 $contribution->payment_instrument_id
= $objects['contribution']->payment_instrument_id
;
312 $contribution->amount_level
= $objects['contribution']->amount_level
;
313 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
314 $objects['contribution'] = &$contribution;
316 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
317 $objects['contribution']->receive_date
= !empty($input['payment_date']) ?
date('YmdHis', strtotime($input['payment_date'])) : $now;
319 $this->single($input, $ids, $objects,
331 public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
332 $contribution = &$objects['contribution'];
334 // make sure the invoice is valid and matches what we have in the contribution record
335 if ((!$recur) ||
($recur && $first)) {
336 if ($contribution->invoice_id
!= $input['invoice']) {
337 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request");
338 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id
. " and input is " . $input['invoice'];
343 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
347 if ($contribution->total_amount
!= $input['amount']) {
348 CRM_Core_Error
::debug_log_message("Amount values dont match between database and IPN request");
349 echo "Failure: Amount values dont match between database and IPN request<p>";
354 $contribution->total_amount
= $input['amount'];
357 $transaction = new CRM_Core_Transaction();
359 $participant = &$objects['participant'];
360 $membership = &$objects['membership'];
362 $status = $input['paymentStatus'];
363 if ($status == 'Denied' ||
$status == 'Failed' ||
$status == 'Voided') {
364 return $this->failed($objects, $transaction);
366 elseif ($status == 'Pending') {
367 return $this->pending($objects, $transaction);
369 elseif ($status == 'Refunded' ||
$status == 'Reversed') {
370 return $this->cancelled($objects, $transaction);
372 elseif ($status != 'Completed') {
373 return $this->unhandled($objects, $transaction);
376 // check if contribution is already completed, if so we ignore this ipn
377 if ($contribution->contribution_status_id
== 1) {
378 $transaction->commit();
379 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
380 echo "Success: Contribution has already been handled<p>";
384 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
388 * This is the main function to call. It should be sufficient to instantiate the class
389 * (with the input parameters) & call this & all will be done
391 * @todo the references to POST throughout this class need to be removed
394 public function main() {
395 CRM_Core_Error
::debug_var('GET', $_GET, TRUE, TRUE);
396 CRM_Core_Error
::debug_var('POST', $_POST, TRUE, TRUE);
397 if ($this->_isPaymentExpress
) {
398 $this->handlePaymentExpress();
401 $objects = $ids = $input = array();
402 $this->_component
= $input['component'] = self
::getValue('m');
403 $input['invoice'] = self
::getValue('i', TRUE);
404 // get the contribution and contact ids from the GET params
405 $ids['contact'] = self
::getValue('c', TRUE);
406 $ids['contribution'] = self
::getValue('b', TRUE);
408 $this->getInput($input, $ids);
410 if ($this->_component
== 'event') {
411 $ids['event'] = self
::getValue('e', TRUE);
412 $ids['participant'] = self
::getValue('p', TRUE);
413 $ids['contributionRecur'] = self
::getValue('r', FALSE);
416 // get the optional ids
417 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
418 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
419 $ids['membership'] = self
::retrieve('membershipID', 'Integer', 'GET', FALSE);
420 $ids['contributionRecur'] = self
::getValue('r', FALSE);
421 $ids['contributionPage'] = self
::getValue('p', FALSE);
422 $ids['related_contact'] = self
::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
423 $ids['onbehalf_dupe_alert'] = self
::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
426 if (!$ids['membership'] && $ids['contributionRecur']) {
429 FROM civicrm_membership m
430 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
431 WHERE m.contribution_recur_id = %2
434 1 => array($ids['contribution'], 'Integer'),
435 2 => array($ids['contributionRecur'], 'Integer'),
437 if ($membershipId = CRM_Core_DAO
::singleValueQuery($sql, $sqlParams)) {
438 $ids['membership'] = $membershipId;
442 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
443 'PayPal', 'id', 'name'
446 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
450 self
::$_paymentProcessor = &$objects['paymentProcessor'];
451 //?? how on earth would we not have component be one of these?
452 // they are the only valid settings & this IPN file can't even be called without one of them
453 // grepping for this class doesn't find other paths to call this class
454 if ($this->_component
== 'contribute' ||
$this->_component
== 'event') {
455 if ($ids['contributionRecur']) {
456 // check if first contribution is completed, else complete first contribution
458 if ($objects['contribution']->contribution_status_id
== 1) {
461 return $this->recur($input, $ids, $objects, $first);
464 return $this->single($input, $ids, $objects, FALSE, FALSE);
468 return $this->single($input, $ids, $objects, FALSE, FALSE);
477 * @throws CRM_Core_Exception
479 public function getInput(&$input, &$ids) {
481 if (!$this->getBillingID($ids)) {
485 $input['txnType'] = self
::retrieve('txn_type', 'String', 'POST', FALSE);
486 $input['paymentStatus'] = self
::retrieve('payment_status', 'String', 'POST', FALSE);
488 $input['amount'] = self
::retrieve('mc_gross', 'Money', 'POST', FALSE);
489 $input['reasonCode'] = self
::retrieve('ReasonCode', 'String', 'POST', FALSE);
491 $billingID = $ids['billing'];
493 "first_name" => 'first_name',
494 "last_name" => 'last_name',
495 "street_address-{$billingID}" => 'address_street',
496 "city-{$billingID}" => 'address_city',
497 "state-{$billingID}" => 'address_state',
498 "postal_code-{$billingID}" => 'address_zip',
499 "country-{$billingID}" => 'address_country_code',
501 foreach ($lookup as $name => $paypalName) {
502 $value = self
::retrieve($paypalName, 'String', 'POST', FALSE);
503 $input[$name] = $value ?
$value : NULL;
506 $input['is_test'] = self
::retrieve('test_ipn', 'Integer', 'POST', FALSE);
507 $input['fee_amount'] = self
::retrieve('mc_fee', 'Money', 'POST', FALSE);
508 $input['net_amount'] = self
::retrieve('settle_amount', 'Money', 'POST', FALSE);
509 $input['trxn_id'] = self
::retrieve('txn_id', 'String', 'POST', FALSE);
510 $input['payment_date'] = self
::retrieve('payment_date', 'String', 'POST', FALSE);
514 * Handle payment express IPNs
515 * For one off IPNS no actual response is required
516 * Recurring is more difficult as we have limited confirmation material
517 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
519 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
520 * then the quasi security of the ids array might be required - although better to
521 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
522 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
523 * only contribute is handled
525 public function handlePaymentExpress() {
526 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
528 // also note that a lot of the complexity above could be removed if we used
529 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
530 // as membership id etc can be derived by the load objects fn
531 $objects = $ids = $input = array();
533 $input['txnType'] = $this->retrieve('txn_type', 'String');
534 if ($input['txnType'] != 'recurring_payment') {
535 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
537 $input['invoice'] = self
::getValue('i', FALSE);
538 $this->getInput($input, $ids);
539 if ($this->transactionExists($input['trxn_id'])) {
540 throw new CRM_Core_Exception('This transaction has already been processed');
543 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', array(
544 'return' => 'contact_id, id',
545 'invoice_id' => $input['invoice'],
547 $ids['contact'] = $contributionRecur['contact_id'];
548 $ids['contributionRecur'] = $contributionRecur['id'];
549 $result = civicrm_api3('contribution', 'getsingle', array('invoice_id' => $input['invoice']));
551 $ids['contribution'] = $result['id'];
552 //@todo hard - coding 'pending' for now
553 if ($result['contribution_status_id'] == 2) {
556 // arg api won't get this - fix it
557 $ids['contributionPage'] = CRM_Core_DAO
::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", array(
559 $ids['contribution'],
563 // only handle component at this stage - not terribly sure how a recurring event payment would arise
564 // & suspec main function may be a victom of copy & paste
565 // membership would be an easy add - but not relevant to my customer...
566 $this->_component
= $input['component'] = 'contribute';
567 $input['trxn_date'] = date('Y-m-d-H-i-s', strtotime(self
::retrieve('time_created', 'String')));
568 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
569 'PayPal', 'id', 'name'
572 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
573 throw new CRM_Core_Exception('Data did not validate');
575 return $this->recur($input, $ids, $objects, $isFirst);
579 * Function check if transaction already exists
580 * @param string $trxn_id
583 public function transactionExists($trxn_id) {
584 if (CRM_Core_DAO
::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
586 1 => array($trxn_id, 'String'),