3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
32 * @copyright CiviCRM LLC (c) 2004-2014
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';
41 * We only need one instance of this object. So we use the singleton
42 * pattern and cache the instance in this variable
47 static private $_singleton = NULL;
52 * @param string $mode the mode of operation: live or test
54 * @param $paymentProcessor
56 * @return \CRM_Core_Payment_Moneris
58 public function __construct($mode, &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
60 $this->_paymentProcessor
= $paymentProcessor;
61 $this->_processorName
= ts('Moneris');
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.'));
68 // get merchant data from config
69 $config = CRM_Core_Config
::singleton();
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
82 * Singleton function used to manage this object
84 * @param string $mode the mode of operation: live or test
86 * @param object $paymentProcessor
91 public static function &singleton($mode, &$paymentProcessor) {
92 if (!empty($paymentProcessor['id'])) {
93 $cacheKey = $paymentProcessor['id'];
96 //@todo eliminated instances of this in favour of id-specific instances.
97 $cacheKey = $mode . '_' . $paymentProcessor['name'];
99 if (self
::$_singleton[$cacheKey] === NULL) {
100 self
::$_singleton[$cacheKey] = new CRM_Core_Payment_Moneris($mode, $paymentProcessor);
102 return self
::$_singleton[$cacheKey];
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
109 * @param array $params assoc array of input parameters for this transaction
111 * @return array the result in an nice formatted array (or an error object)
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');
119 if ($params['currencyID'] != 'CAD') {
120 return self
::error('Invalid currency selection, must be $CAD');
122 /* unused params: cvv not yet implemented, payment action ingored (should test for 'Sale' value?)
124 [ip_address] => 192.168.0.103
125 [payment_action] => Sale
126 [contact_type] => Individual
127 [geo_coord_id] => 1 */
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
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'],
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']);
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),
157 'cust_id' => $params['contactID'],
160 // Allow further manipulation of params via custom hooks
161 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $txnArray);
163 //create a transaction object passing the hash created above
164 $mpgTxn = new mpgTransaction($txnArray);
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) {
172 $recurUnit = $params['frequency_unit'];
173 $recurInterval = $params['frequency_interval'];
176 switch ($recurUnit) {
178 $next +
= $recurInterval * $day;
182 $next +
= $recurInterval * $day * 7;
187 $date['mon'] +
= $recurInterval;
188 while ($date['mon'] > 12) {
192 $next = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
198 $next = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
202 die('Unexpected error!');
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)
212 'recur_unit' => $recurUnit,
214 'start_date' => $startDate,
215 'num_recurs' => $numRecurs,
216 'start_now' => 'true',
217 'period' => $recurInterval,
218 'recur_amount' => $recurAmount,
220 $mpgRecur = new mpgRecur($recurArray);
221 // set the Recur Object to mpgRecur
222 $mpgTxn->setRecur($mpgRecur);
224 //create a mpgRequest object passing the transaction object
225 $mpgRequest = new mpgRequest($mpgTxn);
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);
239 return self
::error('No reply from server - check your settings &/or try again');
242 /* Check for application errors */
244 $result = self
::checkResult($mpgResponse);
245 if (is_a($result, 'CRM_Core_Error')) {
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();
263 public function isError(&$response) {
264 $responseCode = $response->getResponseCode();
265 if (is_null($responseCode)) {
268 if ('null' == $responseCode) {
271 if (($responseCode >= 0) && ($responseCode < 50)) {
277 // ignore for now, more elaborate error handling later.
283 public function &checkResult(&$response) {
286 $errors = $response->getErrors();
287 if (empty($errors)) {
291 $e = CRM_Core_Error
::singleton();
292 if (is_a($errors, 'ErrorType')) {
293 $e->push($errors->getErrorCode(),
295 $errors->getShortMessage() . ' ' . $errors->getLongMessage()
299 foreach ($errors as $error) {
300 $e->push($error->getErrorCode(),
302 $error->getShortMessage() . ' ' . $error->getLongMessage()
314 public function &error($error = NULL) {
315 $e = CRM_Core_Error
::singleton();
316 if (is_object($error)) {
317 $e->push($error->getResponseCode(),
322 elseif (is_string($error)) {
329 $e->push(9001, 0, NULL, "Unknown System Error.");
335 * This function checks to see if we have the right config values
337 * @return string the error message if any
339 public function checkConfig() {
342 if (empty($this->_paymentProcessor
['signature'])) {
343 $error[] = ts('Store ID is not set in the Administer CiviCRM » System Settings » Payment Processors.');
346 if (empty($this->_paymentProcessor
['password'])) {
347 $error[] = ts('Password is not set in the Administer CiviCRM » System Settings » Payment Processors.');
350 if (!empty($error)) {
351 return implode('<p>', $error);