3 * This file is part of CiviCRM.
5 * CiviCRM is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * CiviCRM is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with CiviCRM. If not, see <http://www.gnu.org/licenses/>.
19 * Licensed to CiviCRM under the GPL v3 or higher
21 * Written and contributed by Ward Vandewege <ward@fsf.org> (http://www.fsf.org)
22 * Modified by Lisa Marie Maginnis <lisa@fsf.org> (http://www.fsf.org)
26 // Define logging level (0 = off, 4 = log everything)
27 define('TRUSTCOMMERCE_LOGGING_LEVEL', 4);
29 require_once 'CRM/Core/Payment.php';
30 class org_fsf_payment_trustcommerce
extends CRM_Core_Payment
{
31 CONST CHARSET
= 'iso-8859-1';
32 CONST AUTH_APPROVED
= 'approve';
33 CONST AUTH_DECLINED
= 'decline';
34 CONST AUTH_BADDATA
= 'baddata';
35 CONST AUTH_ERROR
= 'error';
37 static protected $_mode = NULL;
39 static protected $_params = array();
42 * We only need one instance of this object. So we use the singleton
43 * pattern and cache the instance in this variable
48 static private $_singleton = NULL;
53 * @param string $mode the mode of operation: live or test
56 */ function __construct($mode, &$paymentProcessor) {
59 $this->_paymentProcessor
= $paymentProcessor;
61 $this->_processorName
= ts('TrustCommerce');
63 $config = CRM_Core_Config
::singleton();
64 $this->_setParam('user_name', $paymentProcessor['user_name']);
65 $this->_setParam('password', $paymentProcessor['password']);
67 $this->_setParam('timestamp', time());
69 $this->_setParam('sequence', rand(1, 1000));
70 $this->logging_level
= TRUSTCOMMERCE_LOGGING_LEVEL
;
74 * singleton function used to manage this object
76 * @param string $mode the mode of operation: live or test
83 function &singleton($mode, &$paymentProcessor) {
84 $processorName = $paymentProcessor['name'];
85 if (self
::$_singleton[$processorName] === NULL) {
86 self
::$_singleton[$processorName] = new org_fsf_payment_trustcommerce($mode, $paymentProcessor);
88 return self
::$_singleton[$processorName];
92 * Submit a payment using the TC API
93 * @param array $params The params we will be sending to tclink_send()
94 * @return mixed An array of our results, or an error object if the transaction fails.
97 function doDirectPayment(&$params) {
98 if (!extension_loaded("tclink")) {
99 return self
::error(9001, 'TrustCommerce requires that the tclink module is loaded');
102 /* Copy our paramaters to ourself */
103 foreach ($params as $field => $value) {
104 $this->_setParam($field, $value);
107 /* Get our fields to pass to tclink_send() */
108 $tc_params = $this->_getTrustCommerceFields();
110 /* Are we recurring? If so add the extra API fields. */
111 if (CRM_Utils_Array
::value('is_recur', $params) && $params['contributionRecurID']) {
112 $tc_params = $this->_getRecurPaymentFields($tc_params);
115 /* Pass our cooked params to the alter hook, per Core/Payment/Dummy.php */
116 CRM_Utils_Hook
::alterPaymentProcessorParams($this, $params, $tc_params);
118 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
119 if ($this->_checkDupe($tc_params['ticket'])) {
120 return self
::error(9004, 'It appears that this transaction is a duplicate. Have you already submitted the form once? If so there may have been a connection problem. You can try your transaction again. If you continue to have problems please contact the site administrator.');
123 /* Call the TC API, and grab the reply */
124 $reply = $this->_sendTCRequest($tc_params);
126 /* Parse our reply */
127 $result = $this->_getTCReply($reply);
130 /* We were successful, congrats. Lets wrap it up:
131 * Convert back to dollars
132 * Save the transaction ID
134 $params['trxn_id'] = $reply['transid'];
135 $params['gross_amount'] = $tc_params['amount'] / 100;
140 /* Otherwise we return the error object */
145 function _sendTCRequest($request) {
146 $this->_logger($request);
147 return tclink_send($request);
150 function _logger($params) {
152 foreach ($param as $key => $data) {
153 /* Delete any data we should not be writing to disk. This includes:
154 * custid, password, cc, exp, and cvv
164 $msg .= ' '.$key.' => '.$data;
167 error_log('TrustCommerce:'.$msg);
171 * Gets the recurring billing fields for the TC API
172 * @param array $fields The fields to modify.
173 * @return array The fields for tclink_send(), modified for recurring billing.
176 function _getRecurPaymentFields($fields) {
177 $payments = $this->_getParam('frequency_interval');
178 $cycle = $this->_getParam('frequency_unit');
180 /* Translate billing cycle from CiviCRM -> TC */
196 /* Translate frequency interval from CiviCRM -> TC
197 * Payments are the same, HOWEVER a payment of 1 (forever) should be 0 in TC */
202 $fields['cycle'] = '1'.$cycle; /* The billing cycle in years, months, weeks, or days. */
203 $fields['payments'] = $payments;
204 $fields['action'] = 'store'; /* Change our mode to `store' mode. */
209 /* Parses a response from TC via the tclink_send() command.
210 * @param $reply array The result of a call to tclink_send().
211 * @return mixed self::error() if transaction failed, otherwise returns 0.
213 function _getTCReply($reply) {
215 /* DUPLIATE CODE, please refactor. ~lisa */
217 return self
::error(9002, 'Could not initiate connection to payment gateway');
220 switch($reply['status']) {
221 case self
::AUTH_APPROVED
:
224 case self
::AUTH_DECLINED
:
225 // TODO FIXME be more or less specific?
226 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
227 // See TC documentation for more info
228 return self
::error(9009, "Your transaction was declined: {$reply['declinetype']}");
230 case self
::AUTH_BADDATA
:
231 // TODO FIXME do something with $reply['error'] and $reply['offender']
232 return self
::error(9011, "Invalid credit card information. The following fields were invalid: {$reply['offenders']}.");
234 case self
::AUTH_ERROR
:
235 return self
::error(9002, 'Could not initiate connection to payment gateway');
241 function _getTrustCommerceFields() {
242 // Total amount is from the form contribution field
243 $amount = $this->_getParam('total_amount');
244 // CRM-9894 would this ever be the case??
245 if (empty($amount)) {
246 $amount = $this->_getParam('amount');
249 $fields['custid'] = $this->_getParam('user_name');
250 $fields['password'] = $this->_getParam('password');
251 $fields['action'] = 'sale';
253 // Enable address verification
254 $fields['avs'] = 'y';
256 $fields['address1'] = $this->_getParam('street_address');
257 $fields['zip'] = $this->_getParam('postal_code');
259 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
261 // This assumes currencies where the . is used as the decimal point, like USD
262 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
264 // We need to pass the amount to TrustCommerce in dollar cents
265 $fields['amount'] = $amount * 100;
268 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
271 $fields['cc'] = $this->_getParam('credit_card_number');
272 $fields['cvv'] = $this->_getParam('cvv2');
273 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT
);
274 $exp_year = substr($this->_getParam('year'),-2);
275 $fields['exp'] = "$exp_month$exp_year";
277 if ($this->_mode
!= 'live') {
278 $fields['demo'] = 'y';
284 * Checks to see if invoice_id already exists in db
286 * @param int $invoiceId The ID to check
288 * @return bool True if ID exists, else false
290 function _checkDupe($invoiceId) {
291 require_once 'CRM/Contribute/DAO/Contribution.php';
292 $contribution = new CRM_Contribute_DAO_Contribution();
293 $contribution->invoice_id
= $invoiceId;
294 return $contribution->find();
298 * Get the value of a field if set
300 * @param string $field the field
302 * @return mixed value of the field, or empty string if the field is
305 function _getParam($field) {
306 return CRM_Utils_Array
::value($field, $this->_params
, '');
309 function &error($errorCode = NULL, $errorMessage = NULL) {
310 $e = CRM_Core_Error
::singleton();
312 $e->push($errorCode, 0, NULL, $errorMessage);
315 $e->push(9001, 0, NULL, 'Unknown System Error.');
321 * Set a field to the specified value. Value must be a scalar (int,
322 * float, string, or boolean)
324 * @param string $field
325 * @param mixed $value
327 * @return bool false if value is not a scalar, true if successful
329 function _setParam($field, $value) {
330 if (!is_scalar($value)) {
334 $this->_params
[$field] = $value;
339 * This function checks to see if we have the right config values
341 * @return string the error message if any
344 function checkConfig() {
346 if (empty($this->_paymentProcessor
['user_name'])) {
347 $error[] = ts('Customer ID is not set for this payment processor');
350 if (empty($this->_paymentProcessor
['password'])) {
351 $error[] = ts('Password is not set for this payment processor');
354 if (!empty($error)) {
355 return implode('<p>', $error);
361 function cancelSubscription(&$message = '', $params = array()) {
362 $tc_params['custid'] = $this->_getParam('user_name');
363 $tc_params['password'] = $this->_getParam('password');
364 $tc_params['action'] = 'unstore';
365 $tc_params['billingid'] = CRM_Utils_Array
::value('trxn_id', $params);
367 $result = $this->_sendTCRequest($tc_params);
369 /* Test if call failed */
371 return self
::error(9002, 'Could not initiate connection to payment gateway');
373 /* We are done, pass success */
377 public function install() {
381 public function uninstall() {