commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-new / civicrm / CRM / Core / Payment / PaymentExpressIPN.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | This file is a part of CiviCRM. |
7 | |
8 | CiviCRM is free software; you can copy, modify, and distribute it |
9 | under the terms of the GNU Affero General Public License |
10 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
11 | |
12 | CiviCRM is distributed in the hope that it will be useful, but |
13 | WITHOUT ANY WARRANTY; without even the implied warranty of |
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
15 | See the GNU Affero General Public License for more details. |
16 | |
17 | You should have received a copy of the GNU Affero General Public |
18 | License and the CiviCRM Licensing Exception along |
19 | with this program; if not, contact CiviCRM LLC |
20 | at info[AT]civicrm[DOT]org. If you have questions about the |
21 | GNU Affero General Public License or the licensing of CiviCRM, |
22 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
23 +--------------------------------------------------------------------+
24 */
25
26
27 /*
28 * PxPay Functionality Copyright (C) 2008 Lucas Baker, Logistic Information Systems Limited (Logis)
29 * PxAccess Functionality Copyright (C) 2008 Eileen McNaughton
30 * Licensed to CiviCRM under the Academic Free License version 3.0.
31 *
32 * Grateful acknowledgements go to Donald Lobo for invaluable assistance
33 * in creating this payment processor module
34 */
35
36 /**
37 * Class CRM_Core_Payment_PaymentExpressIPN
38 */
39 class CRM_Core_Payment_PaymentExpressIPN extends CRM_Core_Payment_BaseIPN {
40
41 /**
42 * We only need one instance of this object. So we use the singleton
43 * pattern and cache the instance in this variable
44 *
45 * @var object
46 */
47 static private $_singleton = NULL;
48
49 /**
50 * Mode of operation: live or test
51 *
52 * @var object
53 */
54 protected $_mode = NULL;
55
56 /**
57 * @param string $name
58 * @param $type
59 * @param $object
60 * @param bool $abort
61 *
62 * @return mixed
63 */
64 public static function retrieve($name, $type, $object, $abort = TRUE) {
65 $value = CRM_Utils_Array::value($name, $object);
66 if ($abort && $value === NULL) {
67 CRM_Core_Error::debug_log_message("Could not find an entry for $name");
68 echo "Failure: Missing Parameter - " . $name . "<p>";
69 exit();
70 }
71
72 if ($value) {
73 if (!CRM_Utils_Type::validate($value, $type)) {
74 CRM_Core_Error::debug_log_message("Could not find a valid entry for $name");
75 echo "Failure: Invalid Parameter<p>";
76 exit();
77 }
78 }
79
80 return $value;
81 }
82
83 /**
84 * Constructor.
85 *
86 * @param string $mode
87 * The mode of operation: live or test.
88 *
89 * @param $paymentProcessor
90 *
91 * @return \CRM_Core_Payment_PaymentExpressIPN
92 */
93 public function __construct($mode, &$paymentProcessor) {
94 parent::__construct();
95
96 $this->_mode = $mode;
97 $this->_paymentProcessor = $paymentProcessor;
98 }
99
100 /**
101 * The function gets called when a new order takes place.
102 *
103 * @param $success
104 * @param array $privateData
105 * Contains the name value pair of <merchant-private-data>.
106 *
107 * @param $component
108 * @param $amount
109 * @param $transactionReference
110 *
111 * @internal param \xml $dataRoot response send by google in xml format
112 * @return void
113 */
114 public function newOrderNotify($success, $privateData, $component, $amount, $transactionReference) {
115 $ids = $input = $params = array();
116
117 $input['component'] = strtolower($component);
118
119 $ids['contact'] = self::retrieve('contactID', 'Integer', $privateData, TRUE);
120 $ids['contribution'] = self::retrieve('contributionID', 'Integer', $privateData, TRUE);
121
122 if ($input['component'] == "event") {
123 $ids['event'] = self::retrieve('eventID', 'Integer', $privateData, TRUE);
124 $ids['participant'] = self::retrieve('participantID', 'Integer', $privateData, TRUE);
125 $ids['membership'] = NULL;
126 }
127 else {
128 $ids['membership'] = self::retrieve('membershipID', 'Integer', $privateData, FALSE);
129 }
130 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
131
132 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
133 'PayPal_Express', 'id', 'name'
134 );
135
136 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
137 return FALSE;
138 }
139
140 // make sure the invoice is valid and matches what we have in the contribution record
141 $input['invoice'] = $privateData['invoiceID'];
142 $input['newInvoice'] = $transactionReference;
143 $contribution = &$objects['contribution'];
144 $input['trxn_id'] = $transactionReference;
145
146 if ($contribution->invoice_id != $input['invoice']) {
147 CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
148 echo "Failure: Invoice values dont match between database and IPN request<p>";
149 return;
150 }
151
152 // lets replace invoice-id with Payment Processor -number because thats what is common and unique
153 // in subsequent calls or notifications sent by google.
154 $contribution->invoice_id = $input['newInvoice'];
155
156 $input['amount'] = $amount;
157
158 if ($contribution->total_amount != $input['amount']) {
159 CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
160 echo "Failure: Amount values dont match between database and IPN request. " . $contribution->total_amount . "/" . $input['amount'] . "<p>";
161 return;
162 }
163
164 $transaction = new CRM_Core_Transaction();
165
166 // check if contribution is already completed, if so we ignore this ipn
167
168 if ($contribution->contribution_status_id == 1) {
169 CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
170 echo "Success: Contribution has already been handled<p>";
171 return TRUE;
172 }
173 else {
174 /* Since trxn_id hasn't got any use here,
175 * lets make use of it by passing the eventID/membershipTypeID to next level.
176 * And change trxn_id to the payment processor reference before finishing db update */
177
178 if ($ids['event']) {
179 $contribution->trxn_id = $ids['event'] . CRM_Core_DAO::VALUE_SEPARATOR . $ids['participant'];
180 }
181 else {
182 $contribution->trxn_id = $ids['membership'];
183 }
184 }
185 $this->completeTransaction($input, $ids, $objects, $transaction);
186 return TRUE;
187 }
188
189 /**
190 *
191 * /**
192 * The function returns the component(Event/Contribute..)and whether it is Test or not
193 *
194 * @param array $privateData
195 * Contains the name-value pairs of transaction related data.
196 * @param int $orderNo
197 * <order-total> send by google.
198 *
199 * @return array
200 * context of this call (test, component, payment processor id)
201 */
202 public static function getContext($privateData, $orderNo) {
203
204 $component = NULL;
205 $isTest = NULL;
206
207 $contributionID = $privateData['contributionID'];
208 $contribution = new CRM_Contribute_DAO_Contribution();
209 $contribution->id = $contributionID;
210
211 if (!$contribution->find(TRUE)) {
212 CRM_Core_Error::debug_log_message("Could not find contribution record: $contributionID");
213 echo "Failure: Could not find contribution record for $contributionID<p>";
214 exit();
215 }
216
217 if (stristr($contribution->source, 'Online Contribution')) {
218 $component = 'contribute';
219 }
220 elseif (stristr($contribution->source, 'Online Event Registration')) {
221 $component = 'event';
222 }
223 $isTest = $contribution->is_test;
224
225 $duplicateTransaction = 0;
226 if ($contribution->contribution_status_id == 1) {
227 //contribution already handled. (some processors do two notifications so this could be valid)
228 $duplicateTransaction = 1;
229 }
230
231 if ($component == 'contribute') {
232 if (!$contribution->contribution_page_id) {
233 CRM_Core_Error::debug_log_message("Could not find contribution page for contribution record: $contributionID");
234 echo "Failure: Could not find contribution page for contribution record: $contributionID<p>";
235 exit();
236 }
237 }
238 else {
239
240 $eventID = $privateData['eventID'];
241
242 if (!$eventID) {
243 CRM_Core_Error::debug_log_message("Could not find event ID");
244 echo "Failure: Could not find eventID<p>";
245 exit();
246 }
247
248 // we are in event mode
249 // make sure event exists and is valid
250 $event = new CRM_Event_DAO_Event();
251 $event->id = $eventID;
252 if (!$event->find(TRUE)) {
253 CRM_Core_Error::debug_log_message("Could not find event: $eventID");
254 echo "Failure: Could not find event: $eventID<p>";
255 exit();
256 }
257 }
258
259 return array($isTest, $component, $duplicateTransaction);
260 }
261
262 /**
263 * This method is handles the response that will be invoked by the
264 * notification or request sent by the payment processor.
265 * hex string from paymentexpress is passed to this function as hex string. Code based on googleIPN
266 * mac_key is only passed if the processor is pxaccess as it is used for decryption
267 * $dps_method is either pxaccess or pxpay
268 */
269 public static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps_key, $mac_key) {
270
271 $config = CRM_Core_Config::singleton();
272 define('RESPONSE_HANDLER_LOG_FILE', $config->uploadDir . 'CiviCRM.PaymentExpress.log');
273
274 //Setup the log file
275 if (!$message_log = fopen(RESPONSE_HANDLER_LOG_FILE, "a")) {
276 error_func("Cannot open " . RESPONSE_HANDLER_LOG_FILE . " file.\n", 0);
277 exit(1);
278 }
279
280 if ($dps_method == "pxpay") {
281 $processResponse = CRM_Core_Payment_PaymentExpressUtils::_valueXml(array(
282 'PxPayUserId' => $dps_user,
283 'PxPayKey' => $dps_key,
284 'Response' => $_GET['result'],
285 ));
286 $processResponse = CRM_Core_Payment_PaymentExpressUtils::_valueXml('ProcessResponse', $processResponse);
287
288 fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
289 $processResponse
290 ));
291
292 // Send the XML-formatted validation request to DPS so that we can receive a decrypted XML response which contains the transaction results
293 $curl = CRM_Core_Payment_PaymentExpressUtils::_initCURL($processResponse, $dps_url);
294
295 fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
296 $curl
297 ));
298 $success = FALSE;
299 if ($response = curl_exec($curl)) {
300 fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
301 $response
302 ));
303 curl_close($curl);
304
305 // Assign the returned XML values to variables
306 $valid = CRM_Core_Payment_PaymentExpressUtils::_xmlAttribute($response, 'valid');
307 $success = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, 'Success');
308 $txnId = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, 'TxnId');
309 $responseText = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, 'ResponseText');
310 $authCode = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, 'AuthCode');
311 $DPStxnRef = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, 'DpsTxnRef');
312 $qfKey = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, "TxnData1");
313 $privateData = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, "TxnData2");
314 list($component, $paymentProcessorID,) = explode(',', CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, "TxnData3"));
315 $amount = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, "AmountSettlement");
316 $merchantReference = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, "MerchantReference");
317 }
318 else {
319 // calling DPS failed
320 CRM_Core_Error::fatal(ts('Unable to establish connection to the payment gateway to verify transaction response.'));
321 exit;
322 }
323 }
324 elseif ($dps_method == "pxaccess") {
325
326 require_once 'PaymentExpress/pxaccess.inc.php';
327 global $pxaccess;
328 $pxaccess = new PxAccess($dps_url, $dps_user, $dps_key, $mac_key);
329 #getResponse method in PxAccess object returns PxPayResponse object
330 #which encapsulates all the response data
331 $rsp = $pxaccess->getResponse($rawPostData);
332
333 $qfKey = $rsp->getTxnData1();
334 $privateData = $rsp->getTxnData2();
335 list($component, $paymentProcessorID) = explode(',', $rsp->getTxnData3());
336 $success = $rsp->getSuccess();
337 $authCode = $rsp->getAuthCode();
338 $DPStxnRef = $rsp->getDpsTxnRef();
339 $amount = $rsp->getAmountSettlement();
340 $MerchantReference = $rsp->getMerchantReference();
341 }
342
343 $privateData = $privateData ? self::stringToArray($privateData) : '';
344
345 // Record the current count in array, before we start adding things (for later checks)
346 $countPrivateData = count($privateData);
347
348 // Private Data consists of : a=contactID, b=contributionID,c=contributionTypeID,d=invoiceID,e=membershipID,f=participantID,g=eventID
349 $privateData['contactID'] = $privateData['a'];
350 $privateData['contributionID'] = $privateData['b'];
351 $privateData['contributionTypeID'] = $privateData['c'];
352 $privateData['invoiceID'] = $privateData['d'];
353
354 if ($component == "event") {
355 $privateData['participantID'] = $privateData['f'];
356 $privateData['eventID'] = $privateData['g'];
357 }
358 elseif ($component == "contribute") {
359
360 if ($countPrivateData == 5) {
361 $privateData["membershipID"] = $privateData['e'];
362 }
363 }
364
365 $transactionReference = $authCode . "-" . $DPStxnRef;
366
367 list($mode, $component, $duplicateTransaction) = self::getContext($privateData, $transactionReference);
368 $mode = $mode ? 'test' : 'live';
369
370 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
371 $mode
372 );
373
374 $ipn = self::singleton($mode, $component, $paymentProcessor);
375
376 //Check status and take appropriate action
377
378 if ($success == 1) {
379 if ($duplicateTransaction == 0) {
380 $ipn->newOrderNotify($success, $privateData, $component, $amount, $transactionReference);
381 }
382
383 if ($component == "event") {
384 $finalURL = CRM_Utils_System::url('civicrm/event/register',
385 "_qf_ThankYou_display=1&qfKey=$qfKey",
386 FALSE, NULL, FALSE
387 );
388 }
389 elseif ($component == "contribute") {
390 $finalURL = CRM_Utils_System::url('civicrm/contribute/transact',
391 "_qf_ThankYou_display=1&qfKey=$qfKey",
392 FALSE, NULL, FALSE
393 );
394 }
395
396 CRM_Utils_System::redirect($finalURL);
397 }
398 else {
399
400 if ($component == "event") {
401 $finalURL = CRM_Utils_System::url('civicrm/event/confirm',
402 "reset=1&cc=fail&participantId=$privateData[participantID]",
403 FALSE, NULL, FALSE
404 );
405 }
406 elseif ($component == "contribute") {
407 $finalURL = CRM_Utils_System::url('civicrm/contribute/transact',
408 "_qf_Main_display=1&cancel=1&qfKey=$qfKey",
409 FALSE, NULL, FALSE
410 );
411 }
412
413 CRM_Utils_System::redirect($finalURL);
414 }
415 }
416
417 /**
418 * Converts the comma separated name-value pairs in <TxnData2>
419 * to an array of values.
420 */
421 public static function stringToArray($str) {
422 $vars = $labels = array();
423 $labels = explode(',', $str);
424 foreach ($labels as $label) {
425 $terms = explode('=', $label);
426 $vars[$terms[0]] = $terms[1];
427 }
428 return $vars;
429 }
430
431 }