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