3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
37 * Class CRM_Core_Payment_PaymentExpressIPN
39 class CRM_Core_Payment_PaymentExpressIPN
extends CRM_Core_Payment_BaseIPN
{
42 * We only need one instance of this object. So we use the singleton
43 * pattern and cache the instance in this variable
48 static private $_singleton = NULL;
51 * Mode of operation: live or test
55 protected $_mode = NULL;
65 public static function retrieve($name, $type, $object, $abort = TRUE) {
66 $value = CRM_Utils_Array
::value($name, $object);
67 if ($abort && $value === NULL) {
68 CRM_Core_Error
::debug_log_message("Could not find an entry for $name");
69 echo "Failure: Missing Parameter - " . $name . "<p>";
74 if (!CRM_Utils_Type
::validate($value, $type)) {
75 CRM_Core_Error
::debug_log_message("Could not find a valid entry for $name");
76 echo "Failure: Invalid Parameter<p>";
88 * The mode of operation: live or test.
90 * @param $paymentProcessor
92 * @return \CRM_Core_Payment_PaymentExpressIPN
94 public function __construct($mode, &$paymentProcessor) {
95 parent
::__construct();
98 $this->_paymentProcessor
= $paymentProcessor;
102 * The function gets called when a new order takes place.
105 * @param array $privateData
106 * Contains the name value pair of <merchant-private-data>.
110 * @param $transactionReference
112 * @internal param \xml $dataRoot response send by google in xml format
115 public function newOrderNotify($success, $privateData, $component, $amount, $transactionReference) {
116 $ids = $input = $params = array();
118 $input['component'] = strtolower($component);
120 $ids['contact'] = self
::retrieve('contactID', 'Integer', $privateData, TRUE);
121 $ids['contribution'] = self
::retrieve('contributionID', 'Integer', $privateData, TRUE);
123 if ($input['component'] == "event") {
124 $ids['event'] = self
::retrieve('eventID', 'Integer', $privateData, TRUE);
125 $ids['participant'] = self
::retrieve('participantID', 'Integer', $privateData, TRUE);
126 $ids['membership'] = NULL;
129 $ids['membership'] = self
::retrieve('membershipID', 'Integer', $privateData, FALSE);
131 $ids['contributionRecur'] = $ids['contributionPage'] = NULL;
133 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
134 'PayPal_Express', 'id', 'name'
137 if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
141 // make sure the invoice is valid and matches what we have in the contribution record
142 $input['invoice'] = $privateData['invoiceID'];
143 $input['newInvoice'] = $transactionReference;
144 $contribution = &$objects['contribution'];
145 $input['trxn_id'] = $transactionReference;
147 if ($contribution->invoice_id
!= $input['invoice']) {
148 CRM_Core_Error
::debug_log_message("Invoice values dont match between database and IPN request");
149 echo "Failure: Invoice values dont match between database and IPN request<p>";
153 // lets replace invoice-id with Payment Processor -number because thats what is common and unique
154 // in subsequent calls or notifications sent by google.
155 $contribution->invoice_id
= $input['newInvoice'];
157 $input['amount'] = $amount;
159 if ($contribution->total_amount
!= $input['amount']) {
160 CRM_Core_Error
::debug_log_message("Amount values dont match between database and IPN request");
161 echo "Failure: Amount values dont match between database and IPN request. " . $contribution->total_amount
. "/" . $input['amount'] . "<p>";
165 $transaction = new CRM_Core_Transaction();
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
196 * Contains the name-value pairs of transaction related data.
197 * @param int $orderNo
198 * <order-total> send by google.
201 * context of this call (test, component, payment processor id)
204 public static function getContext($privateData, $orderNo) {
209 $contributionID = $privateData['contributionID'];
210 $contribution = new CRM_Contribute_DAO_Contribution();
211 $contribution->id
= $contributionID;
213 if (!$contribution->find(TRUE)) {
214 CRM_Core_Error
::debug_log_message("Could not find contribution record: $contributionID");
215 echo "Failure: Could not find contribution record for $contributionID<p>";
219 if (stristr($contribution->source
, 'Online Contribution')) {
220 $component = 'contribute';
222 elseif (stristr($contribution->source
, 'Online Event Registration')) {
223 $component = 'event';
225 $isTest = $contribution->is_test
;
227 $duplicateTransaction = 0;
228 if ($contribution->contribution_status_id
== 1) {
229 //contribution already handled. (some processors do two notifications so this could be valid)
230 $duplicateTransaction = 1;
233 if ($component == 'contribute') {
234 if (!$contribution->contribution_page_id
) {
235 CRM_Core_Error
::debug_log_message("Could not find contribution page for contribution record: $contributionID");
236 echo "Failure: Could not find contribution page for contribution record: $contributionID<p>";
242 $eventID = $privateData['eventID'];
245 CRM_Core_Error
::debug_log_message("Could not find event ID");
246 echo "Failure: Could not find eventID<p>";
250 // we are in event mode
251 // make sure event exists and is valid
252 $event = new CRM_Event_DAO_Event();
253 $event->id
= $eventID;
254 if (!$event->find(TRUE)) {
255 CRM_Core_Error
::debug_log_message("Could not find event: $eventID");
256 echo "Failure: Could not find event: $eventID<p>";
261 return array($isTest, $component, $duplicateTransaction);
265 * This method is handles the response that will be invoked by the
266 * notification or request sent by the payment processor.
267 * hex string from paymentexpress is passed to this function as hex string. Code based on googleIPN
268 * mac_key is only passed if the processor is pxaccess as it is used for decryption
269 * $dps_method is either pxaccess or pxpay
271 public static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps_key, $mac_key) {
273 $config = CRM_Core_Config
::singleton();
274 define('RESPONSE_HANDLER_LOG_FILE', $config->uploadDir
. 'CiviCRM.PaymentExpress.log');
277 if (!$message_log = fopen(RESPONSE_HANDLER_LOG_FILE
, "a")) {
278 error_func("Cannot open " . RESPONSE_HANDLER_LOG_FILE
. " file.\n", 0);
282 if ($dps_method == "pxpay") {
283 $processResponse = CRM_Core_Payment_PaymentExpressUtils
::_valueXml(array(
284 'PxPayUserId' => $dps_user,
285 'PxPayKey' => $dps_key,
286 'Response' => $_GET['result'],
288 $processResponse = CRM_Core_Payment_PaymentExpressUtils
::_valueXml('ProcessResponse', $processResponse);
290 fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
294 // Send the XML-formatted validation request to DPS so that we can receive a decrypted XML response which contains the transaction results
295 $curl = CRM_Core_Payment_PaymentExpressUtils
::_initCURL($processResponse, $dps_url);
297 fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
301 if ($response = curl_exec($curl)) {
302 fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"),
307 // Assign the returned XML values to variables
308 $valid = CRM_Core_Payment_PaymentExpressUtils
::_xmlAttribute($response, 'valid');
309 $success = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, 'Success');
310 $txnId = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, 'TxnId');
311 $responseText = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, 'ResponseText');
312 $authCode = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, 'AuthCode');
313 $DPStxnRef = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, 'DpsTxnRef');
314 $qfKey = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, "TxnData1");
315 $privateData = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, "TxnData2");
316 list($component, $paymentProcessorID,) = explode(',', CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, "TxnData3"));
317 $amount = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, "AmountSettlement");
318 $merchantReference = CRM_Core_Payment_PaymentExpressUtils
::_xmlElement($response, "MerchantReference");
321 // calling DPS failed
322 CRM_Core_Error
::fatal(ts('Unable to establish connection to the payment gateway to verify transaction response.'));
326 elseif ($dps_method == "pxaccess") {
328 require_once 'PaymentExpress/pxaccess.inc.php';
330 $pxaccess = new PxAccess($dps_url, $dps_user, $dps_key, $mac_key);
331 #getResponse method in PxAccess object returns PxPayResponse object
332 #which encapsulates all the response data
333 $rsp = $pxaccess->getResponse($rawPostData);
335 $qfKey = $rsp->getTxnData1();
336 $privateData = $rsp->getTxnData2();
337 list($component, $paymentProcessorID) = explode(',', $rsp->getTxnData3());
338 $success = $rsp->getSuccess();
339 $authCode = $rsp->getAuthCode();
340 $DPStxnRef = $rsp->getDpsTxnRef();
341 $amount = $rsp->getAmountSettlement();
342 $MerchantReference = $rsp->getMerchantReference();
345 $privateData = $privateData ? self
::stringToArray($privateData) : '';
347 // Record the current count in array, before we start adding things (for later checks)
348 $countPrivateData = count($privateData);
350 // Private Data consists of : a=contactID, b=contributionID,c=contributionTypeID,d=invoiceID,e=membershipID,f=participantID,g=eventID
351 $privateData['contactID'] = $privateData['a'];
352 $privateData['contributionID'] = $privateData['b'];
353 $privateData['contributionTypeID'] = $privateData['c'];
354 $privateData['invoiceID'] = $privateData['d'];
356 if ($component == "event") {
357 $privateData['participantID'] = $privateData['f'];
358 $privateData['eventID'] = $privateData['g'];
360 elseif ($component == "contribute") {
362 if ($countPrivateData == 5) {
363 $privateData["membershipID"] = $privateData['e'];
367 $transactionReference = $authCode . "-" . $DPStxnRef;
369 list($mode, $component, $duplicateTransaction) = self
::getContext($privateData, $transactionReference);
370 $mode = $mode ?
'test' : 'live';
372 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
376 $ipn = self
::singleton($mode, $component, $paymentProcessor);
378 //Check status and take appropriate action
381 if ($duplicateTransaction == 0) {
382 $ipn->newOrderNotify($success, $privateData, $component, $amount, $transactionReference);
385 if ($component == "event") {
386 $finalURL = CRM_Utils_System
::url('civicrm/event/register',
387 "_qf_ThankYou_display=1&qfKey=$qfKey",
391 elseif ($component == "contribute") {
392 $finalURL = CRM_Utils_System
::url('civicrm/contribute/transact',
393 "_qf_ThankYou_display=1&qfKey=$qfKey",
398 CRM_Utils_System
::redirect($finalURL);
402 if ($component == "event") {
403 $finalURL = CRM_Utils_System
::url('civicrm/event/confirm',
404 "reset=1&cc=fail&participantId=$privateData[participantID]",
408 elseif ($component == "contribute") {
409 $finalURL = CRM_Utils_System
::url('civicrm/contribute/transact',
410 "_qf_Main_display=1&cancel=1&qfKey=$qfKey",
415 CRM_Utils_System
::redirect($finalURL);
420 * Converts the comma separated name-value pairs in <TxnData2>
421 * to an array of values.
423 public static function stringToArray($str) {
424 $vars = $labels = array();
425 $labels = explode(',', $str);
426 foreach ($labels as $label) {
427 $terms = explode('=', $label);
428 $vars[$terms[0]] = $terms[1];