3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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
73 * @param string $name e.g. i, values are stored in the string with letter codes
74 * @param boolean $abort fatal if not found?
77 function getValue($name, $abort = TRUE) {
78 if ($abort && empty($this->_invoiceData
[$name])) {
79 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
82 return CRM_Utils_Array
::value($name, $this->_invoiceData
);
87 * Set $this->_invoiceData from the input array
89 function setInvoiceData() {
90 if(empty($this->_inputParameters
['rp_invoice_id'])) {
91 $this->_isPaymentExpress
= TRUE;
94 $rpInvoiceArray = explode('&', $this->_inputParameters
['rp_invoice_id']);
95 // for clarify let's also store without the single letter unreadable
96 //@todo after more refactoring we might ditch storing the one letter stuff
101 'b' => 'contribution_id',
102 'r' => 'contribution_recur_id',
103 'p' => 'participant_id',
106 foreach ($rpInvoiceArray as $rpInvoiceValue) {
107 $rpValueArray = explode('=', $rpInvoiceValue);
108 $this->_invoiceData
[$rpValueArray[0]] = $rpValueArray[1];
109 $this->_inputParameters
[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
110 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
111 // alphabet with more letters.
112 // the mode will always be resolved before the mystery p is reached
113 if($rpValueArray[1] == 'contribute') {
114 $mapping['p'] = 'contribution_page_id';
120 * @param string $name of variable to return
121 * @param string $type data type
124 * @param string $location - deprecated
125 * @param boolean $abort abort if empty
126 * @return Ambigous <mixed, NULL, value, unknown, array, number>
128 function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
129 $value = CRM_Utils_Type
::validate(
130 CRM_Utils_Array
::value($name, $this->_inputParameters
),
134 if ($abort && $value === NULL) {
135 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
141 * Process recurring contributions
142 * @param array $input
144 * @param array $objects
145 * @param boolean $first
146 * @return void|boolean
148 function recur(&$input, &$ids, &$objects, $first) {
149 if (!isset($input['txnType'])) {
150 CRM_Core_Error
::debug_log_message("Could not find txn_type in input request");
151 echo "Failure: Invalid parameters<p>";
155 if ($input['txnType'] == 'recurring_payment' &&
156 $input['paymentStatus'] != 'Completed'
158 CRM_Core_Error
::debug_log_message("Ignore all IPN payments that are not completed");
159 echo "Failure: Invalid parameters<p>";
163 $recur = &$objects['contributionRecur'];
165 // make sure the invoice ids match
166 // make sure the invoice is valid and matches what we have in
167 // the contribution record
168 if ($recur->invoice_id
!= $input['invoice']) {
169 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id
. " input is " . $input['invoice']);
170 echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id
. " input is " . $input['invoice'];
174 $now = date('YmdHis');
176 // fix dates that already exist
177 $dates = array('create', 'start', 'end', 'cancel', 'modified');
178 foreach ($dates as $date) {
179 $name = "{$date}_date";
181 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
185 $sendNotification = FALSE;
186 $subscriptionPaymentStatus = NULL;
187 //List of Transaction Type
189 recurring_payment_profile_created RP Profile Created
190 recurring_payment RP Sucessful Payment
191 recurring_payment_failed RP Failed Payment
192 recurring_payment_profile_cancel RP Profile Cancelled
193 recurring_payment_expired RP Profile Expired
194 recurring_payment_skipped RP Profile Skipped
195 recurring_payment_outstanding_payment RP Sucessful Outstanding Payment
196 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
197 recurring_payment_suspended RP Profile Suspended
198 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
202 //set transaction type
203 $txnType = $this->retrieve('txn_type', 'String');
204 //Changes for paypal pro recurring payment
205 $contributionStatuses = civicrm_api3('contribution', 'getoptions', array('field' => 'contribution_status_id'));
206 $contributionStatuses = $contributionStatuses['values'];
208 case 'recurring_payment_profile_created':
209 if(in_array($recur->contribution_status_id
, array(array_search('Pending',$contributionStatuses), array_search('In Progress',$contributionStatuses)))
210 && !empty($recur->processor_id
)) {
211 echo "already handled";
214 $recur->create_date
= $now;
215 $recur->contribution_status_id
= 2;
216 $recur->processor_id
= $this->retrieve('recurring_payment_id', 'String');
217 $recur->trxn_id
= $recur->processor_id
;
218 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
219 $sendNotification = TRUE;
222 case 'recurring_payment':
224 $recur->start_date
= $now;
227 $recur->modified_date
= $now;
230 //contribution installment is completed
231 if ($this->retrieve('profile_status', 'String') == 'Expired') {
232 if(!empty($recur->end_date
)) {
233 echo "already handled";
236 $recur->contribution_status_id
= 1;
237 $recur->end_date
= $now;
238 $sendNotification = TRUE;
239 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
242 // make sure the contribution status is not done
243 // since order of ipn's is unknown
244 if ($recur->contribution_status_id
!= 1) {
245 $recur->contribution_status_id
= 5;
252 if ($sendNotification) {
253 $autoRenewMembership = FALSE;
255 isset($ids['membership']) && $ids['membership']
257 $autoRenewMembership = TRUE;
259 //send recurring Notification email for user
260 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
262 $ids['contributionPage'],
268 if ($txnType != 'recurring_payment') {
273 //check if this contribution transaction is already processed
274 //if not create a contribution and then get it processed
275 $contribution = new CRM_Contribute_BAO_Contribution();
276 $contribution->trxn_id
= $input['trxn_id'];
277 if ($contribution->trxn_id
&& $contribution->find()) {
278 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
279 echo "Success: Contribution has already been handled<p>";
283 $contribution->contact_id
= $recur->contact_id
;
284 $contribution->financial_type_id
= $objects['contributionType']->id
;
285 $contribution->contribution_page_id
= $ids['contributionPage'];
286 $contribution->contribution_recur_id
= $ids['contributionRecur'];
287 $contribution->currency
= $objects['contribution']->currency
;
288 $contribution->payment_instrument_id
= $objects['contribution']->payment_instrument_id
;
289 $contribution->amount_level
= $objects['contribution']->amount_level
;
290 $contribution->honor_contact_id
= $objects['contribution']->honor_contact_id
;
291 $contribution->honor_type_id
= $objects['contribution']->honor_type_id
;
292 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
293 $objects['contribution'] = &$contribution;
295 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
296 $objects['contribution']->receive_date
= !empty($input['payment_date']) ?
date('YmdHis', strtotime($input['payment_date'])): $now;
298 $this->single($input, $ids, $objects,
303 function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
304 $contribution = &$objects['contribution'];
306 // make sure the invoice is valid and matches what we have in the contribution record
307 if ((!$recur) ||
($recur && $first)) {
308 if ($contribution->invoice_id
!= $input['invoice']) {
309 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request");
310 echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id
. " and input is " . $input['invoice'];
315 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
319 if ($contribution->total_amount
!= $input['amount']) {
320 CRM_Core_Error
::debug_log_message("Amount values dont match between database and IPN request");
321 echo "Failure: Amount values dont match between database and IPN request<p>";
326 $contribution->total_amount
= $input['amount'];
329 $transaction = new CRM_Core_Transaction();
331 $participant = &$objects['participant'];
332 $membership = &$objects['membership'];
334 $status = $input['paymentStatus'];
335 if ($status == 'Denied' ||
$status == 'Failed' ||
$status == 'Voided') {
336 return $this->failed($objects, $transaction);
338 elseif ($status == 'Pending') {
339 return $this->pending($objects, $transaction);
341 elseif ($status == 'Refunded' ||
$status == 'Reversed') {
342 return $this->cancelled($objects, $transaction);
344 elseif ($status != 'Completed') {
345 return $this->unhandled($objects, $transaction);
348 // check if contribution is already completed, if so we ignore this ipn
349 if ($contribution->contribution_status_id
== 1) {
350 $transaction->commit();
351 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
352 echo "Success: Contribution has already been handled<p>";
356 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
360 * This is the main function to call. It should be sufficient to instantiate the class
361 * (with the input parameters) & call this & all will be done
363 * @todo the references to POST throughout this class need to be removed
364 * @return void|boolean|Ambigous <void, boolean>
367 CRM_Core_Error
::debug_var('GET', $_GET, TRUE, TRUE);
368 CRM_Core_Error
::debug_var('POST', $_POST, TRUE, TRUE);
369 if($this->_isPaymentExpress
) {
370 $this->handlePaymentExpress();
373 $objects = $ids = $input = array();
374 $this->_component
= $input['component'] = self
::getValue('m');
376 // get the contribution and contact ids from the GET params
377 $ids['contact'] = self
::getValue('c', TRUE);
378 $ids['contribution'] = self
::getValue('b', TRUE);
380 $this->getInput($input, $ids);
382 if ($this->_component
== 'event') {
383 $ids['event'] = self
::getValue('e', TRUE);
384 $ids['participant'] = self
::getValue('p', TRUE);
385 $ids['contributionRecur'] = self
::getValue('r', FALSE);
388 // get the optional ids
389 //@ how can this not be broken retrieving from GET as we are dealing with a POST request?
390 // copy & paste? Note the retrieve function now uses data from _REQUEST so this will be included
391 $ids['membership'] = self
::retrieve('membershipID', 'Integer', 'GET', FALSE);
392 $ids['contributionRecur'] = self
::getValue('r', FALSE);
393 $ids['contributionPage'] = self
::getValue('p', FALSE);
394 $ids['related_contact'] = self
::retrieve('relatedContactID', 'Integer', 'GET', FALSE);
395 $ids['onbehalf_dupe_alert'] = self
::retrieve('onBehalfDupeAlert', 'Integer', 'GET', FALSE);
398 if (!$ids['membership'] && $ids['contributionRecur']) {
401 FROM civicrm_membership m
402 INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = %1
403 WHERE m.contribution_recur_id = %2
405 $sqlParams = array(1 => array($ids['contribution'], 'Integer'),
406 2 => array($ids['contributionRecur'], 'Integer'),
408 if ($membershipId = CRM_Core_DAO
::singleValueQuery($sql, $sqlParams)) {
409 $ids['membership'] = $membershipId;
413 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
414 'PayPal', 'id', 'name'
417 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
421 self
::$_paymentProcessor = &$objects['paymentProcessor'];
422 //?? how on earth would we not have component be one of these?
423 // they are the only valid settings & this IPN file can't even be called without one of them
424 // grepping for this class doesn't find other paths to call this class
425 if ($this->_component
== 'contribute' ||
$this->_component
== 'event') {
426 if ($ids['contributionRecur']) {
427 // check if first contribution is completed, else complete first contribution
429 if ($objects['contribution']->contribution_status_id
== 1) {
432 return $this->recur($input, $ids, $objects, $first);
435 return $this->single($input, $ids, $objects, FALSE, FALSE);
439 return $this->single($input, $ids, $objects, FALSE, FALSE);
443 function getInput(&$input, &$ids) {
445 if (!$this->getBillingID($ids)) {
449 $input['txnType'] = self
::retrieve('txn_type', 'String', 'POST', FALSE);
450 $input['paymentStatus'] = self
::retrieve('payment_status', 'String', 'POST', FALSE);
451 $input['invoice'] = self
::getValue('i', TRUE);
453 $input['amount'] = self
::retrieve('mc_gross', 'Money', 'POST', FALSE);
454 $input['reasonCode'] = self
::retrieve('ReasonCode', 'String', 'POST', FALSE);
456 $billingID = $ids['billing'];
458 "first_name" => 'first_name',
459 "last_name" => 'last_name',
460 "street_address-{$billingID}" => 'address_street',
461 "city-{$billingID}" => 'address_city',
462 "state-{$billingID}" => 'address_state',
463 "postal_code-{$billingID}" => 'address_zip',
464 "country-{$billingID}" => 'address_country_code',
466 foreach ($lookup as $name => $paypalName) {
467 $value = self
::retrieve($paypalName, 'String', 'POST', FALSE);
468 $input[$name] = $value ?
$value : NULL;
471 $input['is_test'] = self
::retrieve('test_ipn', 'Integer', 'POST', FALSE);
472 $input['fee_amount'] = self
::retrieve('mc_fee', 'Money', 'POST', FALSE);
473 $input['net_amount'] = self
::retrieve('settle_amount', 'Money', 'POST', FALSE);
474 $input['trxn_id'] = self
::retrieve('txn_id', 'String', 'POST', FALSE);
475 $input['payment_date'] = self
::retrieve('payment_date', 'String', 'POST', FALSE);
479 * Handle payment express IPNs
480 * For one off IPNS no actual response is required
481 * Recurring is more difficult as we have limited confirmation material
483 function handlePaymentExpress() {
484 throw new CRM_Core_Exception('Payment Express IPNS not currently handled');