CRM-19372 allow payment processors to define an array of accepted credit card types
[civicrm-core.git] / CRM / Core / Payment / PayPalProIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2016
32 */
33 class CRM_Core_Payment_PayPalProIPN extends CRM_Core_Payment_BaseIPN {
34
35 static $_paymentProcessor = NULL;
36
37 /**
38 * Input parameters from payment processor. Store these so that
39 * the code does not need to keep retrieving from the http request
40 * @var array
41 */
42 protected $_inputParameters = array();
43
44 /**
45 * Store for the variables from the invoice string.
46 * @var array
47 */
48 protected $_invoiceData = array();
49
50 /**
51 * Is this a payment express transaction.
52 */
53 protected $_isPaymentExpress = FALSE;
54
55 /**
56 * Are we dealing with an event an 'anything else' (contribute)
57 * @var string component
58 */
59 protected $_component = 'contribute';
60
61 /**
62 * Constructor function.
63 *
64 * @param array $inputData
65 * Contents of HTTP REQUEST.
66 *
67 * @throws CRM_Core_Exception
68 */
69 public function __construct($inputData) {
70 $this->setInputParameters($inputData);
71 $this->setInvoiceData();
72 parent::__construct();
73 }
74
75 /**
76 * get the values from the rp_invoice_id string.
77 *
78 * @param string $name
79 * E.g. i, values are stored in the string with letter codes.
80 * @param bool $abort
81 * Throw exception if not found
82 *
83 * @throws CRM_Core_Exception
84 * @return mixed
85 */
86 public function getValue($name, $abort = TRUE) {
87 if ($abort && empty($this->_invoiceData[$name])) {
88 throw new CRM_Core_Exception("Failure: Missing Parameter $name");
89 }
90 else {
91 return CRM_Utils_Array::value($name, $this->_invoiceData);
92 }
93 }
94
95 /**
96 * Set $this->_invoiceData from the input array
97 */
98 public function setInvoiceData() {
99 if (empty($this->_inputParameters['rp_invoice_id'])) {
100 $this->_isPaymentExpress = TRUE;
101 return;
102 }
103 $rpInvoiceArray = explode('&', $this->_inputParameters['rp_invoice_id']);
104 // for clarify let's also store without the single letter unreadable
105 //@todo after more refactoring we might ditch storing the one letter stuff
106 $mapping = array(
107 'i' => 'invoice_id',
108 'm' => 'component',
109 'c' => 'contact_id',
110 'b' => 'contribution_id',
111 'r' => 'contribution_recur_id',
112 'p' => 'participant_id',
113 'e' => 'event_id',
114 );
115 foreach ($rpInvoiceArray as $rpInvoiceValue) {
116 $rpValueArray = explode('=', $rpInvoiceValue);
117 $this->_invoiceData[$rpValueArray[0]] = $rpValueArray[1];
118 $this->_inputParameters[$mapping[$rpValueArray[0]]] = $rpValueArray[1];
119 // p has been overloaded & could mean contribution page or participant id. Clearly we need an
120 // alphabet with more letters.
121 // the mode will always be resolved before the mystery p is reached
122 if ($rpValueArray[1] == 'contribute') {
123 $mapping['p'] = 'contribution_page_id';
124 }
125 }
126 if (empty($this->_inputParameters['component'])) {
127 $this->_isPaymentExpress = TRUE;
128 }
129 }
130
131 /**
132 * @param string $name
133 * Of variable to return.
134 * @param string $type
135 * Data type.
136 * - String
137 * - Integer
138 * @param string $location
139 * Deprecated.
140 * @param bool $abort
141 * Abort if empty.
142 *
143 * @throws CRM_Core_Exception
144 * @return mixed
145 */
146 public function retrieve($name, $type, $location = 'POST', $abort = TRUE) {
147 $value = CRM_Utils_Type::validate(
148 CRM_Utils_Array::value($name, $this->_inputParameters),
149 $type,
150 FALSE
151 );
152 if ($abort && $value === NULL) {
153 throw new CRM_Core_Exception("Could not find an entry for $name in $location");
154 }
155 return $value;
156 }
157
158 /**
159 * Process recurring contributions.
160 * @param array $input
161 * @param array $ids
162 * @param array $objects
163 * @param bool $first
164 * @return bool
165 */
166 public function recur(&$input, &$ids, &$objects, $first) {
167 if (!isset($input['txnType'])) {
168 CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
169 echo "Failure: Invalid parameters<p>";
170 return FALSE;
171 }
172
173 if ($input['txnType'] == 'recurring_payment' &&
174 $input['paymentStatus'] != 'Completed'
175 ) {
176 CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
177 echo "Failure: Invalid parameters<p>";
178 return FALSE;
179 }
180
181 $recur = &$objects['contributionRecur'];
182
183 // make sure the invoice ids match
184 // make sure the invoice is valid and matches what we have in
185 // the contribution record
186 if ($recur->invoice_id != $input['invoice']) {
187 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice']);
188 echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice'];
189 return FALSE;
190 }
191
192 $now = date('YmdHis');
193
194 // fix dates that already exist
195 $dates = array('create', 'start', 'end', 'cancel', 'modified');
196 foreach ($dates as $date) {
197 $name = "{$date}_date";
198 if ($recur->$name) {
199 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
200 }
201 }
202
203 $sendNotification = FALSE;
204 $subscriptionPaymentStatus = NULL;
205 //List of Transaction Type
206 /*
207 recurring_payment_profile_created RP Profile Created
208 recurring_payment RP Successful Payment
209 recurring_payment_failed RP Failed Payment
210 recurring_payment_profile_cancel RP Profile Cancelled
211 recurring_payment_expired RP Profile Expired
212 recurring_payment_skipped RP Profile Skipped
213 recurring_payment_outstanding_payment RP Successful Outstanding Payment
214 recurring_payment_outstanding_payment_failed RP Failed Outstanding Payment
215 recurring_payment_suspended RP Profile Suspended
216 recurring_payment_suspended_due_to_max_failed_payment RP Profile Suspended due to Max Failed Payment
217 */
218
219 //set transaction type
220 $txnType = $this->retrieve('txn_type', 'String');
221 //Changes for paypal pro recurring payment
222 $contributionStatuses = civicrm_api3('contribution', 'getoptions', array('field' => 'contribution_status_id'));
223 $contributionStatuses = $contributionStatuses['values'];
224 switch ($txnType) {
225 case 'recurring_payment_profile_created':
226 if (in_array($recur->contribution_status_id, array(
227 array_search('Pending', $contributionStatuses),
228 array_search('In Progress', $contributionStatuses),
229 ))
230 && !empty($recur->processor_id)
231 ) {
232 echo "already handled";
233 return FALSE;
234 }
235 $recur->create_date = $now;
236 $recur->contribution_status_id = 2;
237 $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
238 $recur->trxn_id = $recur->processor_id;
239 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
240 $sendNotification = TRUE;
241 break;
242
243 case 'recurring_payment':
244 if ($first) {
245 $recur->start_date = $now;
246 }
247 else {
248 $recur->modified_date = $now;
249 }
250
251 //contribution installment is completed
252 if ($this->retrieve('profile_status', 'String') == 'Expired') {
253 if (!empty($recur->end_date)) {
254 echo "already handled";
255 return FALSE;
256 }
257 $recur->contribution_status_id = 1;
258 $recur->end_date = $now;
259 $sendNotification = TRUE;
260 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
261 }
262
263 // make sure the contribution status is not done
264 // since order of ipn's is unknown
265 if ($recur->contribution_status_id != 1) {
266 $recur->contribution_status_id = 5;
267 }
268 break;
269 }
270
271 $recur->save();
272
273 if ($sendNotification) {
274 $autoRenewMembership = FALSE;
275 if ($recur->id &&
276 isset($ids['membership']) && $ids['membership']
277 ) {
278 $autoRenewMembership = TRUE;
279 }
280 //send recurring Notification email for user
281 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
282 $ids['contact'],
283 $ids['contributionPage'],
284 $recur,
285 $autoRenewMembership
286 );
287 }
288
289 if ($txnType != 'recurring_payment') {
290 return TRUE;
291 }
292
293 if (!$first) {
294 //check if this contribution transaction is already processed
295 //if not create a contribution and then get it processed
296 $contribution = new CRM_Contribute_BAO_Contribution();
297 $contribution->trxn_id = $input['trxn_id'];
298 if ($contribution->trxn_id && $contribution->find()) {
299 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
300 echo "Success: Contribution has already been handled<p>";
301 return TRUE;
302 }
303
304 $contribution->contact_id = $recur->contact_id;
305 $contribution->financial_type_id = $objects['contributionType']->id;
306 $contribution->contribution_page_id = $ids['contributionPage'];
307 $contribution->contribution_recur_id = $ids['contributionRecur'];
308 $contribution->currency = $objects['contribution']->currency;
309 $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
310 $contribution->amount_level = $objects['contribution']->amount_level;
311 $contribution->campaign_id = $objects['contribution']->campaign_id;
312 $objects['contribution'] = &$contribution;
313 }
314 // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
315 $objects['contribution']->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])) : $now;
316
317 $this->single($input, $ids, $objects,
318 TRUE, $first
319 );
320 }
321
322 /**
323 * @param $input
324 * @param $ids
325 * @param $objects
326 * @param bool $recur
327 * @param bool $first
328 *
329 * @return bool
330 */
331 public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
332 $contribution = &$objects['contribution'];
333
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'];
339 return FALSE;
340 }
341 }
342 else {
343 $contribution->invoice_id = md5(uniqid(rand(), TRUE));
344 }
345
346 if (!$recur) {
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>";
350 return FALSE;
351 }
352 }
353 else {
354 $contribution->total_amount = $input['amount'];
355 }
356
357 $transaction = new CRM_Core_Transaction();
358
359 $participant = &$objects['participant'];
360 $membership = &$objects['membership'];
361
362 $status = $input['paymentStatus'];
363 if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
364 return $this->failed($objects, $transaction);
365 }
366 elseif ($status == 'Pending') {
367 return $this->pending($objects, $transaction);
368 }
369 elseif ($status == 'Refunded' || $status == 'Reversed') {
370 return $this->cancelled($objects, $transaction);
371 }
372 elseif ($status != 'Completed') {
373 return $this->unhandled($objects, $transaction);
374 }
375
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>";
381 return TRUE;
382 }
383
384 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
385 }
386
387 /**
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
390 *
391 * @todo the references to POST throughout this class need to be removed
392 * @return bool
393 */
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();
399 return FALSE;
400 }
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);
407
408 $this->getInput($input, $ids);
409
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);
414 }
415 else {
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);
424 }
425
426 if (!$ids['membership'] && $ids['contributionRecur']) {
427 $sql = "
428 SELECT m.id
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
432 LIMIT 1";
433 $sqlParams = array(
434 1 => array($ids['contribution'], 'Integer'),
435 2 => array($ids['contributionRecur'], 'Integer'),
436 );
437 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql, $sqlParams)) {
438 $ids['membership'] = $membershipId;
439 }
440 }
441
442 // This is an unreliable method as there could be more than one instance.
443 // Recommended approach is to use the civicrm/payment/ipn/xx url where xx is the payment
444 // processor id & the handleNotification function (which should call the completetransaction api & by-pass this
445 // entirely). The only thing the IPN class should really do is extract data from the request, validate it
446 // & call completetransaction or call fail? (which may not exist yet).
447 $paymentProcessorTypeID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
448 'PayPal', 'id', 'name'
449 );
450 $paymentProcessorID = (int) civicrm_api3('PaymentProcessor', 'getvalue', array(
451 'is_test' => 0,
452 'options' => array('limit' => 1),
453 'payment_processor_type_id' => $paymentProcessorTypeID,
454 'return' => 'id',
455 ));
456
457 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
458 return FALSE;
459 }
460
461 self::$_paymentProcessor = &$objects['paymentProcessor'];
462 //?? how on earth would we not have component be one of these?
463 // they are the only valid settings & this IPN file can't even be called without one of them
464 // grepping for this class doesn't find other paths to call this class
465 if ($this->_component == 'contribute' || $this->_component == 'event') {
466 if ($ids['contributionRecur']) {
467 // check if first contribution is completed, else complete first contribution
468 $first = TRUE;
469 if ($objects['contribution']->contribution_status_id == 1) {
470 $first = FALSE;
471 }
472 return $this->recur($input, $ids, $objects, $first);
473 }
474 else {
475 return $this->single($input, $ids, $objects, FALSE, FALSE);
476 }
477 }
478 else {
479 return $this->single($input, $ids, $objects, FALSE, FALSE);
480 }
481 }
482
483 /**
484 * @param $input
485 * @param $ids
486 *
487 * @return bool
488 * @throws CRM_Core_Exception
489 */
490 public function getInput(&$input, &$ids) {
491
492 if (!$this->getBillingID($ids)) {
493 return FALSE;
494 }
495
496 $input['txnType'] = self::retrieve('txn_type', 'String', 'POST', FALSE);
497 $input['paymentStatus'] = self::retrieve('payment_status', 'String', 'POST', FALSE);
498
499 $input['amount'] = self::retrieve('mc_gross', 'Money', 'POST', FALSE);
500 $input['reasonCode'] = self::retrieve('ReasonCode', 'String', 'POST', FALSE);
501
502 $billingID = $ids['billing'];
503 $lookup = array(
504 "first_name" => 'first_name',
505 "last_name" => 'last_name',
506 "street_address-{$billingID}" => 'address_street',
507 "city-{$billingID}" => 'address_city',
508 "state-{$billingID}" => 'address_state',
509 "postal_code-{$billingID}" => 'address_zip',
510 "country-{$billingID}" => 'address_country_code',
511 );
512 foreach ($lookup as $name => $paypalName) {
513 $value = self::retrieve($paypalName, 'String', 'POST', FALSE);
514 $input[$name] = $value ? $value : NULL;
515 }
516
517 $input['is_test'] = self::retrieve('test_ipn', 'Integer', 'POST', FALSE);
518 $input['fee_amount'] = self::retrieve('mc_fee', 'Money', 'POST', FALSE);
519 $input['net_amount'] = self::retrieve('settle_amount', 'Money', 'POST', FALSE);
520 $input['trxn_id'] = self::retrieve('txn_id', 'String', 'POST', FALSE);
521 $input['payment_date'] = $input['receive_date'] = self::retrieve('payment_date', 'String', 'POST', FALSE);
522 }
523
524 /**
525 * Handle payment express IPNs.
526 * For one off IPNS no actual response is required
527 * Recurring is more difficult as we have limited confirmation material
528 * lets look up invoice id in recur_contribution & rely on the unique transaction id to ensure no
529 * duplicated
530 * this may not be acceptable to all sites - e.g. if they are shipping or delivering something in return
531 * then the quasi security of the ids array might be required - although better to
532 * http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
533 * but let's assume knowledge on invoice id & schedule is enough for now esp for donations
534 * only contribute is handled
535 */
536 public function handlePaymentExpress() {
537 //@todo - loads of copy & paste / code duplication but as this not going into core need to try to
538 // keep discreet
539 // also note that a lot of the complexity above could be removed if we used
540 // http://stackoverflow.com/questions/4848227/validate-that-ipn-call-is-from-paypal
541 // as membership id etc can be derived by the load objects fn
542 $objects = $ids = $input = array();
543 $isFirst = FALSE;
544 $input['txnType'] = $this->retrieve('txn_type', 'String');
545 if ($input['txnType'] != 'recurring_payment') {
546 throw new CRM_Core_Exception('Paypal IPNS not handled other than recurring_payments');
547 }
548 $input['invoice'] = self::getValue('i', FALSE);
549 $this->getInput($input, $ids);
550 if ($this->transactionExists($input['trxn_id'])) {
551 throw new CRM_Core_Exception('This transaction has already been processed');
552 }
553
554 $contributionRecur = civicrm_api3('contribution_recur', 'getsingle', array(
555 'return' => 'contact_id, id',
556 'invoice_id' => $input['invoice'],
557 ));
558 $ids['contact'] = $contributionRecur['contact_id'];
559 $ids['contributionRecur'] = $contributionRecur['id'];
560 $result = civicrm_api3('contribution', 'getsingle', array('invoice_id' => $input['invoice']));
561
562 $ids['contribution'] = $result['id'];
563 //@todo hard - coding 'pending' for now
564 if ($result['contribution_status_id'] == 2) {
565 $isFirst = TRUE;
566 }
567 // arg api won't get this - fix it
568 $ids['contributionPage'] = CRM_Core_DAO::singleValueQuery("SELECT contribution_page_id FROM civicrm_contribution WHERE invoice_id = %1", array(
569 1 => array(
570 $ids['contribution'],
571 'Integer',
572 ),
573 ));
574 // only handle component at this stage - not terribly sure how a recurring event payment would arise
575 // & suspec main function may be a victom of copy & paste
576 // membership would be an easy add - but not relevant to my customer...
577 $this->_component = $input['component'] = 'contribute';
578 $input['trxn_date'] = date('Y-m-d-H-i-s', strtotime(self::retrieve('time_created', 'String')));
579 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
580 'PayPal', 'id', 'name'
581 );
582
583 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
584 throw new CRM_Core_Exception('Data did not validate');
585 }
586 return $this->recur($input, $ids, $objects, $isFirst);
587 }
588
589 /**
590 * Function check if transaction already exists.
591 * @param string $trxn_id
592 * @return bool|void
593 */
594 public function transactionExists($trxn_id) {
595 if (CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM civicrm_contribution WHERE trxn_id = %1",
596 array(
597 1 => array($trxn_id, 'String'),
598 ))
599 ) {
600 return TRUE;
601 }
602 }
603
604 }