3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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';
63 * constructor function
65 function __construct($inputData) {
66 $this->setInputParameters($inputData);
67 $this->setInvoiceData();
68 parent
::__construct();
72 * function exists to get the values from the rp_invoice_id string
74 * @param string $name e.g. i, values are stored in the string with letter codes
75 * @param boolean $abort fatal if not found?
77 * @throws CRM_Core_Exception
80 function getValue($name, $abort = TRUE) {
81 if ($abort && empty($this->_invoiceData
[$name])) {
82 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
85 return CRM_Utils_Array
::value($name, $this->_invoiceData
);
90 * Set $this->_invoiceData from the input array
92 function setInvoiceData() {
93 if(empty($this->_inputParameters
['rp_invoice_id'])) {
94 $this->_isPaymentExpress
= TRUE;
97 $rpInvoiceArray = explode('&', $this->_inputParameters
['rp_invoice_id']);
98 // for clarify let's also store without the single letter unreadable
99 //@todo after more refactoring we might ditch storing the one letter stuff
104 'b' => 'contribution_id',
105 'r' => 'contribution_recur_id',
106 'p' => 'participant_id',
109 foreach ($rpInvoiceArray as $rpInvoiceValue) {
110 $rpValueArray = explode('=', $rpInvoiceValue);
111 $this->_invoiceData
[$rpValueArray[0]] = $rpValueArray[1];
112 $this->_inputParameters
[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
113 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
114 // alphabet with more letters.
115 // the mode will always be resolved before the mystery p is reached
116 if($rpValueArray[1] == 'contribute') {
117 $mapping['p'] = 'contribution_page_id';
120 if(empty($this->_inputParameters
['component'])) {
121 $this->_isPaymentExpress
= TRUE;
126 * @param string $name of variable to return
127 * @param string $type data type
130 * @param string $location - deprecated
131 * @param boolean $abort abort if empty
133 * @throws CRM_Core_Exception
134 * @return Ambigous <mixed, NULL, value, unknown, array, number>
136 function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
137 $value = CRM_Utils_Type
::validate(
138 CRM_Utils_Array
::value($name, $this->_inputParameters
),
142 if ($abort && $value === NULL) {
143 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
149 * Process recurring contributions
150 * @param array $input
152 * @param array $objects
153 * @param boolean $first
154 * @return void|boolean
156 function recur(&$input, &$ids, &$objects, $first) {
157 if (!isset($input['txnType'])) {
158 CRM_Core_Error
::debug_log_message("Could not find txn_type in input request");
159 echo "Failure: Invalid parameters<p>";
163 if ($input['txnType'] == 'recurring_payment' &&
164 $input['paymentStatus'] != 'Completed'
166 CRM_Core_Error
::debug_log_message("Ignore all IPN payments that are not completed");
167 echo "Failure: Invalid parameters<p>";
171 $recur = &$objects['contributionRecur'];
173 // make sure the invoice ids match
174 // make sure the invoice is valid and matches what we have in
175 // the contribution record
176 if ($recur->invoice_id
!= $input['invoice']) {
177 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id
. " input is " . $input['invoice']);
178 echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id
. " input is " . $input['invoice'];
182 $now = date('YmdHis');
184 // fix dates that already exist
185 $dates = array('create', 'start', 'end', 'cancel', 'modified');
186 foreach ($dates as $date) {
187 $name = "{$date}_date";
189 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
193 $sendNotification = FALSE;
194 $subscriptionPaymentStatus = NULL;
195 //List of Transaction Type
197 recurring_payment_profile_created RP Profile Created
198 recurring_payment RP Sucessful Payment
199 recurring_payment_failed RP Failed Payment
200 recurring_payment_profile_cancel RP Profile Cancelled
201 recurring_payment_expired RP Profile Expired
202 recurring_payment_skipped RP Profile Skipped
203 recurring_payment_outstanding_payment RP Sucessful Outstanding Payment
204 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
205 recurring_payment_suspended RP Profile Suspended
206 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
210 //set transaction type
211 $txnType = $this->retrieve('txn_type', 'String');
212 //Changes for paypal pro recurring payment
213 $contributionStatuses = civicrm_api3('contribution', 'getoptions', array('field' => 'contribution_status_id'));
214 $contributionStatuses = $contributionStatuses['values'];
216 case 'recurring_payment_profile_created':
217 if(in_array($recur->contribution_status_id
, array(array_search('Pending',$contributionStatuses), array_search('In Progress',$contributionStatuses)))
218 && !empty($recur->processor_id
)) {
219 echo "already handled";
222 $recur->create_date
= $now;
223 $recur->contribution_status_id
= 2;
224 $recur->processor_id
= $this->retrieve('recurring_payment_id', 'String');
225 $recur->trxn_id
= $recur->processor_id
;
226 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
227 $sendNotification = TRUE;
230 case 'recurring_payment':
232 $recur->start_date
= $now;
235 $recur->modified_date
= $now;
238 //contribution installment is completed
239 if ($this->retrieve('profile_status', 'String') == 'Expired') {
240 if(!empty($recur->end_date
)) {
241 echo "already handled";
244 $recur->contribution_status_id
= 1;
245 $recur->end_date
= $now;
246 $sendNotification = TRUE;
247 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
250 // make sure the contribution status is not done
251 // since order of ipn's is unknown
252 if ($recur->contribution_status_id
!= 1) {
253 $recur->contribution_status_id
= 5;
260 if ($sendNotification) {
261 $autoRenewMembership = FALSE;
263 isset($ids['membership']) && $ids['membership']
265 $autoRenewMembership = TRUE;
267 //send recurring Notification email for user
268 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
270 $ids['contributionPage'],
276 if ($txnType != 'recurring_payment') {
281 //check if this contribution transaction is already processed
282 //if not create a contribution and then get it processed
283 $contribution = new CRM_Contribute_BAO_Contribution();
284 $contribution->trxn_id
= $input['trxn_id'];
285 if ($contribution->trxn_id
&& $contribution->find()) {
286 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
287 echo "Success: Contribution has already been handled<p>";
291 $contribution->contact_id
= $recur->contact_id
;
292 $contribution->financial_type_id
= $objects['contributionType']->id
;
293 $contribution->contribution_page_id
= $ids['contributionPage'];
294 $contribution->contribution_recur_id
= $ids['contributionRecur'];
295 $contribution->currency
= $objects['contribution']->currency
;
296 $contribution->payment_instrument_id
= $objects['contribution']->payment_instrument_id
;
297 $contribution->amount_level
= $objects['contribution']->amount_level
;
298 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
299 $objects['contribution'] = &$contribution;
301 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
302 $objects['contribution']->receive_date
= !empty($input['payment_date']) ?
date('YmdHis', strtotime($input['payment_date'])): $now;
304 $this->single($input, $ids, $objects,
316 function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
317 $contribution = &$objects['contribution'];
319 // make sure the invoice is valid and matches what we have in the contribution record
320 if ((!$recur) ||
($recur && $first)) {
321 if ($contribution->invoice_id
!= $input['invoice']) {
322 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request");
323 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id
. " and input is " . $input['invoice'];
328 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
332 if ($contribution->total_amount
!= $input['amount']) {
333 CRM_Core_Error
::debug_log_message("Amount values dont match between database and IPN request");
334 echo "Failure: Amount values dont match between database and IPN request<p>";
339 $contribution->total_amount
= $input['amount'];
342 $transaction = new CRM_Core_Transaction();
344 $participant = &$objects['participant'];
345 $membership = &$objects['membership'];
347 $status = $input['paymentStatus'];
348 if ($status == 'Denied' ||
$status == 'Failed' ||
$status == 'Voided') {
349 return $this->failed($objects, $transaction);
351 elseif ($status == 'Pending') {
352 return $this->pending($objects, $transaction);
354 elseif ($status == 'Refunded' ||
$status == 'Reversed') {
355 return $this->cancelled($objects, $transaction);
357 elseif ($status != 'Completed') {
358 return $this->unhandled($objects, $transaction);
361 // check if contribution is already completed, if so we ignore this ipn
362 if ($contribution->contribution_status_id
== 1) {
363 $transaction->commit();
364 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
365 echo "Success: Contribution has already been handled<p>";
369 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
373 * This is the main function to call. It should be sufficient to instantiate the class
374 * (with the input parameters) & call this & all will be done
376 * @todo the references to POST throughout this class need to be removed
377 * @return void|boolean|Ambigous <void, boolean>
380 CRM_Core_Error
::debug_var('GET', $_GET, TRUE, TRUE);
381 CRM_Core_Error
::debug_var('POST', $_POST, TRUE, TRUE);
382 if($this->_isPaymentExpress
) {
383 $this->handlePaymentExpress();
386 $objects = $ids = $input = array();
387 $this->_component
= $input['component'] = self
::getValue('m');
388 $input['invoice'] = self
::getValue('i', TRUE);
389 // get the contribution and contact ids from the GET params
390 $ids['contact'] = self
::getValue('c', TRUE);
391 $ids['contribution'] = self
::getValue('b', TRUE);
393 $this->getInput($input, $ids);
395 if ($this->_component
== 'event') {
396 $ids['event'] = self
::getValue('e', TRUE);
397 $ids['participant'] = self
::getValue('p', TRUE);
398 $ids['contributionRecur'] = self
::getValue('r', FALSE);
401 // get the optional ids
402 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
403 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
404 $ids['membership'] = self
::retrieve('membershipID', 'Integer', 'GET', FALSE);
405 $ids['contributionRecur'] = self
::getValue('r', FALSE);
406 $ids['contributionPage'] = self
::getValue('p', FALSE);
407 $ids['related_contact'] = self
::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
408 $ids['onbehalf_dupe_alert'] = self
::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
411 if (!$ids['membership'] && $ids['contributionRecur']) {
414 FROM civicrm_membership m
415 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
416 WHERE m.contribution_recur_id = %2
418 $sqlParams = array(1 => array($ids['contribution'], 'Integer'),
419 2 => array($ids['contributionRecur'], 'Integer'),
421 if ($membershipId = CRM_Core_DAO
::singleValueQuery($sql, $sqlParams)) {
422 $ids['membership'] = $membershipId;
426 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
427 'PayPal', 'id', 'name'
430 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
434 self
::$_paymentProcessor = &$objects['paymentProcessor'];
435 //?? how on earth would we not have component be one of these?
436 // they are the only valid settings & this IPN file can't even be called without one of them
437 // grepping for this class doesn't find other paths to call this class
438 if ($this->_component
== 'contribute' ||
$this->_component
== 'event') {
439 if ($ids['contributionRecur']) {
440 // check if first contribution is completed, else complete first contribution
442 if ($objects['contribution']->contribution_status_id
== 1) {
445 return $this->recur($input, $ids, $objects, $first);
448 return $this->single($input, $ids, $objects, FALSE, FALSE);
452 return $this->single($input, $ids, $objects, FALSE, FALSE);
460 * @throws CRM_Core_Exception
462 function getInput(&$input, &$ids) {
464 if (!$this->getBillingID($ids)) {
468 $input['txnType'] = self
::retrieve('txn_type', 'String', 'POST', FALSE);
469 $input['paymentStatus'] = self
::retrieve('payment_status', 'String', 'POST', FALSE);
471 $input['amount'] = self
::retrieve('mc_gross', 'Money', 'POST', FALSE);
472 $input['reasonCode'] = self
::retrieve('ReasonCode', 'String', 'POST', FALSE);
474 $billingID = $ids['billing'];
476 "first_name" => 'first_name',
477 "last_name" => 'last_name',
478 "street_address-{$billingID}" => 'address_street',
479 "city-{$billingID}" => 'address_city',
480 "state-{$billingID}" => 'address_state',
481 "postal_code-{$billingID}" => 'address_zip',
482 "country-{$billingID}" => 'address_country_code',
484 foreach ($lookup as $name => $paypalName) {
485 $value = self
::retrieve($paypalName, 'String', 'POST', FALSE);
486 $input[$name] = $value ?
$value : NULL;
489 $input['is_test'] = self
::retrieve('test_ipn', 'Integer', 'POST', FALSE);
490 $input['fee_amount'] = self
::retrieve('mc_fee', 'Money', 'POST', FALSE);
491 $input['net_amount'] = self
::retrieve('settle_amount', 'Money', 'POST', FALSE);
492 $input['trxn_id'] = self
::retrieve('txn_id', 'String', 'POST', FALSE);
493 $input['payment_date'] = self
::retrieve('payment_date', 'String', 'POST', FALSE);
497 * Handle payment express IPNs
498 * For one off IPNS no actual response is required
499 * Recurring is more difficult as we have limited confirmation material
500 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
502 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
503 * then the quasi security of the ids array might be required - although better to
504 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
505 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
506 * only contribute is handled
508 function handlePaymentExpress() {
509 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
511 // also note that a lot of the complexity above could be removed if we used
512 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
513 // as membership id etc can be derived by the load objects fn
514 $objects = $ids = $input = array();
516 $input['txnType'] = $this->retrieve('txn_type', 'String');
517 if($input['txnType'] != 'recurring_payment') {
518 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
520 $input['invoice'] = self
::getValue('i', FALSE);
521 $this->getInput($input, $ids);
522 if($this-> transactionExists($input['trxn_id'])) {
523 throw new CRM_Core_Exception('This transaction has already been processed');
526 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', array('return' => 'contact_id, id', 'invoice_id' => $input['invoice']));
527 $ids['contact'] = $contributionRecur['contact_id'];
528 $ids['contributionRecur'] = $contributionRecur['id'];
529 $result = civicrm_api3('contribution', 'getsingle', array('invoice_id' => $input['invoice'], ));
531 $ids['contribution'] = $result['id'];
532 //@todo hard - coding 'pending' for now
533 if($result['contribution_status_id'] == 2) {
536 // arg api won't get this - fix it
537 $ids['contributionPage'] = CRM_Core_DAO
::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", array(1 => array($ids['contribution'], 'Integer')));
538 // only handle component at this stage - not terribly sure how a recurring event payment would arise
539 // & suspec main function may be a victom of copy & paste
540 // membership would be an easy add - but not relevant to my customer...
541 $this->_component
= $input['component'] = 'contribute';
542 $input['trxn_date'] = date('Y-m-d-H-i-s', strtotime(self
::retrieve('time_created', 'String')));
543 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
544 'PayPal', 'id', 'name'
547 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
548 throw new CRM_Core_Exception('Data did not validate');
550 return $this->recur($input, $ids, $objects, $isFirst);
554 * Function check if transaction already exists
555 * @param string $trxn_id
557 function transactionExists($trxn_id) {
558 if(CRM_Core_DAO
::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
560 1 => array($trxn_id, 'String')