3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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
46 static private $_singleton = NULL;
52 * The mode of operation: live or test.
54 * @param $paymentProcessor
56 * @param null $paymentForm
61 public function __construct($mode, &$paymentProcessor, &$paymentForm = NULL, $force = FALSE) {
63 $this->_paymentProcessor
= $paymentProcessor;
64 $this->_processorName
= ts('Moneris');
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.'));
71 // get merchant data from config
72 $config = CRM_Core_Config
::singleton();
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
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
88 * @param array $params
89 * Assoc array of input parameters for this transaction.
92 * the result in an nice formatted array (or an error object)
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');
100 if ($params['currencyID'] != 'CAD') {
101 return self
::error('Invalid currency selection, must be $CAD');
103 /* unused params: cvv not yet implemented, payment action ingored (should test for 'Sale' value?)
105 [ip_address] => 192.168.0.103
106 [payment_action] => Sale
107 [contact_type] => Individual
108 [geo_coord_id] => 1 */
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
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'],
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']);
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),
138 'cust_id' => $params['contactID'],
141 // Allow further manipulation of params via custom hooks
142 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $txnArray);
144 //create a transaction object passing the hash created above
145 $mpgTxn = new mpgTransaction($txnArray);
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) {
153 $recurUnit = $params['frequency_unit'];
154 $recurInterval = $params['frequency_interval'];
157 switch ($recurUnit) {
159 $next +
= $recurInterval * $day;
163 $next +
= $recurInterval * $day * 7;
168 $date['mon'] +
= $recurInterval;
169 while ($date['mon'] > 12) {
173 $next = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
179 $next = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
183 die('Unexpected error!');
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)
193 'recur_unit' => $recurUnit,
195 'start_date' => $startDate,
196 'num_recurs' => $numRecurs,
197 'start_now' => 'true',
198 'period' => $recurInterval,
199 'recur_amount' => $recurAmount,
201 $mpgRecur = new mpgRecur($recurArray);
202 // set the Recur Object to mpgRecur
203 $mpgTxn->setRecur($mpgRecur);
205 //create a mpgRequest object passing the transaction object
206 $mpgRequest = new mpgRequest($mpgTxn);
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);
220 return self
::error('No reply from server - check your settings &/or try again');
223 /* Check for application errors */
225 $result = self
::checkResult($mpgResponse);
226 if (is_a($result, 'CRM_Core_Error')) {
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();
244 public function isError(&$response) {
245 $responseCode = $response->getResponseCode();
246 if (is_null($responseCode)) {
249 if ('null' == $responseCode) {
252 if (($responseCode >= 0) && ($responseCode < 50)) {
259 * ignore for now, more elaborate error handling later.
264 public function &checkResult(&$response) {
267 $errors = $response->getErrors();
268 if (empty($errors)) {
272 $e = CRM_Core_Error
::singleton();
273 if (is_a($errors, 'ErrorType')) {
274 $e->push($errors->getErrorCode(),
276 $errors->getShortMessage() . ' ' . $errors->getLongMessage()
280 foreach ($errors as $error) {
281 $e->push($error->getErrorCode(),
283 $error->getShortMessage() . ' ' . $error->getLongMessage()
295 public function &error($error = NULL) {
296 $e = CRM_Core_Error
::singleton();
297 if (is_object($error)) {
298 $e->push($error->getResponseCode(),
303 elseif (is_string($error)) {
310 $e->push(9001, 0, NULL, "Unknown System Error.");
316 * This function checks to see if we have the right config values.
319 * the error message if any
321 public function checkConfig() {
324 if (empty($this->_paymentProcessor
['signature'])) {
325 $error[] = ts('Store ID is not set in the Administer CiviCRM » System Settings » Payment Processors.');
328 if (empty($this->_paymentProcessor
['password'])) {
329 $error[] = ts('Password is not set in the Administer CiviCRM » System Settings » Payment Processors.');
332 if (!empty($error)) {
333 return implode('<p>', $error);