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';
64 * constructor function
66 * @param array $inputData contents of HTTP REQUEST
68 * @throws CRM_Core_Exception
70 function __construct($inputData) {
71 $this->setInputParameters($inputData);
72 $this->setInvoiceData();
73 parent
::__construct();
77 * function exists to get the values from the rp_invoice_id string
79 * @param string $name e.g. i, values are stored in the string with letter codes
80 * @param boolean $abort fatal if not found?
82 * @throws CRM_Core_Exception
85 function getValue($name, $abort = TRUE) {
86 if ($abort && empty($this->_invoiceData
[$name])) {
87 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
90 return CRM_Utils_Array
::value($name, $this->_invoiceData
);
95 * Set $this->_invoiceData from the input array
97 function setInvoiceData() {
98 if(empty($this->_inputParameters
['rp_invoice_id'])) {
99 $this->_isPaymentExpress
= TRUE;
102 $rpInvoiceArray = explode('&', $this->_inputParameters
['rp_invoice_id']);
103 // for clarify let's also store without the single letter unreadable
104 //@todo after more refactoring we might ditch storing the one letter stuff
109 'b' => 'contribution_id',
110 'r' => 'contribution_recur_id',
111 'p' => 'participant_id',
114 foreach ($rpInvoiceArray as $rpInvoiceValue) {
115 $rpValueArray = explode('=', $rpInvoiceValue);
116 $this->_invoiceData
[$rpValueArray[0]] = $rpValueArray[1];
117 $this->_inputParameters
[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
118 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
119 // alphabet with more letters.
120 // the mode will always be resolved before the mystery p is reached
121 if($rpValueArray[1] == 'contribute') {
122 $mapping['p'] = 'contribution_page_id';
125 if(empty($this->_inputParameters
['component'])) {
126 $this->_isPaymentExpress
= TRUE;
131 * @param string $name of variable to return
132 * @param string $type data type
135 * @param string $location - deprecated
136 * @param boolean $abort abort if empty
138 * @throws CRM_Core_Exception
139 * @return Ambigous <mixed, NULL, value, unknown, array, number>
141 function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
142 $value = CRM_Utils_Type
::validate(
143 CRM_Utils_Array
::value($name, $this->_inputParameters
),
147 if ($abort && $value === NULL) {
148 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
154 * Process recurring contributions
155 * @param array $input
157 * @param array $objects
158 * @param boolean $first
159 * @return void|boolean
161 function recur(&$input, &$ids, &$objects, $first) {
162 if (!isset($input['txnType'])) {
163 CRM_Core_Error
::debug_log_message("Could not find txn_type in input request");
164 echo "Failure: Invalid parameters<p>";
168 if ($input['txnType'] == 'recurring_payment' &&
169 $input['paymentStatus'] != 'Completed'
171 CRM_Core_Error
::debug_log_message("Ignore all IPN payments that are not completed");
172 echo "Failure: Invalid parameters<p>";
176 $recur = &$objects['contributionRecur'];
178 // make sure the invoice ids match
179 // make sure the invoice is valid and matches what we have in
180 // the contribution record
181 if ($recur->invoice_id
!= $input['invoice']) {
182 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id
. " input is " . $input['invoice']);
183 echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id
. " input is " . $input['invoice'];
187 $now = date('YmdHis');
189 // fix dates that already exist
190 $dates = array('create', 'start', 'end', 'cancel', 'modified');
191 foreach ($dates as $date) {
192 $name = "{$date}_date";
194 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
198 $sendNotification = FALSE;
199 $subscriptionPaymentStatus = NULL;
200 //List of Transaction Type
202 recurring_payment_profile_created RP Profile Created
203 recurring_payment RP Sucessful Payment
204 recurring_payment_failed RP Failed Payment
205 recurring_payment_profile_cancel RP Profile Cancelled
206 recurring_payment_expired RP Profile Expired
207 recurring_payment_skipped RP Profile Skipped
208 recurring_payment_outstanding_payment RP Sucessful Outstanding Payment
209 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
210 recurring_payment_suspended RP Profile Suspended
211 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
215 //set transaction type
216 $txnType = $this->retrieve('txn_type', 'String');
217 //Changes for paypal pro recurring payment
218 $contributionStatuses = civicrm_api3('contribution', 'getoptions', array('field' => 'contribution_status_id'));
219 $contributionStatuses = $contributionStatuses['values'];
221 case 'recurring_payment_profile_created':
222 if(in_array($recur->contribution_status_id
, array(array_search('Pending',$contributionStatuses), array_search('In Progress',$contributionStatuses)))
223 && !empty($recur->processor_id
)) {
224 echo "already handled";
227 $recur->create_date
= $now;
228 $recur->contribution_status_id
= 2;
229 $recur->processor_id
= $this->retrieve('recurring_payment_id', 'String');
230 $recur->trxn_id
= $recur->processor_id
;
231 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
232 $sendNotification = TRUE;
235 case 'recurring_payment':
237 $recur->start_date
= $now;
240 $recur->modified_date
= $now;
243 //contribution installment is completed
244 if ($this->retrieve('profile_status', 'String') == 'Expired') {
245 if(!empty($recur->end_date
)) {
246 echo "already handled";
249 $recur->contribution_status_id
= 1;
250 $recur->end_date
= $now;
251 $sendNotification = TRUE;
252 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
255 // make sure the contribution status is not done
256 // since order of ipn's is unknown
257 if ($recur->contribution_status_id
!= 1) {
258 $recur->contribution_status_id
= 5;
265 if ($sendNotification) {
266 $autoRenewMembership = FALSE;
268 isset($ids['membership']) && $ids['membership']
270 $autoRenewMembership = TRUE;
272 //send recurring Notification email for user
273 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
275 $ids['contributionPage'],
281 if ($txnType != 'recurring_payment') {
286 //check if this contribution transaction is already processed
287 //if not create a contribution and then get it processed
288 $contribution = new CRM_Contribute_BAO_Contribution();
289 $contribution->trxn_id
= $input['trxn_id'];
290 if ($contribution->trxn_id
&& $contribution->find()) {
291 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
292 echo "Success: Contribution has already been handled<p>";
296 $contribution->contact_id
= $recur->contact_id
;
297 $contribution->financial_type_id
= $objects['contributionType']->id
;
298 $contribution->contribution_page_id
= $ids['contributionPage'];
299 $contribution->contribution_recur_id
= $ids['contributionRecur'];
300 $contribution->currency
= $objects['contribution']->currency
;
301 $contribution->payment_instrument_id
= $objects['contribution']->payment_instrument_id
;
302 $contribution->amount_level
= $objects['contribution']->amount_level
;
303 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
304 $objects['contribution'] = &$contribution;
306 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
307 $objects['contribution']->receive_date
= !empty($input['payment_date']) ?
date('YmdHis', strtotime($input['payment_date'])): $now;
309 $this->single($input, $ids, $objects,
321 function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
322 $contribution = &$objects['contribution'];
324 // make sure the invoice is valid and matches what we have in the contribution record
325 if ((!$recur) ||
($recur && $first)) {
326 if ($contribution->invoice_id
!= $input['invoice']) {
327 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request");
328 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id
. " and input is " . $input['invoice'];
333 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
337 if ($contribution->total_amount
!= $input['amount']) {
338 CRM_Core_Error
::debug_log_message("Amount values dont match between database and IPN request");
339 echo "Failure: Amount values dont match between database and IPN request<p>";
344 $contribution->total_amount
= $input['amount'];
347 $transaction = new CRM_Core_Transaction();
349 $participant = &$objects['participant'];
350 $membership = &$objects['membership'];
352 $status = $input['paymentStatus'];
353 if ($status == 'Denied' ||
$status == 'Failed' ||
$status == 'Voided') {
354 return $this->failed($objects, $transaction);
356 elseif ($status == 'Pending') {
357 return $this->pending($objects, $transaction);
359 elseif ($status == 'Refunded' ||
$status == 'Reversed') {
360 return $this->cancelled($objects, $transaction);
362 elseif ($status != 'Completed') {
363 return $this->unhandled($objects, $transaction);
366 // check if contribution is already completed, if so we ignore this ipn
367 if ($contribution->contribution_status_id
== 1) {
368 $transaction->commit();
369 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
370 echo "Success: Contribution has already been handled<p>";
374 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
378 * This is the main function to call. It should be sufficient to instantiate the class
379 * (with the input parameters) & call this & all will be done
381 * @todo the references to POST throughout this class need to be removed
382 * @return void|boolean|Ambigous <void, boolean>
385 CRM_Core_Error
::debug_var('GET', $_GET, TRUE, TRUE);
386 CRM_Core_Error
::debug_var('POST', $_POST, TRUE, TRUE);
387 if($this->_isPaymentExpress
) {
388 $this->handlePaymentExpress();
391 $objects = $ids = $input = array();
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, $ids);
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
423 $sqlParams = array(1 => array($ids['contribution'], 'Integer'),
424 2 => array($ids['contributionRecur'], 'Integer'),
426 if ($membershipId = CRM_Core_DAO
::singleValueQuery($sql, $sqlParams)) {
427 $ids['membership'] = $membershipId;
431 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
432 'PayPal', 'id', 'name'
435 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
439 self
::$_paymentProcessor = &$objects['paymentProcessor'];
440 //?? how on earth would we not have component be one of these?
441 // they are the only valid settings & this IPN file can't even be called without one of them
442 // grepping for this class doesn't find other paths to call this class
443 if ($this->_component
== 'contribute' ||
$this->_component
== 'event') {
444 if ($ids['contributionRecur']) {
445 // check if first contribution is completed, else complete first contribution
447 if ($objects['contribution']->contribution_status_id
== 1) {
450 return $this->recur($input, $ids, $objects, $first);
453 return $this->single($input, $ids, $objects, FALSE, FALSE);
457 return $this->single($input, $ids, $objects, FALSE, FALSE);
465 * @throws CRM_Core_Exception
467 function getInput(&$input, &$ids) {
469 if (!$this->getBillingID($ids)) {
473 $input['txnType'] = self
::retrieve('txn_type', 'String', 'POST', FALSE);
474 $input['paymentStatus'] = self
::retrieve('payment_status', 'String', 'POST', FALSE);
476 $input['amount'] = self
::retrieve('mc_gross', 'Money', 'POST', FALSE);
477 $input['reasonCode'] = self
::retrieve('ReasonCode', 'String', 'POST', FALSE);
479 $billingID = $ids['billing'];
481 "first_name" => 'first_name',
482 "last_name" => 'last_name',
483 "street_address-{$billingID}" => 'address_street',
484 "city-{$billingID}" => 'address_city',
485 "state-{$billingID}" => 'address_state',
486 "postal_code-{$billingID}" => 'address_zip',
487 "country-{$billingID}" => 'address_country_code',
489 foreach ($lookup as $name => $paypalName) {
490 $value = self
::retrieve($paypalName, 'String', 'POST', FALSE);
491 $input[$name] = $value ?
$value : NULL;
494 $input['is_test'] = self
::retrieve('test_ipn', 'Integer', 'POST', FALSE);
495 $input['fee_amount'] = self
::retrieve('mc_fee', 'Money', 'POST', FALSE);
496 $input['net_amount'] = self
::retrieve('settle_amount', 'Money', 'POST', FALSE);
497 $input['trxn_id'] = self
::retrieve('txn_id', 'String', 'POST', FALSE);
498 $input['payment_date'] = self
::retrieve('payment_date', 'String', 'POST', FALSE);
502 * 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 transaction id to ensure no
507 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
508 * then 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 for donations
511 * only contribute is handled
513 function handlePaymentExpress() {
514 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
516 // also note that a lot of the complexity above could be removed if we used
517 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
518 // as membership id etc can be derived by the load objects fn
519 $objects = $ids = $input = array();
521 $input['txnType'] = $this->retrieve('txn_type', 'String');
522 if($input['txnType'] != 'recurring_payment') {
523 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
525 $input['invoice'] = self
::getValue('i', FALSE);
526 $this->getInput($input, $ids);
527 if($this-> transactionExists($input['trxn_id'])) {
528 throw new CRM_Core_Exception('This transaction has already been processed');
531 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', array('return' => 'contact_id, id', 'invoice_id' => $input['invoice']));
532 $ids['contact'] = $contributionRecur['contact_id'];
533 $ids['contributionRecur'] = $contributionRecur['id'];
534 $result = civicrm_api3('contribution', 'getsingle', array('invoice_id' => $input['invoice'], ));
536 $ids['contribution'] = $result['id'];
537 //@todo hard - coding 'pending' for now
538 if($result['contribution_status_id'] == 2) {
541 // arg api won't get this - fix it
542 $ids['contributionPage'] = CRM_Core_DAO
::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", array(1 => array($ids['contribution'], 'Integer')));
543 // only handle component at this stage - not terribly sure how a recurring event payment would arise
544 // & suspec main function may be a victom of copy & paste
545 // membership would be an easy add - but not relevant to my customer...
546 $this->_component
= $input['component'] = 'contribute';
547 $input['trxn_date'] = date('Y-m-d-H-i-s', strtotime(self
::retrieve('time_created', 'String')));
548 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
549 'PayPal', 'id', 'name'
552 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
553 throw new CRM_Core_Exception('Data did not validate');
555 return $this->recur($input, $ids, $objects, $isFirst);
559 * Function check if transaction already exists
560 * @param string $trxn_id
562 function transactionExists($trxn_id) {
563 if(CRM_Core_DAO
::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
565 1 => array($trxn_id, 'String')