3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
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.
32 * Grateful acknowledgements go to Donald Lobo for invaluable assistance
33 * in creating this payment processor module
35 class CRM_Core_Payment_PaymentExpressIPN
extends CRM_Core_Payment_BaseIPN
{
38 * We only need one instance of this object. So we use the singleton
39 * pattern and cache the instance in this variable
44 static private $_singleton = NULL;
47 * mode of operation: live or test
51 protected $_mode = NULL;
53 static function retrieve($name, $type, $object, $abort = TRUE) {
54 $value = CRM_Utils_Array
::value($name, $object);
55 if ($abort && $value === NULL) {
56 CRM_Core_Error
::debug_log_message("Could not find an entry for $name");
57 echo "Failure: Missing Parameter - " . $name . "<p>";
62 if (!CRM_Utils_Type
::validate($value, $type)) {
63 CRM_Core_Error
::debug_log_message("Could not find a valid entry for $name");
64 echo "Failure: Invalid Parameter<p>";
75 * @param string $mode the mode of operation: live or test
79 function __construct($mode, &$paymentProcessor) {
80 parent
::__construct();
83 $this->_paymentProcessor
= $paymentProcessor;
87 * singleton function used to manage this object
89 * @param string $mode the mode of operation: live or test
94 static function &singleton($mode, $component, &$paymentProcessor) {
95 if (self
::$_singleton === NULL) {
96 self
::$_singleton = new CRM_Core_Payment_PaymentExpressIPN($mode, $paymentProcessor);
98 return self
::$_singleton;
102 * The function gets called when a new order takes place.
104 * @param xml $dataRoot response send by google in xml format
105 * @param array $privateData contains the name value pair of <merchant-private-data>
110 function newOrderNotify($success, $privateData, $component, $amount, $transactionReference) {
111 $ids = $input = $params = array();
113 $input['component'] = strtolower($component);
115 $ids['contact'] = self
::retrieve('contactID', 'Integer', $privateData, TRUE);
116 $ids['contribution'] = self
::retrieve('contributionID', 'Integer', $privateData, TRUE);
118 if ($input['component'] == "event") {
119 $ids['event'] = self
::retrieve('eventID', 'Integer', $privateData, TRUE);
120 $ids['participant'] = self
::retrieve('participantID', 'Integer', $privateData, TRUE);
121 $ids['membership'] = NULL;
124 $ids['membership'] = self
::retrieve('membershipID', 'Integer', $privateData, FALSE);
126 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
128 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
129 'PayPal_Express', 'id', 'name'
132 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
136 // make sure the invoice is valid and matches what we have in the contribution record
137 $input['invoice'] = $privateData['invoiceID'];
138 $input['newInvoice'] = $transactionReference;
139 $contribution = &$objects['contribution'];
140 $input['trxn_id'] = $transactionReference;
142 if ($contribution->invoice_id
!= $input['invoice']) {
143 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request");
144 echo "Failure: Invoice values dont match between database and IPN request<p>";
148 // lets replace invoice-id with Payment Processor -number because thats what is common and unique
149 // in subsequent calls or notifications sent by google.
150 $contribution->invoice_id
= $input['newInvoice'];
152 $input['amount'] = $amount;
154 if ($contribution->total_amount
!= $input['amount']) {
155 CRM_Core_Error
::debug_log_message("Amount values dont match between database and IPN request");
156 echo "Failure: Amount values dont match between database and IPN request. " . $contribution->total_amount
. "/" . $input['amount'] . "<p>";
160 $transaction = new CRM_Core_Transaction();
163 // if ( ! $this->createContact( $input, $ids, $objects ) ) {
167 // check if contribution is already completed, if so we ignore this ipn
169 if ($contribution->contribution_status_id
== 1) {
170 CRM_Core_Error
::debug_log_message("returning since contribution has already been handled");
171 echo "Success: Contribution has already been handled<p>";
175 /* Since trxn_id hasn't got any use here,
176 * lets make use of it by passing the eventID/membershipTypeID to next level.
177 * And change trxn_id to the payment processor reference before finishing db update */
180 $contribution->trxn_id
= $ids['event'] . CRM_Core_DAO
::VALUE_SEPARATOR
. $ids['participant'];
183 $contribution->trxn_id
= $ids['membership'];
186 $this->completeTransaction($input, $ids, $objects, $transaction);
193 * The function returns the component(Event/Contribute..)and whether it is Test or not
195 * @param array $privateData contains the name-value pairs of transaction related data
196 * @param int $orderNo <order-total> send by google
198 * @return array context of this call (test, component, payment processor id)
201 static function getContext($privateData, $orderNo) {
206 $contributionID = $privateData['contributionID'];
207 $contribution = new CRM_Contribute_DAO_Contribution();
208 $contribution->id
= $contributionID;
210 if (!$contribution->find(TRUE)) {
211 CRM_Core_Error
::debug_log_message("Could not find contribution record: $contributionID");
212 echo "Failure: Could not find contribution record for $contributionID<p>";
216 if (stristr($contribution->source
, 'Online Contribution')) {
217 $component = 'contribute';
219 elseif (stristr($contribution->source
, 'Online Event Registration')) {
220 $component = 'event';
222 $isTest = $contribution->is_test
;
224 $duplicateTransaction = 0;
225 if ($contribution->contribution_status_id
== 1) {
226 //contribution already handled. (some processors do two notifications so this could be valid)
227 $duplicateTransaction = 1;
230 if ($component == 'contribute') {
231 if (!$contribution->contribution_page_id
) {
232 CRM_Core_Error
::debug_log_message("Could not find contribution page for contribution record: $contributionID");
233 echo "Failure: Could not find contribution page for contribution record: $contributionID<p>";
239 $eventID = $privateData['eventID'];
242 CRM_Core_Error
::debug_log_message("Could not find event ID");
243 echo "Failure: Could not find eventID<p>";
247 // we are in event mode
248 // make sure event exists and is valid
249 $event = new CRM_Event_DAO_Event();
250 $event->id
= $eventID;
251 if (!$event->find(TRUE)) {
252 CRM_Core_Error
::debug_log_message("Could not find event: $eventID");
253 echo "Failure: Could not find event: $eventID<p>";
258 return array($isTest, $component, $duplicateTransaction);
262 * This method is handles the response that will be invoked by the
263 * notification or request sent by the payment processor.
264 *hex string from paymentexpress is passed to this function as hex string. Code based on googleIPN
265 * mac_key is only passed if the processor is pxaccess as it is used for decryption
266 * $dps_method is either pxaccess or pxpay
268 static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps_key, $mac_key) {
270 $config = CRM_Core_Config
::singleton();
271 define('RESPONSE_HANDLER_LOG_FILE', $config->uploadDir
. 'CiviCRM.PaymentExpress.log');
274 if (!$message_log = fopen(RESPONSE_HANDLER_LOG_FILE
, "a")) {
275 error_func("Cannot open " . RESPONSE_HANDLER_LOG_FILE
. " file.\n", 0);
279 if ($dps_method == "pxpay") {
280 $processResponse = CRM_Core_Payment_PaymentExpressUtils
::_valueXml(array(
281 'PxPayUserId' => $dps_user,
282 'PxPayKey' => $dps_key,
283 'Response' => $_GET['result'],
285 $processResponse = CRM_Core_Payment_PaymentExpressUtils
::_valueXml('ProcessResponse', $processResponse);
287 fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
291 // Send the XML-formatted validation request to DPS so that we can receive a decrypted XML response which contains the transaction results
292 $curl = CRM_Core_Payment_PaymentExpressUtils
::_initCURL($processResponse, $dps_url);
294 fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
298 if ($response = curl_exec($curl)) {
299 fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
304 // Assign the returned XML values to variables
305 $valid = CRM_Core_Payment_PaymentExpressUtils
::_xmlAttribute($response, 'valid');
306 $success = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, 'Success');
307 $txnId = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, 'TxnId');
308 $responseText = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, 'ResponseText');
309 $authCode = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, 'AuthCode');
310 $DPStxnRef = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, 'DpsTxnRef');
311 $qfKey = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, "TxnData1");
312 $privateData = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, "TxnData2");
313 list($component,$paymentProcessorID,) =explode(',', CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, "TxnData3"));
314 $amount = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, "AmountSettlement");
315 $merchantReference = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, "MerchantReference");
318 // calling DPS failed
319 CRM_Core_Error
::fatal(ts('Unable to establish connection to the payment gateway to verify transaction response.'));
323 elseif ($dps_method == "pxaccess") {
325 require_once ('PaymentExpress/pxaccess.inc.php');
327 $pxaccess = new PxAccess($dps_url, $dps_user, $dps_key, $mac_key);
328 #getResponse method in PxAccess object returns PxPayResponse object
329 #which encapsulates all the response data
330 $rsp = $pxaccess->getResponse($rawPostData);
332 $qfKey = $rsp->getTxnData1();
333 $privateData = $rsp->getTxnData2();
334 list($component,$paymentProcessorID) = explode(',',$rsp->getTxnData3());
335 $success = $rsp->getSuccess();
336 $authCode = $rsp->getAuthCode();
337 $DPStxnRef = $rsp->getDpsTxnRef();
338 $amount = $rsp->getAmountSettlement();
339 $MerchantReference = $rsp->getMerchantReference();
342 $privateData = $privateData ? self
::stringToArray($privateData) : '';
344 // Record the current count in array, before we start adding things (for later checks)
345 $countPrivateData = count($privateData);
347 // Private Data consists of : a=contactID, b=contributionID,c=contributionTypeID,d=invoiceID,e=membershipID,f=participantID,g=eventID
348 $privateData['contactID'] = $privateData['a'];
349 $privateData['contributionID'] = $privateData['b'];
350 $privateData['contributionTypeID'] = $privateData['c'];
351 $privateData['invoiceID'] = $privateData['d'];
353 if ($component == "event") {
354 $privateData['participantID'] = $privateData['f'];
355 $privateData['eventID'] = $privateData['g'];
357 elseif ($component == "contribute") {
359 if ($countPrivateData == 5) {
360 $privateData["membershipID"] = $privateData['e'];
364 $transactionReference = $authCode . "-" . $DPStxnRef;
366 list($mode, $component, $duplicateTransaction) = self
::getContext($privateData, $transactionReference);
367 $mode = $mode ?
'test' : 'live';
370 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
374 $ipn = self
::singleton($mode, $component, $paymentProcessor);
377 //Check status and take appropriate action
380 if ($duplicateTransaction == 0) {
381 $ipn->newOrderNotify($success, $privateData, $component, $amount, $transactionReference);
384 if ($component == "event") {
385 $finalURL = CRM_Utils_System
::url('civicrm/event/register',
386 "_qf_ThankYou_display=1&qfKey=$qfKey",
390 elseif ($component == "contribute") {
391 $finalURL = CRM_Utils_System
::url('civicrm/contribute/transact',
392 "_qf_ThankYou_display=1&qfKey=$qfKey",
397 CRM_Utils_System
::redirect($finalURL);
401 if ($component == "event") {
402 $finalURL = CRM_Utils_System
::url('civicrm/event/confirm',
403 "reset=1&cc=fail&participantId=$privateData[participantID]",
407 elseif ($component == "contribute") {
408 $finalURL = CRM_Utils_System
::url('civicrm/contribute/transact',
409 "_qf_Main_display=1&cancel=1&qfKey=$qfKey",
414 CRM_Utils_System
::redirect($finalURL);
419 * Converts the comma separated name-value pairs in <TxnData2>
420 * to an array of values.
422 static function stringToArray($str) {
423 $vars = $labels = array();
424 $labels = explode(',', $str);
425 foreach ($labels as $label) {
426 $terms = explode('=', $label);
427 $vars[$terms[0]] = $terms[1];