Started fixing comments, added template for disableAutorenew()
[tc-ipn-receiver.git] / trustcommerceIPN.php
1 <?php
2 /*
3 * This file is part of CiviCRM.
4 *
5 * CiviCRM is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * CiviCRM is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with CiviCRM. If not, see <http://www.gnu.org/licenses/>.
17 *
18 * Copyright 2016, Lisa Marie Maginnis <lisa@fsf.org> (http://www.fsf.org)
19 *
20 */
21
22 /**
23 * CiviCRM (Instant Payment Notification) IPN processor module for
24 * TrustCommerece.
25 *
26 * For full documentation on the
27 * TrustCommerece API, please see the TCDevGuide for more information:
28 * https://vault.trustcommerce.com/downloads/TCDevGuide.htm
29 *
30 * This module supports the following features: Single credit/debit card
31 * transactions, AVS checking, recurring (create, update, and cancel
32 * subscription) optional blacklist with fail2ban,
33 *
34 * @copyright Lisa Marie Maginnis <lisa@fsf.org> (http://www.fsf.org)
35 * @version 1.0
36 * @package org.fsf.payment.trustcommerce.ipn
37 */
38
39 define("MAX_FAILURES", 4)
40
41 class CRM_Core_Payment_trustcommerce_IPN extends CRM_Core_Payment_BaseIPN {
42
43 /**
44 * Inheret
45 *
46 * @return void
47 */
48 function __construct() {
49 parent::__construct();
50 }
51
52 function getLastFailures($recur_id) {
53 $sql="SELECT contribution_recur_id, trxn_id, contribution_status_id,
54 SUM(id > COALESCE(
55 ( SELECT max(id) FROM civicrm_contribution AS c2
56 WHERE c2.id = c.id and c2.contribution_status_id = 1),
57 4 )) AS numfails
58 FROM civicrm_contribution AS c
59 WHERE c.contribution_recur_id = $recur_id GROUP BY c.contribution_recur_id;"
60
61 $result = CRM_Core_DAO::executeQuery($sql);
62 if($result->fetch()) {
63 $failures = $result->numfails;
64 } else {
65 $failures = NULL;
66 }
67
68 return $failures;
69
70 }
71
72 function main($component = 'contribute') {
73 static $no = NULL;
74 $billingid = CRM_Utils_Request::retrieve('billingid', 'String', $no, FALSE, 'GET');
75 $input['status'] = CRM_Utils_Request::retrieve('status', 'String', $no, FALSE, 'GET');
76 $input['amount'] = CRM_Utils_Request::retrieve('amount', 'String', $no, FALSE, 'GET');
77 $input['date'] = CRM_Utils_Request::retrieve('date', 'String', $no, FALSE, 'GET');
78 $input['trxn_id'] = CRM_Utils_Request::retrieve('trxn_id', 'String', $no, FALSE, 'GET');
79 $checksum = CRM_Utils_Request::retrieve('checksum', 'String', $no, FALSE, 'GET');
80
81 if ($billingid) {
82 if( $input['status'] == '' || $input['amount'] == '' || $input['date'] == '' || $input['trxn_id'] == '' || md5($billingid.$input['trxn_id'].$input['amount'].$input['date']) != $checksum) {
83 CRM_Core_Error::debug_log_message("Error: IPN called with out proper fields");
84 echo "Error: invalid paramaters<p>\n";
85 exit;
86 }
87
88
89 $ids = $objects = array();
90 $input['component'] = $component;
91
92 // load post ids in $ids
93 $ids = NULL;
94 $ids = $this->getIDs($billingid, $input, $input['component']);
95
96 $ids['trxn_id'] = $input['trxn_id'];
97
98 if($this->checkDuplicate($input, $ids) != NULL) {
99 $msg = 'TrustCommerceIPN: Skipping duplicate contribution: '.$ids['contribution'].' for contact: '.$ids['contact'].' amount: $'.$input['amount'].' trxn_id: '.$input['trxn_id']."\n";
100 echo $msg;
101 CRM_Core_Error::debug_log_message($msg);
102 exit;
103 }
104
105 if(array_key_exists('membership', $ids)) {
106 $membership = array();
107 $params = array('id' => $ids['membership']);
108 $obj = CRM_Member_BAO_Membership::retrieve($params, $membership);
109 $objects['membership'] = array(&$obj);
110 }
111
112 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
113 'TrustCommerce', 'id', 'name'
114 );
115
116 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
117 return FALSE;
118 }
119 // var_dump($objects);
120
121 if ($component == 'contribute' && $ids['contributionRecur']) {
122 // check if first contribution is completed, else complete first contribution
123 $first = TRUE;
124 if ($objects['contribution']->contribution_status_id == 1) {
125 $first = FALSE;
126 }
127
128
129 return $this->processRecur($input, $ids, $objects, $first);
130
131 }
132
133 }
134 }
135
136 protected function disableAutorenew($recur_id) {
137
138 }
139
140 protected function checkDuplicate($input, $ids) {
141 // $sql='select id from civicrm_contribution where receive_date like \''.$input['date'].'%\' and total_amount='.$input['amount'].' and contact_id='.$ids['contact'].' and contribution_status_id = 1 limit 1';
142 $sql="select id from civicrm_contribution where trxn_id = '".$ids['trxn_id']."'";
143
144
145 $result = CRM_Core_DAO::executeQuery($sql);
146 if($result->fetch()) {
147 $id = $result->id;
148 } else {
149 $id = NULL;
150 }
151
152 return $id;
153 }
154 protected function processRecur($input, $ids, $objects, $first) {
155 $recur = &$objects['contributionRecur'];
156 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
157
158 $transaction = new CRM_Core_Transaction();
159
160 $now = date('YmdHis');
161
162 // fix dates that already exist
163 $dates = array('create_date', 'start_date', 'end_date', 'cancel_date', 'modified_date');
164 foreach ($dates as $name) {
165 if ($recur->$name) {
166 $recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
167 }
168 }
169
170 if (!$first) {
171 // create a contribution and then get it processed
172 $contribution = new CRM_Contribute_BAO_Contribution();
173 $contribution->contact_id = $ids['contact'];
174 $contribution->financial_type_id = $objects['contributionType']->id;
175 $contribution->contribution_page_id = $ids['contributionPage'];
176 $contribution->contribution_recur_id = $ids['contributionRecur'];
177 $contribution->receive_date = $input['date'];
178 $contribution->currency = $objects['contribution']->currency;
179 $contribution->payment_instrument_id = 1;
180 $contribution->amount_level = $objects['contribution']->amount_level;
181 $contribution->address_id = $objects['contribution']->address_id;
182 $contribution->campaign_id = $objects['contribution']->campaign_id;
183 $contribution->total_amount = $input['amount'];
184
185 $objects['contribution'] = &$contribution;
186 }
187
188 $objects['contribution']->invoice_id = md5(uniqid(rand(), TRUE));
189 // $objects['contribution']->total_amount = $objects['contribution']->total_amount;
190 $objects['contribution']->trxn_id = $input['trxn_id'];
191
192 // check if contribution is already completed, if so we ignore this ipn
193 if ($objects['contribution']->contribution_status_id == 1) {
194 $transaction->commit();
195 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
196 echo 'Success: Contribution has already been handled<p>';
197 echo '';
198 return TRUE;
199 }
200
201 $sendNotification = FALSE;
202
203 $recur->trxn_id = $input['trxn_id'];
204 $recur->total_amount = $input['amount'];
205 $recur->payment_instrument_id = 1;
206 $recur->fee = 0;
207 $recur->net_amount = $input['amount'];
208
209 if ($input['status'] == 1) {
210
211 // Approved
212 if ($first) {
213 $recur->start_date = $now;
214 $sendNotification = TRUE;
215 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
216 }
217 $statusName = 'In Progress';
218 if (($recur->installments > 0) &&
219 ($input['subscription_paynum'] >= $recur->installments)
220 ) {
221 // this is the last payment
222 $statusName = 'Completed';
223 $recur->end_date = $now;
224
225 $sendNotification = TRUE;
226 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
227 }
228
229 $recur->modified_date = $now;
230 $recur->contribution_status_id = array_search($statusName, $contributionStatus);
231 $recur->save();
232 $input['is_test'] = 0;
233 $msg = 'TrustCommerceIPN: Created contribution: '.$ids['contribution'].' for contact: '.$ids['contact'].' amount: $'.$input['amount'].' trxn_id: '.$input['trxn_id'].' status: Completed'."\n";
234 echo $msg;
235 CRM_Core_Error::debug_log_message($msg);
236
237 $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
238 }
239 else if( $input['status'] == 4 ) {
240 // Declined
241 // failed status
242
243 $recur->contribution_status_id = array_search('Failed', $contributionStatus);
244 $recur->cancel_date = $now;
245 $recur->save();
246
247 $msg = 'TrustCommerceIPN: Created contribution: '.$ids['contribution'].' for contact: '.$ids['contact'].' amount: $'.$input['amount'].' trxn_id: '.$input['trxn_id'].' status: Failed'."\n";
248 echo $msg;
249 CRM_Core_Error::debug_log_message($msg);
250
251 /* Action for repeated failures */
252 if(MAX_FAILURES <= $this->getLastFailures($ids['contributionRecur'])) {
253 $this->disableAutoRenew(($ids['contributionRecur']));
254 }
255
256 return $this->failed($objects, $transaction);
257 }
258
259 if ($sendNotification) {
260 $autoRenewMembership = FALSE;
261 if ($recur->id && isset($ids['membership']) && $ids['membership'] ) {
262 $autoRenewMembership = TRUE;
263 }
264
265 //send recurring Notification email for user
266 CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus,
267 $ids['contact'],
268 $ids['contributionPage'],
269 $recur,
270 $autoRenewMembership
271 );
272 }
273 }
274
275 protected function getIDs($billingid, $input, $module) {
276 $sql = "SELECT cr.id, cr.contact_id, co.id as coid
277 FROM civicrm_contribution_recur cr
278 INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
279 WHERE cr.processor_id = '$billingid' LIMIT 1";
280
281
282 $result = CRM_Core_DAO::executeQuery($sql);
283 $result->fetch();
284 $ids['contribution'] = $result->coid;
285 $ids['contributionRecur'] = $result->id;
286 $ids['contact'] = $result->contact_id;
287 $ids['processor_id'] = $billingid;
288
289 if (!$ids['contributionRecur']) {
290 CRM_Core_Error::debug_log_message("Could not find billingid: ".$billingid);
291 echo "Failure: Could not find contributionRecur<p>\n";
292 exit();
293 }
294
295 // get page id based on contribution id
296 $ids['contributionPage'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
297 $ids['contribution'],
298 'contribution_page_id'
299 );
300
301 if ($module == 'event') {
302 // FIXME: figure out fields for event
303 }
304 else {
305 // get the optional ids
306
307 // Get membershipId. Join with membership payment table for additional checks
308 $sql = "
309 SELECT m.id
310 FROM civicrm_membership as m
311 WHERE m.contribution_recur_id = '{$ids['contributionRecur']}'
312 LIMIT 1";
313 if ($membershipId = CRM_Core_DAO::singleValueQuery($sql)) {
314
315 $ids['membership'] = $membershipId;
316 }
317
318 }
319
320 return $ids;
321 }
322
323
324
325 }