CRM-15771 fix inconsistencies with test vs live instances by making key more complex
[civicrm-core.git] / CRM / Core / Payment / PaymentExpress.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_PaymentExpress
38 */
39 class CRM_Core_Payment_PaymentExpress extends CRM_Core_Payment {
40 const CHARSET = 'iso-8859-1';
41
42 protected $_mode = NULL;
43
44 /**
45 * We only need one instance of this object. So we use the singleton
46 * pattern and cache the instance in this variable
47 *
48 * @var object
49 * @static
50 */
51 static private $_singleton = NULL;
52
53 /**
54 * Constructor
55 *
56 * @param string $mode the mode of operation: live or test
57 *
58 * @param $paymentProcessor
59 *
60 * @return \CRM_Core_Payment_PaymentExpress
61 */
62 public function __construct($mode, &$paymentProcessor) {
63
64 $this->_mode = $mode;
65 $this->_paymentProcessor = $paymentProcessor;
66 $this->_processorName = ts('DPS Payment Express');
67 }
68
69 /**
70 * Singleton function used to manage this object
71 *
72 * @param string $mode the mode of operation: live or test
73 *
74 * @param object $paymentProcessor
75 * @param null $paymentForm
76 * @param bool $force
77 *
78 * @return object
79 * @static
80 */
81 public static function &singleton($mode = 'test', &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
82 if (!empty($paymentProcessor['id'])) {
83 $cacheKey = $paymentProcessor['id'];
84 }
85 else {
86 //@todo eliminated instances of this in favour of id-specific instances.
87 $cacheKey = $mode . '_' . $paymentProcessor['name'];
88 }
89 if (self::$_singleton[$cacheKey] === NULL) {
90 self::$_singleton[$cacheKey] = new CRM_Core_Payment_PaymentExpress($mode, $paymentProcessor);
91 }
92 return self::$_singleton[$cacheKey];
93 }
94
95 /**
96 * This function checks to see if we have the right config values
97 *
98 * @internal param string $mode the mode we are operating in (live or test)
99 *
100 * @return string the error message if any
101 */
102 public function checkConfig() {
103 $config = CRM_Core_Config::singleton();
104
105 $error = array();
106
107 if (empty($this->_paymentProcessor['user_name'])) {
108 $error[] = ts('UserID is not set in the Administer &raquo; System Settings &raquo; Payment Processors');
109 }
110
111 if (empty($this->_paymentProcessor['password'])) {
112 $error[] = ts('pxAccess / pxPay Key is not set in the Administer &raquo; System Settings &raquo; Payment Processors');
113 }
114
115 if (!empty($error)) {
116 return implode('<p>', $error);
117 }
118 else {
119 return NULL;
120 }
121 }
122
123 /**
124 * @param array $params
125 *
126 * @throws Exception
127 */
128 public function setExpressCheckOut(&$params) {
129 CRM_Core_Error::fatal(ts('This function is not implemented'));
130 }
131
132 /**
133 * @param $token
134 *
135 * @throws Exception
136 */
137 public function getExpressCheckoutDetails($token) {
138 CRM_Core_Error::fatal(ts('This function is not implemented'));
139 }
140
141 /**
142 * @param array $params
143 *
144 * @throws Exception
145 */
146 public function doExpressCheckout(&$params) {
147 CRM_Core_Error::fatal(ts('This function is not implemented'));
148 }
149
150 /**
151 * This function collects all the information from a web/api form and invokes
152 * the relevant payment processor specific functions to perform the transaction
153 *
154 * @param array $params assoc array of input parameters for this transaction
155 *
156 * @return array the result in an nice formatted array (or an error object)
157 * @abstract
158 */
159 public function doDirectPayment(&$params) {
160 CRM_Core_Error::fatal(ts('This function is not implemented'));
161 }
162
163 /**
164 * Main transaction function
165 *
166 * @param array $params name value pair of contribution data
167 *
168 * @param $component
169 *
170 * @return void
171 */
172 public function doTransferCheckout(&$params, $component) {
173 $component = strtolower($component);
174 $config = CRM_Core_Config::singleton();
175 if ($component != 'contribute' && $component != 'event') {
176 CRM_Core_Error::fatal(ts('Component is invalid'));
177 }
178
179 $url = $config->userFrameworkResourceURL . "extern/pxIPN.php";
180
181 if ($component == 'event') {
182 $cancelURL = CRM_Utils_System::url('civicrm/event/register',
183 "_qf_Confirm_display=true&qfKey={$params['qfKey']}",
184 FALSE, NULL, FALSE
185 );
186 }
187 elseif ($component == 'contribute') {
188 $cancelURL = CRM_Utils_System::url('civicrm/contribute/transact',
189 "_qf_Confirm_display=true&qfKey={$params['qfKey']}",
190 FALSE, NULL, FALSE
191 );
192 }
193
194
195 /*
196 * Build the private data string to pass to DPS, which they will give back to us with the
197 *
198 * transaction result. We are building this as a comma-separated list so as to avoid long URLs.
199 *
200 * Parameters passed: a=contactID, b=contributionID,c=contributionTypeID,d=invoiceID,e=membershipID,f=participantID,g=eventID
201 */
202
203 $privateData = "a={$params['contactID']},b={$params['contributionID']},c={$params['contributionTypeID']},d={$params['invoiceID']}";
204
205 if ($component == 'event') {
206 $merchantRef = substr($params['contactID'] . "-" . $params['contributionID'] . " " . substr($params['description'], 27, 20), 0, 24);
207 $privateData .= ",f={$params['participantID']},g={$params['eventID']}";
208 }
209 elseif ($component == 'contribute') {
210 $membershipID = CRM_Utils_Array::value('membershipID', $params);
211 if ($membershipID) {
212 $privateData .= ",e=$membershipID";
213 }
214 $merchantRef = substr($params['contactID'] . "-" . $params['contributionID'] . " " . substr($params['description'], 20, 20), 0, 24);
215
216 }
217
218 $dpsParams = array(
219 'AmountInput' => str_replace(",", "", number_format($params['amount'], 2)),
220 'CurrencyInput' => $params['currencyID'],
221 'MerchantReference' => $merchantRef,
222 'TxnData1' => $params['qfKey'],
223 'TxnData2' => $privateData,
224 'TxnData3' => $component . ",".$this->_paymentProcessor['id'],
225 'TxnType' => 'Purchase',
226 // Leave this empty for now, causes an error with DPS if we populate it
227 'TxnId' => '',
228 'UrlFail' => $url,
229 'UrlSuccess' => $url,
230 );
231 // Allow further manipulation of params via custom hooks
232 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $dpsParams);
233
234 /*
235 * determine whether method is pxaccess or pxpay by whether signature (mac key) is defined
236 */
237
238
239 if (empty($this->_paymentProcessor['signature'])) {
240 /*
241 * Processor is pxpay
242 *
243 * This contains the XML/Curl functions we'll need to generate the XML request
244 */
245
246 $dpsParams['PxPayUserId'] = $this->_paymentProcessor['user_name'];
247 $dpsParams['PxPayKey'] = $this->_paymentProcessor['password'];
248 // Build a valid XML string to pass to DPS
249 $generateRequest = CRM_Core_Payment_PaymentExpressUtils::_valueXml($dpsParams);
250
251 $generateRequest = CRM_Core_Payment_PaymentExpressUtils::_valueXml('GenerateRequest', $generateRequest);
252 // Get the special validated URL back from DPS by sending them the XML we've generated
253 $curl = CRM_Core_Payment_PaymentExpressUtils::_initCURL($generateRequest, $this->_paymentProcessor['url_site']);
254 $success = FALSE;
255
256 if ($response = curl_exec($curl)) {
257 curl_close($curl);
258 $valid = CRM_Core_Payment_PaymentExpressUtils::_xmlAttribute($response, 'valid');
259 if (1 == $valid) {
260 // the request was validated, so we'll get the URL and redirect to it
261 $uri = CRM_Core_Payment_PaymentExpressUtils::_xmlElement($response, 'URI');
262 CRM_Utils_System::redirect($uri);
263 }
264 else {
265 // redisplay confirmation page
266 CRM_Utils_System::redirect($cancelURL);
267 }
268 }
269 else {
270 // calling DPS failed
271 CRM_Core_Error::fatal(ts('Unable to establish connection to the payment gateway.'));
272 }
273 }
274 else {
275 $processortype = "pxaccess";
276 require_once ('PaymentExpress/pxaccess.inc.php');
277 // URL
278 $PxAccess_Url = $this->_paymentProcessor['url_site'];
279 // User ID
280 $PxAccess_Userid = $this->_paymentProcessor['user_name'];
281 // Your DES Key from DPS
282 $PxAccess_Key = $this->_paymentProcessor['password'];
283 // Your MAC key from DPS
284 $Mac_Key = $this->_paymentProcessor['signature'];
285
286 $pxaccess = new PxAccess($PxAccess_Url, $PxAccess_Userid, $PxAccess_Key, $Mac_Key);
287 $request = new PxPayRequest();
288 $request->setAmountInput($dpsParams['AmountInput']);
289 $request->setTxnData1($dpsParams['TxnData1']);
290 $request->setTxnData2($dpsParams['TxnData2']);
291 $request->setTxnData3($dpsParams['TxnData3']);
292 $request->setTxnType($dpsParams['TxnType']);
293 $request->setInputCurrency($dpsParams['InputCurrency']);
294 $request->setMerchantReference($dpsParams['MerchantReference']);
295 $request->setUrlFail($dpsParams['UrlFail']);
296 $request->setUrlSuccess($dpsParams['UrlSuccess']);
297 $request_string = $pxaccess->makeRequest($request);
298 CRM_Utils_System::redirect($request_string);
299 }
300 }
301 }