Merge pull request #4635 from colemanw/comments
[civicrm-core.git] / CRM / Core / Payment / Moneris.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 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 static function &singleton($mode, &$paymentProcessor) {
92 $processorName = $paymentProcessor['name'];
93 if (self::$_singleton[$processorName] === NULL) {
94 self::$_singleton[$processorName] = new CRM_Core_Payment_Moneris($mode, $paymentProcessor);
95 }
96 return self::$_singleton[$processorName];
97 }
98
99 /**
100 * This function collects all the information from a web/api form and invokes
101 * the relevant payment processor specific functions to perform the transaction
102 *
103 * @param array $params assoc array of input parameters for this transaction
104 *
105 * @return array the result in an nice formatted array (or an error object)
106 * @abstract
107 */
108 function doDirectPayment(&$params) {
109 //make sure i've been called correctly ...
110 if (!$this->_profile) {
111 return self::error('Unexpected error, missing profile');
112 }
113 if ($params['currencyID'] != 'CAD') {
114 return self::error('Invalid currency selection, must be $CAD');
115 }
116 /* unused params: cvv not yet implemented, payment action ingored (should test for 'Sale' value?)
117 [cvv2] => 000
118 [ip_address] => 192.168.0.103
119 [payment_action] => Sale
120 [contact_type] => Individual
121 [geo_coord_id] => 1 */
122
123 //this code based on Moneris example code #
124 //create an mpgCustInfo object
125 $mpgCustInfo = new mpgCustInfo();
126 //call set methods of the mpgCustinfo object
127 $mpgCustInfo->setEmail($params['email']);
128 //get text representations of province/country to send to moneris for billing info
129
130 $billing = array(
131 'first_name' => $params['first_name'],
132 'last_name' => $params['last_name'],
133 'address' => $params['street_address'],
134 'city' => $params['city'],
135 'province' => $params['state_province'],
136 'postal_code' => $params['postal_code'],
137 'country' => $params['country'],
138 );
139 $mpgCustInfo->setBilling($billing);
140 // set orderid as invoiceID to help match things up with Moneris later
141 $my_orderid = $params['invoiceID'];
142 $expiry_string = sprintf('%04d%02d', $params['year'], $params['month']);
143
144 $txnArray = array(
145 'type' => 'purchase',
146 'order_id' => $my_orderid,
147 'amount' => sprintf('%01.2f', $params['amount']),
148 'pan' => $params['credit_card_number'],
149 'expdate' => substr($expiry_string, 2, 4),
150 'crypt_type' => '7',
151 'cust_id' => $params['contactID'],
152 );
153
154 // Allow further manipulation of params via custom hooks
155 CRM_Utils_Hook::alterPaymentProcessorParams($this, $params, $txnArray);
156
157 //create a transaction object passing the hash created above
158 $mpgTxn = new mpgTransaction($txnArray);
159
160 //use the setCustInfo method of mpgTransaction object to
161 //set the customer info (level 3 data) for this transaction
162 $mpgTxn->setCustInfo($mpgCustInfo);
163 // add a recurring payment if requested
164 if ($params['is_recur'] && $params['installments'] > 1) {
165 //Recur Variables
166 $recurUnit = $params['frequency_unit'];
167 $recurInterval = $params['frequency_interval'];
168 $next = time();
169 $day = 60 * 60 * 24;
170 switch ($recurUnit) {
171 case 'day':
172 $next += $recurInterval * $day;
173 break;
174
175 case 'week':
176 $next += $recurInterval * $day * 7;
177 break;
178
179 case 'month':
180 $date = getdate();
181 $date['mon'] += $recurInterval;
182 while ($date['mon'] > 12) {
183 $date['mon'] -= 12;
184 $date['year'] += 1;
185 }
186 $next = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
187 break;
188
189 case 'year':
190 $date = getdate();
191 $date['year'] += 1;
192 $next = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
193 break;
194
195 default:
196 die('Unexpected error!');
197 }
198 // next payment in moneris required format
199 $startDate = date("Y/m/d", $next);
200 $numRecurs = $params['installments'] - 1;
201 //$startNow = 'true'; -- setting start now to false will mean the main transaction doesn't happen!
202 $recurAmount = sprintf('%01.2f', $params['amount']);
203 //Create an array with the recur variables
204 // (day | week | month)
205 $recurArray = array(
206 'recur_unit' => $recurUnit,
207 // yyyy/mm/dd
208 'start_date' => $startDate,
209 'num_recurs' => $numRecurs,
210 'start_now' => 'true',
211 'period' => $recurInterval,
212 'recur_amount' => $recurAmount,
213 );
214 $mpgRecur = new mpgRecur($recurArray);
215 // set the Recur Object to mpgRecur
216 $mpgTxn->setRecur($mpgRecur);
217 }
218 //create a mpgRequest object passing the transaction object
219 $mpgRequest = new mpgRequest($mpgTxn);
220
221 // create mpgHttpsPost object which does an https post ##
222 // [extra parameter added to library by AD]
223 $isProduction = ($this->_profile['mode'] == 'live');
224 $mpgHttpPost = new mpgHttpsPost($this->_profile['storeid'], $this->_profile['apitoken'], $mpgRequest, $isProduction);
225 // get an mpgResponse object
226 $mpgResponse = $mpgHttpPost->getMpgResponse();
227 $params['trxn_result_code'] = $mpgResponse->getResponseCode();
228 if (self::isError($mpgResponse)) {
229 if ($params['trxn_result_code']) {
230 return self::error($mpgResponse);
231 }
232 else {
233 return self::error('No reply from server - check your settings &/or try again');
234 }
235 }
236 /* Check for application errors */
237
238 $result = self::checkResult($mpgResponse);
239 if (is_a($result, 'CRM_Core_Error')) {
240 return $result;
241 }
242
243 /* Success */
244
245 $params['trxn_result_code'] = (integer) $mpgResponse->getResponseCode();
246 // todo: above assignment seems to be ignored, not getting stored in the civicrm_financial_trxn table
247 $params['trxn_id'] = $mpgResponse->getTxnNumber();
248 $params['gross_amount'] = $mpgResponse->getTransAmount();
249 return $params;
250 }
251
252 /**
253 * @param $response
254 *
255 * @return bool
256 */
257 function isError(&$response) {
258 $responseCode = $response->getResponseCode();
259 if (is_null($responseCode)) {
260 return TRUE;
261 }
262 if ('null' == $responseCode) {
263 return TRUE;
264 }
265 if (($responseCode >= 0) && ($responseCode < 50)) {
266 return FALSE;
267 }
268 return TRUE;
269 }
270
271 // ignore for now, more elaborate error handling later.
272 /**
273 * @param $response
274 *
275 * @return object
276 */
277 function &checkResult(&$response) {
278 return $response;
279
280 $errors = $response->getErrors();
281 if (empty($errors)) {
282 return $result;
283 }
284
285 $e = CRM_Core_Error::singleton();
286 if (is_a($errors, 'ErrorType')) {
287 $e->push($errors->getErrorCode(),
288 0, NULL,
289 $errors->getShortMessage() . ' ' . $errors->getLongMessage()
290 );
291 }
292 else {
293 foreach ($errors as $error) {
294 $e->push($error->getErrorCode(),
295 0, NULL,
296 $error->getShortMessage() . ' ' . $error->getLongMessage()
297 );
298 }
299 }
300 return $e;
301 }
302
303 /**
304 * @param null $error
305 *
306 * @return object
307 */
308 function &error($error = NULL) {
309 $e = CRM_Core_Error::singleton();
310 if (is_object($error)) {
311 $e->push($error->getResponseCode(),
312 0, NULL,
313 $error->getMessage()
314 );
315 }
316 elseif (is_string($error)) {
317 $e->push(9002,
318 0, NULL,
319 $error
320 );
321 }
322 else {
323 $e->push(9001, 0, NULL, "Unknown System Error.");
324 }
325 return $e;
326 }
327
328 /**
329 * This function checks to see if we have the right config values
330 *
331 * @return string the error message if any
332 * @public
333 */
334 function checkConfig() {
335 $error = array();
336
337 if (empty($this->_paymentProcessor['signature'])) {
338 $error[] = ts('Store ID is not set in the Administer CiviCRM &raquo; System Settings &raquo; Payment Processors.');
339 }
340
341 if (empty($this->_paymentProcessor['password'])) {
342 $error[] = ts('Password is not set in the Administer CiviCRM &raquo; System Settings &raquo; Payment Processors.');
343 }
344
345 if (!empty($error)) {
346 return implode('<p>', $error);
347 }
348 else {
349 return NULL;
350 }
351 }
352 }
353