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
215 case 'recurring_payment_profile_created':
216 $recur->create_date
= $now;
217 $recur->contribution_status_id
= 2;
218 $recur->processor_id
= $this->retrieve('recurring_payment_id', 'String');
219 $recur->trxn_id
= $recur->processor_id
;
220 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
221 $sendNotification = TRUE;
224 case 'recurring_payment':
226 $recur->start_date
= $now;
229 $recur->modified_date
= $now;
232 //contribution installment is completed
233 if ($this->retrieve('profile_status', 'String') == 'Expired') {
234 $recur->contribution_status_id
= 1;
235 $recur->end_date
= $now;
236 $sendNotification = TRUE;
237 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
240 // make sure the contribution status is not done
241 // since order of ipn's is unknown
242 if ($recur->contribution_status_id
!= 1) {
243 $recur->contribution_status_id
= 5;
250 if ($sendNotification) {
251 $autoRenewMembership = FALSE;
253 isset($ids['membership']) && $ids['membership']
255 $autoRenewMembership = TRUE;
257 //send recurring Notification email for user
258 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
260 $ids['contributionPage'],
266 if ($txnType != 'recurring_payment') {
271 //check if this contribution transaction is already processed
272 //if not create a contribution and then get it processed
273 $contribution = new CRM_Contribute_BAO_Contribution();
274 $contribution->trxn_id
= $input['trxn_id'];
275 if ($contribution->trxn_id
&& $contribution->find()) {
276 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
277 echo "Success: Contribution has already been handled<p>";
281 $contribution->contact_id
= $recur->contact_id
;
282 $contribution->financial_type_id
= $objects['contributionType']->id
;
283 $contribution->contribution_page_id
= $ids['contributionPage'];
284 $contribution->contribution_recur_id
= $ids['contributionRecur'];
285 $contribution->currency
= $objects['contribution']->currency
;
286 $contribution->payment_instrument_id
= $objects['contribution']->payment_instrument_id
;
287 $contribution->amount_level
= $objects['contribution']->amount_level
;
288 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
289 $objects['contribution'] = &$contribution;
291 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
292 $objects['contribution']->receive_date
= !empty($input['payment_date']) ?
date('YmdHis', strtotime($input['payment_date'])): $now;
294 $this->single($input, $ids, $objects,
306 function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
307 $contribution = &$objects['contribution'];
309 // make sure the invoice is valid and matches what we have in the contribution record
310 if ((!$recur) ||
($recur && $first)) {
311 if ($contribution->invoice_id
!= $input['invoice']) {
312 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request");
313 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id
. " and input is " . $input['invoice'];
318 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
322 if ($contribution->total_amount
!= $input['amount']) {
323 CRM_Core_Error
::debug_log_message("Amount values dont match between database and IPN request");
324 echo "Failure: Amount values dont match between database and IPN request<p>";
329 $contribution->total_amount
= $input['amount'];
332 $transaction = new CRM_Core_Transaction();
334 $participant = &$objects['participant'];
335 $membership = &$objects['membership'];
337 $status = $input['paymentStatus'];
338 if ($status == 'Denied' ||
$status == 'Failed' ||
$status == 'Voided') {
339 return $this->failed($objects, $transaction);
341 elseif ($status == 'Pending') {
342 return $this->pending($objects, $transaction);
344 elseif ($status == 'Refunded' ||
$status == 'Reversed') {
345 return $this->cancelled($objects, $transaction);
347 elseif ($status != 'Completed') {
348 return $this->unhandled($objects, $transaction);
351 // check if contribution is already completed, if so we ignore this ipn
352 if ($contribution->contribution_status_id
== 1) {
353 $transaction->commit();
354 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
355 echo "Success: Contribution has already been handled<p>";
359 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
363 * This is the main function to call. It should be sufficient to instantiate the class
364 * (with the input parameters) & call this & all will be done
366 * @todo the references to POST throughout this class need to be removed
367 * @return void|boolean|Ambigous <void, boolean>
370 CRM_Core_Error
::debug_var('GET', $_GET, TRUE, TRUE);
371 CRM_Core_Error
::debug_var('POST', $_POST, TRUE, TRUE);
372 if($this->_isPaymentExpress
) {
373 $this->handlePaymentExpress();
376 $objects = $ids = $input = array();
377 $this->_component
= $input['component'] = self
::getValue('m');
378 $input['invoice'] = self
::getValue('i', TRUE);
379 // get the contribution and contact ids from the GET params
380 $ids['contact'] = self
::getValue('c', TRUE);
381 $ids['contribution'] = self
::getValue('b', TRUE);
383 $this->getInput($input, $ids);
385 if ($this->_component
== 'event') {
386 $ids['event'] = self
::getValue('e', TRUE);
387 $ids['participant'] = self
::getValue('p', TRUE);
388 $ids['contributionRecur'] = self
::getValue('r', FALSE);
391 // get the optional ids
392 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
393 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
394 $ids['membership'] = self
::retrieve('membershipID', 'Integer', 'GET', FALSE);
395 $ids['contributionRecur'] = self
::getValue('r', FALSE);
396 $ids['contributionPage'] = self
::getValue('p', FALSE);
397 $ids['related_contact'] = self
::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
398 $ids['onbehalf_dupe_alert'] = self
::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
401 if (!$ids['membership'] && $ids['contributionRecur']) {
404 FROM civicrm_membership m
405 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
406 WHERE m.contribution_recur_id = %2
408 $sqlParams = array(1 => array($ids['contribution'], 'Integer'),
409 2 => array($ids['contributionRecur'], 'Integer'),
411 if ($membershipId = CRM_Core_DAO
::singleValueQuery($sql, $sqlParams)) {
412 $ids['membership'] = $membershipId;
416 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
417 'PayPal', 'id', 'name'
420 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
424 self
::$_paymentProcessor = &$objects['paymentProcessor'];
425 //?? how on earth would we not have component be one of these?
426 // they are the only valid settings & this IPN file can't even be called without one of them
427 // grepping for this class doesn't find other paths to call this class
428 if ($this->_component
== 'contribute' ||
$this->_component
== 'event') {
429 if ($ids['contributionRecur']) {
430 // check if first contribution is completed, else complete first contribution
432 if ($objects['contribution']->contribution_status_id
== 1) {
435 return $this->recur($input, $ids, $objects, $first);
438 return $this->single($input, $ids, $objects, FALSE, FALSE);
442 return $this->single($input, $ids, $objects, FALSE, FALSE);
450 * @throws CRM_Core_Exception
452 function getInput(&$input, &$ids) {
454 if (!$this->getBillingID($ids)) {
458 $input['txnType'] = self
::retrieve('txn_type', 'String', 'POST', FALSE);
459 $input['paymentStatus'] = self
::retrieve('payment_status', 'String', 'POST', FALSE);
461 $input['amount'] = self
::retrieve('mc_gross', 'Money', 'POST', FALSE);
462 $input['reasonCode'] = self
::retrieve('ReasonCode', 'String', 'POST', FALSE);
464 $billingID = $ids['billing'];
466 "first_name" => 'first_name',
467 "last_name" => 'last_name',
468 "street_address-{$billingID}" => 'address_street',
469 "city-{$billingID}" => 'address_city',
470 "state-{$billingID}" => 'address_state',
471 "postal_code-{$billingID}" => 'address_zip',
472 "country-{$billingID}" => 'address_country_code',
474 foreach ($lookup as $name => $paypalName) {
475 $value = self
::retrieve($paypalName, 'String', 'POST', FALSE);
476 $input[$name] = $value ?
$value : NULL;
479 $input['is_test'] = self
::retrieve('test_ipn', 'Integer', 'POST', FALSE);
480 $input['fee_amount'] = self
::retrieve('mc_fee', 'Money', 'POST', FALSE);
481 $input['net_amount'] = self
::retrieve('settle_amount', 'Money', 'POST', FALSE);
482 $input['trxn_id'] = self
::retrieve('txn_id', 'String', 'POST', FALSE);
483 $input['payment_date'] = self
::retrieve('payment_date', 'String', 'POST', FALSE);
487 * Handle payment express IPNs
488 * For one off IPNS no actual response is required
489 * Recurring is more difficult as we have limited confirmation material
490 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
492 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
493 * then the quasi security of the ids array might be required - although better to
494 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
495 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
496 * only contribute is handled
498 function handlePaymentExpress() {
499 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
501 // also note that a lot of the complexity above could be removed if we used
502 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
503 // as membership id etc can be derived by the load objects fn
504 $objects = $ids = $input = array();
506 $input['txnType'] = $this->retrieve('txn_type', 'String');
507 if($input['txnType'] != 'recurring_payment') {
508 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
510 $input['invoice'] = self
::getValue('i', FALSE);
511 $this->getInput($input, $ids);
512 if($this-> transactionExists($input['trxn_id'])) {
513 throw new CRM_Core_Exception('This transaction has already been processed');
516 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', array('return' => 'contact_id, id', 'invoice_id' => $input['invoice']));
517 $ids['contact'] = $contributionRecur['contact_id'];
518 $ids['contributionRecur'] = $contributionRecur['id'];
519 $result = civicrm_api3('contribution', 'getsingle', array('invoice_id' => $input['invoice'], ));
521 $ids['contribution'] = $result['id'];
522 //@todo hard - coding 'pending' for now
523 if($result['contribution_status_id'] == 2) {
526 // arg api won't get this - fix it
527 $ids['contributionPage'] = CRM_Core_DAO
::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", array(1 => array($ids['contribution'], 'Integer')));
528 // only handle component at this stage - not terribly sure how a recurring event payment would arise
529 // & suspec main function may be a victom of copy & paste
530 // membership would be an easy add - but not relevant to my customer...
531 $this->_component
= $input['component'] = 'contribute';
532 $input['trxn_date'] = date('Y-m-d-H-i-s', strtotime(self
::retrieve('time_created', 'String')));
533 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
534 'PayPal', 'id', 'name'
537 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
538 throw new CRM_Core_Exception('Data did not validate');
540 return $this->recur($input, $ids, $objects, $isFirst);
544 * Function check if transaction already exists
545 * @param string $trxn_id
547 function transactionExists($trxn_id) {
548 if(CRM_Core_DAO
::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
550 1 => array($trxn_id, 'String')