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