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;
53 * The mode of operation: live or test.
55 * @param $paymentProcessor
57 * @return \CRM_Core_Payment_Moneris
59 public function __construct($mode, &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
61 $this->_paymentProcessor
= $paymentProcessor;
62 $this->_processorName
= ts('Moneris');
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.'));
69 // get merchant data from config
70 $config = CRM_Core_Config
::singleton();
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
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
86 * @param array $params
87 * Assoc array of input parameters for this transaction.
90 * the result in an nice formatted array (or an error object)
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');
98 if ($params['currencyID'] != 'CAD') {
99 return self
::error('Invalid currency selection, must be $CAD');
101 /* unused params: cvv not yet implemented, payment action ingored (should test for 'Sale' value?)
103 [ip_address] => 192.168.0.103
104 [payment_action] => Sale
105 [contact_type] => Individual
106 [geo_coord_id] => 1 */
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
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'],
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']);
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),
136 'cust_id' => $params['contactID'],
139 // Allow further manipulation of params via custom hooks
140 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $txnArray);
142 //create a transaction object passing the hash created above
143 $mpgTxn = new mpgTransaction($txnArray);
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) {
151 $recurUnit = $params['frequency_unit'];
152 $recurInterval = $params['frequency_interval'];
155 switch ($recurUnit) {
157 $next +
= $recurInterval * $day;
161 $next +
= $recurInterval * $day * 7;
166 $date['mon'] +
= $recurInterval;
167 while ($date['mon'] > 12) {
171 $next = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
177 $next = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
181 die('Unexpected error!');
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)
191 'recur_unit' => $recurUnit,
193 'start_date' => $startDate,
194 'num_recurs' => $numRecurs,
195 'start_now' => 'true',
196 'period' => $recurInterval,
197 'recur_amount' => $recurAmount,
199 $mpgRecur = new mpgRecur($recurArray);
200 // set the Recur Object to mpgRecur
201 $mpgTxn->setRecur($mpgRecur);
203 //create a mpgRequest object passing the transaction object
204 $mpgRequest = new mpgRequest($mpgTxn);
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);
218 return self
::error('No reply from server - check your settings &/or try again');
221 /* Check for application errors */
223 $result = self
::checkResult($mpgResponse);
224 if (is_a($result, 'CRM_Core_Error')) {
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();
242 public function isError(&$response) {
243 $responseCode = $response->getResponseCode();
244 if (is_null($responseCode)) {
247 if ('null' == $responseCode) {
250 if (($responseCode >= 0) && ($responseCode < 50)) {
256 // ignore for now, more elaborate error handling later.
262 public function &checkResult(&$response) {
265 $errors = $response->getErrors();
266 if (empty($errors)) {
270 $e = CRM_Core_Error
::singleton();
271 if (is_a($errors, 'ErrorType')) {
272 $e->push($errors->getErrorCode(),
274 $errors->getShortMessage() . ' ' . $errors->getLongMessage()
278 foreach ($errors as $error) {
279 $e->push($error->getErrorCode(),
281 $error->getShortMessage() . ' ' . $error->getLongMessage()
293 public function &error($error = NULL) {
294 $e = CRM_Core_Error
::singleton();
295 if (is_object($error)) {
296 $e->push($error->getResponseCode(),
301 elseif (is_string($error)) {
308 $e->push(9001, 0, NULL, "Unknown System Error.");
314 * This function checks to see if we have the right config values
317 * the error message if any
319 public function checkConfig() {
322 if (empty($this->_paymentProcessor
['signature'])) {
323 $error[] = ts('Store ID is not set in the Administer CiviCRM » System Settings » Payment Processors.');
326 if (empty($this->_paymentProcessor
['password'])) {
327 $error[] = ts('Password is not set in the Administer CiviCRM » System Settings » Payment Processors.');
330 if (!empty($error)) {
331 return implode('<p>', $error);