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