Merge pull request #4859 from eileenmcnaughton/CRM-15771-fix
[civicrm-core.git] / CRM / Core / Payment / Moneris.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @author Alan Dixon
32 * @copyright CiviCRM LLC (c) 2004-2014
33 * $Id$
34 *
35 */
36 class CRM_Core_Payment_Moneris extends CRM_Core_Payment {
37 # (not used, implicit in the API, might need to convert?)
38 const CHARSET = 'UFT-8';
39
40 /**
41 * We only need one instance of this object. So we use the singleton
42 * pattern and cache the instance in this variable
43 *
44 * @var object
45 * @static
46 */
47 static private $_singleton = NULL;
48
49 /**
50 * Constructor
51 *
52 * @param string $mode the mode of operation: live or test
53 *
54 * @param $paymentProcessor
55 *
56 * @return \CRM_Core_Payment_Moneris
57 */
58 public function __construct($mode, &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
59 $this->_mode = $mode;
60 $this->_paymentProcessor = $paymentProcessor;
61 $this->_processorName = ts('Moneris');
62
63 // require moneris supplied api library
64 if ((include_once 'Services/mpgClasses.php') === FALSE) {
65 CRM_Core_Error::fatal(ts('Please download and put the Moneris mpgClasses.php file in packages/Services directory to enable Moneris Support.'));
66 }
67
68 // get merchant data from config
69 $config = CRM_Core_Config::singleton();
70 // live or test
71 $this->_profile['mode'] = $mode;
72 $this->_profile['storeid'] = $this->_paymentProcessor['signature'];
73 $this->_profile['apitoken'] = $this->_paymentProcessor['password'];
74 $currencyID = $config->defaultCurrency;
75 if ('CAD' != $currencyID) {
76 return self::error('Invalid configuration:' . $currencyID . ', you must use currency $CAD with Moneris');
77 // Configuration error: default currency must be CAD
78 }
79 }
80
81 /**
82 * Singleton function used to manage this object
83 *
84 * @param string $mode the mode of operation: live or test
85 *
86 * @param object $paymentProcessor
87 *
88 * @return object
89 * @static
90 */
91 public static function &singleton($mode, &$paymentProcessor) {
92 if (!empty($paymentProcessor['id'])) {
93 $cacheKey = $paymentProcessor['id'];
94 }
95 else {
96 //@todo eliminated instances of this in favour of id-specific instances.
97 $cacheKey = $mode . '_' . $paymentProcessor['name'];
98 }
99 if (self::$_singleton[$cacheKey] === NULL) {
100 self::$_singleton[$cacheKey] = new CRM_Core_Payment_Moneris($mode, $paymentProcessor);
101 }
102 return self::$_singleton[$cacheKey];
103 }
104
105 /**
106 * This function collects all the information from a web/api form and invokes
107 * the relevant payment processor specific functions to perform the transaction
108 *
109 * @param array $params assoc array of input parameters for this transaction
110 *
111 * @return array the result in an nice formatted array (or an error object)
112 * @abstract
113 */
114 public function doDirectPayment(&$params) {
115 //make sure i've been called correctly ...
116 if (!$this->_profile) {
117 return self::error('Unexpected error, missing profile');
118 }
119 if ($params['currencyID'] != 'CAD') {
120 return self::error('Invalid currency selection, must be $CAD');
121 }
122 /* unused params: cvv not yet implemented, payment action ingored (should test for 'Sale' value?)
123 [cvv2] => 000
124 [ip_address] => 192.168.0.103
125 [payment_action] => Sale
126 [contact_type] => Individual
127 [geo_coord_id] => 1 */
128
129 //this code based on Moneris example code #
130 //create an mpgCustInfo object
131 $mpgCustInfo = new mpgCustInfo();
132 //call set methods of the mpgCustinfo object
133 $mpgCustInfo->setEmail($params['email']);
134 //get text representations of province/country to send to moneris for billing info
135
136 $billing = array(
137 'first_name' => $params['first_name'],
138 'last_name' => $params['last_name'],
139 'address' => $params['street_address'],
140 'city' => $params['city'],
141 'province' => $params['state_province'],
142 'postal_code' => $params['postal_code'],
143 'country' => $params['country'],
144 );
145 $mpgCustInfo->setBilling($billing);
146 // set orderid as invoiceID to help match things up with Moneris later
147 $my_orderid = $params['invoiceID'];
148 $expiry_string = sprintf('%04d%02d', $params['year'], $params['month']);
149
150 $txnArray = array(
151 'type' => 'purchase',
152 'order_id' => $my_orderid,
153 'amount' => sprintf('%01.2f', $params['amount']),
154 'pan' => $params['credit_card_number'],
155 'expdate' => substr($expiry_string, 2, 4),
156 'crypt_type' => '7',
157 'cust_id' => $params['contactID'],
158 );
159
160 // Allow further manipulation of params via custom hooks
161 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $txnArray);
162
163 //create a transaction object passing the hash created above
164 $mpgTxn = new mpgTransaction($txnArray);
165
166 //use the setCustInfo method of mpgTransaction object to
167 //set the customer info (level 3 data) for this transaction
168 $mpgTxn->setCustInfo($mpgCustInfo);
169 // add a recurring payment if requested
170 if ($params['is_recur'] && $params['installments'] > 1) {
171 //Recur Variables
172 $recurUnit = $params['frequency_unit'];
173 $recurInterval = $params['frequency_interval'];
174 $next = time();
175 $day = 60 * 60 * 24;
176 switch ($recurUnit) {
177 case 'day':
178 $next += $recurInterval * $day;
179 break;
180
181 case 'week':
182 $next += $recurInterval * $day * 7;
183 break;
184
185 case 'month':
186 $date = getdate();
187 $date['mon'] += $recurInterval;
188 while ($date['mon'] > 12) {
189 $date['mon'] -= 12;
190 $date['year'] += 1;
191 }
192 $next = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
193 break;
194
195 case 'year':
196 $date = getdate();
197 $date['year'] += 1;
198 $next = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
199 break;
200
201 default:
202 die('Unexpected error!');
203 }
204 // next payment in moneris required format
205 $startDate = date("Y/m/d", $next);
206 $numRecurs = $params['installments'] - 1;
207 //$startNow = 'true'; -- setting start now to false will mean the main transaction doesn't happen!
208 $recurAmount = sprintf('%01.2f', $params['amount']);
209 //Create an array with the recur variables
210 // (day | week | month)
211 $recurArray = array(
212 'recur_unit' => $recurUnit,
213 // yyyy/mm/dd
214 'start_date' => $startDate,
215 'num_recurs' => $numRecurs,
216 'start_now' => 'true',
217 'period' => $recurInterval,
218 'recur_amount' => $recurAmount,
219 );
220 $mpgRecur = new mpgRecur($recurArray);
221 // set the Recur Object to mpgRecur
222 $mpgTxn->setRecur($mpgRecur);
223 }
224 //create a mpgRequest object passing the transaction object
225 $mpgRequest = new mpgRequest($mpgTxn);
226
227 // create mpgHttpsPost object which does an https post ##
228 // [extra parameter added to library by AD]
229 $isProduction = ($this->_profile['mode'] == 'live');
230 $mpgHttpPost = new mpgHttpsPost($this->_profile['storeid'], $this->_profile['apitoken'], $mpgRequest, $isProduction);
231 // get an mpgResponse object
232 $mpgResponse = $mpgHttpPost->getMpgResponse();
233 $params['trxn_result_code'] = $mpgResponse->getResponseCode();
234 if (self::isError($mpgResponse)) {
235 if ($params['trxn_result_code']) {
236 return self::error($mpgResponse);
237 }
238 else {
239 return self::error('No reply from server - check your settings &/or try again');
240 }
241 }
242 /* Check for application errors */
243
244 $result = self::checkResult($mpgResponse);
245 if (is_a($result, 'CRM_Core_Error')) {
246 return $result;
247 }
248
249 /* Success */
250
251 $params['trxn_result_code'] = (integer) $mpgResponse->getResponseCode();
252 // todo: above assignment seems to be ignored, not getting stored in the civicrm_financial_trxn table
253 $params['trxn_id'] = $mpgResponse->getTxnNumber();
254 $params['gross_amount'] = $mpgResponse->getTransAmount();
255 return $params;
256 }
257
258 /**
259 * @param $response
260 *
261 * @return bool
262 */
263 public function isError(&$response) {
264 $responseCode = $response->getResponseCode();
265 if (is_null($responseCode)) {
266 return TRUE;
267 }
268 if ('null' == $responseCode) {
269 return TRUE;
270 }
271 if (($responseCode >= 0) && ($responseCode < 50)) {
272 return FALSE;
273 }
274 return TRUE;
275 }
276
277 // ignore for now, more elaborate error handling later.
278 /**
279 * @param $response
280 *
281 * @return object
282 */
283 public function &checkResult(&$response) {
284 return $response;
285
286 $errors = $response->getErrors();
287 if (empty($errors)) {
288 return $result;
289 }
290
291 $e = CRM_Core_Error::singleton();
292 if (is_a($errors, 'ErrorType')) {
293 $e->push($errors->getErrorCode(),
294 0, NULL,
295 $errors->getShortMessage() . ' ' . $errors->getLongMessage()
296 );
297 }
298 else {
299 foreach ($errors as $error) {
300 $e->push($error->getErrorCode(),
301 0, NULL,
302 $error->getShortMessage() . ' ' . $error->getLongMessage()
303 );
304 }
305 }
306 return $e;
307 }
308
309 /**
310 * @param null $error
311 *
312 * @return object
313 */
314 public function &error($error = NULL) {
315 $e = CRM_Core_Error::singleton();
316 if (is_object($error)) {
317 $e->push($error->getResponseCode(),
318 0, NULL,
319 $error->getMessage()
320 );
321 }
322 elseif (is_string($error)) {
323 $e->push(9002,
324 0, NULL,
325 $error
326 );
327 }
328 else {
329 $e->push(9001, 0, NULL, "Unknown System Error.");
330 }
331 return $e;
332 }
333
334 /**
335 * This function checks to see if we have the right config values
336 *
337 * @return string the error message if any
338 */
339 public function checkConfig() {
340 $error = array();
341
342 if (empty($this->_paymentProcessor['signature'])) {
343 $error[] = ts('Store ID is not set in the Administer CiviCRM &raquo; System Settings &raquo; Payment Processors.');
344 }
345
346 if (empty($this->_paymentProcessor['password'])) {
347 $error[] = ts('Password is not set in the Administer CiviCRM &raquo; System Settings &raquo; Payment Processors.');
348 }
349
350 if (!empty($error)) {
351 return implode('<p>', $error);
352 }
353 else {
354 return NULL;
355 }
356 }
357 }