3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
34 class CRM_Core_Payment_PayPalIPN
extends CRM_Core_Payment_BaseIPN
{
36 static $_paymentProcessor = NULL;
39 * Input parameters from payment processor. Store these so that
40 * the code does not need to keep retrieving from the http request
43 protected $_inputParameters = array();
46 * Constructor function.
48 * @param array $inputData
49 * Contents of HTTP REQUEST.
51 * @throws CRM_Core_Exception
53 public function __construct($inputData) {
55 $params = (!empty($inputData['custom'])) ?
56 array_merge($inputData, json_decode($inputData['custom'], TRUE)) :
58 $this->setInputParameters($params);
59 parent
::__construct();
68 * @throws \CRM_Core_Exception
70 public function retrieve($name, $type, $abort = TRUE) {
71 $value = CRM_Utils_Type
::validate(CRM_Utils_Array
::value($name, $this->_inputParameters
), $type, FALSE);
72 if ($abort && $value === NULL) {
73 Civi
::log()->debug("PayPalIPN: Could not find an entry for $name");
74 echo "Failure: Missing Parameter<p>" . CRM_Utils_Type
::escape($name, 'String');
75 throw new CRM_Core_Exception("PayPalIPN: Could not find an entry for $name");
83 * @param array $objects
88 * @throws \CRM_Core_Exception
89 * @throws \CiviCRM_API3_Exception
91 public function recur(&$input, &$ids, &$objects, $first) {
92 if (!isset($input['txnType'])) {
93 Civi
::log()->debug('PayPalIPN: Could not find txn_type in input request');
94 echo "Failure: Invalid parameters<p>";
98 if ($input['txnType'] == 'subscr_payment' &&
99 $input['paymentStatus'] != 'Completed'
101 Civi
::log()->debug('PayPalIPN: Ignore all IPN payments that are not completed');
102 echo "Failure: Invalid parameters<p>";
106 $recur = &$objects['contributionRecur'];
108 // make sure the invoice ids match
109 // make sure the invoice is valid and matches what we have in the contribution record
110 if ($recur->invoice_id
!= $input['invoice']) {
111 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request (RecurID: ' . $recur->id
. ').');
112 echo "Failure: Invoice values dont match between database and IPN request<p>";
116 $now = date('YmdHis');
118 // fix dates that already exist
119 $dates = array('create', 'start', 'end', 'cancel', 'modified');
120 foreach ($dates as $date) {
121 $name = "{$date}_date";
123 $recur->$name = CRM_Utils_Date
::isoToMysql($recur->$name);
126 $sendNotification = FALSE;
127 $subscriptionPaymentStatus = NULL;
128 // set transaction type
129 $txnType = $this->retrieve('txn_type', 'String');
130 $contributionStatuses = array_flip(CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'validate'));
132 case 'subscr_signup':
133 $recur->create_date
= $now;
134 // sometimes subscr_signup response come after the subscr_payment and set to pending mode.
136 $statusID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionRecur',
137 $recur->id
, 'contribution_status_id'
139 if ($statusID != $contributionStatuses['In Progress']) {
140 $recur->contribution_status_id
= $contributionStatuses['Pending'];
142 $recur->processor_id
= $this->retrieve('subscr_id', 'String');
143 $recur->trxn_id
= $recur->processor_id
;
144 $sendNotification = TRUE;
145 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_START
;
149 if ($recur->contribution_status_id
!= $contributionStatuses['Cancelled']) {
150 $recur->contribution_status_id
= $contributionStatuses['Completed'];
152 $recur->end_date
= $now;
153 $sendNotification = TRUE;
154 $subscriptionPaymentStatus = CRM_Core_Payment
::RECURRING_PAYMENT_END
;
157 case 'subscr_cancel':
158 $recur->contribution_status_id
= $contributionStatuses['Cancelled'];
159 $recur->cancel_date
= $now;
162 case 'subscr_failed':
163 $recur->contribution_status_id
= $contributionStatuses['Failed'];
164 $recur->modified_date
= $now;
167 case 'subscr_modify':
168 Civi
::log()->debug('PayPalIPN: We do not handle modifications to subscriptions right now (RecurID: ' . $recur->id
. ').');
169 echo "Failure: We do not handle modifications to subscriptions right now<p>";
172 case 'subscr_payment':
174 $recur->start_date
= $now;
177 $recur->modified_date
= $now;
180 // make sure the contribution status is not done
181 // since order of ipn's is unknown
182 if ($recur->contribution_status_id
!= $contributionStatuses['Completed']) {
183 $recur->contribution_status_id
= $contributionStatuses['In Progress'];
190 if ($sendNotification) {
191 $autoRenewMembership = FALSE;
193 isset($ids['membership']) && $ids['membership']
195 $autoRenewMembership = TRUE;
198 //send recurring Notification email for user
199 CRM_Contribute_BAO_ContributionPage
::recurringNotify($subscriptionPaymentStatus,
201 $ids['contributionPage'],
207 if ($txnType != 'subscr_payment') {
212 // check if this contribution transaction is already processed
213 // if not create a contribution and then get it processed
214 $contribution = new CRM_Contribute_BAO_Contribution();
215 $contribution->trxn_id
= $input['trxn_id'];
216 if ($contribution->trxn_id
&& $contribution->find()) {
217 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled (trxn_id: ' . $contribution->trxn_id
. ')');
218 echo "Success: Contribution has already been handled<p>";
222 if ($input['paymentStatus'] != 'Completed') {
223 throw new CRM_Core_Exception("Ignore all IPN payments that are not completed");
226 $contribution->contact_id
= $ids['contact'];
227 $contribution->financial_type_id
= $objects['contributionType']->id
;
228 $contribution->contribution_page_id
= $ids['contributionPage'];
229 $contribution->contribution_recur_id
= $ids['contributionRecur'];
230 $contribution->receive_date
= $now;
231 $contribution->currency
= $objects['contribution']->currency
;
232 $contribution->payment_instrument_id
= $objects['contribution']->payment_instrument_id
;
233 $contribution->amount_level
= $objects['contribution']->amount_level
;
234 $contribution->campaign_id
= $objects['contribution']->campaign_id
;
236 $objects['contribution'] = &$contribution;
239 $this->single($input, $ids, $objects,
245 * @param array $input
247 * @param array $objects
253 public function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE) {
254 $contribution = &$objects['contribution'];
256 // make sure the invoice is valid and matches what we have in the contribution record
257 if ((!$recur) ||
($recur && $first)) {
258 if ($contribution->invoice_id
!= $input['invoice']) {
259 Civi
::log()->debug('PayPalIPN: Invoice values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
260 echo "Failure: Invoice values dont match between database and IPN request<p>";
265 $contribution->invoice_id
= md5(uniqid(rand(), TRUE));
269 if ($contribution->total_amount
!= $input['amount']) {
270 Civi
::log()->debug('PayPalIPN: Amount values dont match between database and IPN request. (ID: ' . $contribution->id
. ').');
271 echo "Failure: Amount values dont match between database and IPN request<p>";
276 $contribution->total_amount
= $input['amount'];
279 $transaction = new CRM_Core_Transaction();
281 $status = $input['paymentStatus'];
282 if ($status == 'Denied' ||
$status == 'Failed' ||
$status == 'Voided') {
283 return $this->failed($objects, $transaction);
285 elseif ($status == 'Pending') {
286 return $this->pending($objects, $transaction);
288 elseif ($status == 'Refunded' ||
$status == 'Reversed') {
289 return $this->cancelled($objects, $transaction);
291 elseif ($status != 'Completed') {
292 return $this->unhandled($objects, $transaction);
295 // check if contribution is already completed, if so we ignore this ipn
296 $completedStatusId = CRM_Core_Pseudoconstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
297 if ($contribution->contribution_status_id
== $completedStatusId) {
298 $transaction->commit();
299 Civi
::log()->debug('PayPalIPN: Returning since contribution has already been handled. (ID: ' . $contribution->id
. ').');
300 echo "Success: Contribution has already been handled<p>";
304 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
310 * @throws \CRM_Core_Exception
311 * @throws \CiviCRM_API3_Exception
313 public function main() {
314 $objects = $ids = $input = array();
315 $component = $this->retrieve('module', 'String');
316 $input['component'] = $component;
318 $ids['contact'] = $this->retrieve('contactID', 'Integer', TRUE);
319 $ids['contribution'] = $this->retrieve('contributionID', 'Integer', TRUE);
321 $this->getInput($input, $ids);
323 if ($component == 'event') {
324 $ids['event'] = $this->retrieve('eventID', 'Integer', TRUE);
325 $ids['participant'] = $this->retrieve('participantID', 'Integer', TRUE);
328 // get the optional ids
329 $ids['membership'] = $this->retrieve('membershipID', 'Integer', FALSE);
330 $ids['contributionRecur'] = $this->retrieve('contributionRecurID', 'Integer', FALSE);
331 $ids['contributionPage'] = $this->retrieve('contributionPageID', 'Integer', FALSE);
332 $ids['related_contact'] = $this->retrieve('relatedContactID', 'Integer', FALSE);
333 $ids['onbehalf_dupe_alert'] = $this->retrieve('onBehalfDupeAlert', 'Integer', FALSE);
336 $paymentProcessorID = $this->retrieve('processor_id', 'Integer', FALSE);
337 if (empty($paymentProcessorID)) {
338 $processorParams = array(
339 'user_name' => $this->retrieve('business', 'String', FALSE),
340 'payment_processor_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', 'PayPal_Standard', 'id', 'name'),
341 'is_test' => empty($input['is_test']) ?
0 : 1,
344 $processorInfo = array();
345 if (!CRM_Financial_BAO_PaymentProcessor
::retrieve($processorParams, $processorInfo)) {
348 $paymentProcessorID = $processorInfo['id'];
351 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
355 self
::$_paymentProcessor = &$objects['paymentProcessor'];
356 if ($component == 'contribute') {
357 if ($ids['contributionRecur']) {
358 // check if first contribution is completed, else complete first contribution
360 $completedStatusId = CRM_Core_Pseudoconstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
361 if ($objects['contribution']->contribution_status_id
== $completedStatusId) {
364 $this->recur($input, $ids, $objects, $first);
368 $this->single($input, $ids, $objects, FALSE, FALSE);
372 * @param array $input
375 * @throws \CRM_Core_Exception
377 public function getInput(&$input, &$ids) {
378 if (!$this->getBillingID($ids)) {
382 $input['txnType'] = $this->retrieve('txn_type', 'String', FALSE);
383 $input['paymentStatus'] = $this->retrieve('payment_status', 'String', FALSE);
384 $input['invoice'] = $this->retrieve('invoice', 'String', TRUE);
385 $input['amount'] = $this->retrieve('mc_gross', 'Money', FALSE);
386 $input['reasonCode'] = $this->retrieve('ReasonCode', 'String', FALSE);
388 $billingID = $ids['billing'];
390 "first_name" => 'first_name',
391 "last_name" => 'last_name',
392 "street_address-{$billingID}" => 'address_street',
393 "city-{$billingID}" => 'address_city',
394 "state-{$billingID}" => 'address_state',
395 "postal_code-{$billingID}" => 'address_zip',
396 "country-{$billingID}" => 'address_country_code',
398 foreach ($lookup as $name => $paypalName) {
399 $value = $this->retrieve($paypalName, 'String', FALSE);
400 $input[$name] = $value ?
$value : NULL;
403 $input['is_test'] = $this->retrieve('test_ipn', 'Integer', FALSE);
404 $input['fee_amount'] = $this->retrieve('mc_fee', 'Money', FALSE);
405 $input['net_amount'] = $this->retrieve('settle_amount', 'Money', FALSE);
406 $input['trxn_id'] = $this->retrieve('txn_id', 'String', FALSE);