4 * Licensed to CiviCRM under the GPL v3 or higher
6 * Written and contributed by Ward Vandewege <ward@fsf.org> (http://www.fsf.org)
7 * Modified by Lisa Marie Maginnis <lisa@fsf.org> (http://www.fsf.org)
11 // Define logging level (0 = off, 4 = log everything)
12 define('TRUSTCOMMERCE_LOGGING_LEVEL', 4);
14 require_once 'CRM/Core/Payment.php';
15 class org_fsf_payment_trustcommerce
extends CRM_Core_Payment
{
16 CONST CHARSET
= 'iso-8859-1';
17 CONST AUTH_APPROVED
= 'approve';
18 CONST AUTH_DECLINED
= 'decline';
19 CONST AUTH_BADDATA
= 'baddata';
20 CONST AUTH_ERROR
= 'error';
22 static protected $_mode = NULL;
24 static protected $_params = array();
27 * We only need one instance of this object. So we use the singleton
28 * pattern and cache the instance in this variable
33 static private $_singleton = NULL;
38 * @param string $mode the mode of operation: live or test
41 */ function __construct($mode, &$paymentProcessor) {
44 $this->_paymentProcessor
= $paymentProcessor;
46 $this->_processorName
= ts('TrustCommerce');
48 $config = CRM_Core_Config
::singleton();
49 $this->_setParam('user_name', $paymentProcessor['user_name']);
50 $this->_setParam('password', $paymentProcessor['password']);
52 $this->_setParam('timestamp', time());
54 $this->_setParam('sequence', rand(1, 1000));
55 $this->logging_level
= TRUSTCOMMERCE_LOGGING_LEVEL
;
59 * singleton function used to manage this object
61 * @param string $mode the mode of operation: live or test
68 function &singleton($mode, &$paymentProcessor) {
69 $processorName = $paymentProcessor['name'];
70 if (self
::$_singleton[$processorName] === NULL) {
71 self
::$_singleton[$processorName] = new org_fsf_payment_trustcommerce($mode, $paymentProcessor);
73 return self
::$_singleton[$processorName];
77 * Submit a payment using Advanced Integration Method
79 * @param array $params assoc array of input parameters for this transaction
81 * @return array the result in a nice formatted array (or an error object)
84 function doDirectPayment(&$params) {
85 if (!extension_loaded("tclink")) {
86 return self
::error(9001, 'TrustCommerce requires that the tclink module is loaded');
90 if (CRM_Utils_Array
::value('is_recur', $params) &&
91 $params['contributionRecurID']
93 CRM_Utils_Hook
::alterPaymentProcessorParams($this,
98 foreach ($newParams as $field => $value) {
99 $this->_setParam($field, $value);
102 if (CRM_Utils_Array
::value('is_recur', $params) &&
103 $params['contributionRecurID']
105 return $this->doRecurPayment($params);
108 $postFields = array();
109 $tclink = $this->_getTrustCommerceFields();
111 // Set up our call for hook_civicrm_paymentProcessor,
112 // since we now have our parameters as assigned for the AIM back end.
113 CRM_Utils_Hook
::alterPaymentProcessorParams($this,
118 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
119 if ($this->_checkDupe($tclink['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 $result = tclink_send($tclink);
126 return self
::error(9002, 'Could not initiate connection to payment gateway');
129 foreach ($result as $field => $value) {
130 error_log("result: $field => $value");
133 switch($result['status']) {
134 case self
::AUTH_APPROVED
:
137 case self
::AUTH_DECLINED
:
138 // TODO FIXME be more or less specific?
139 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
140 // See TC documentation for more info
141 return self
::error(9009, "Your transaction was declined: {$result['declinetype']}");
143 case self
::AUTH_BADDATA
:
144 // TODO FIXME do something with $result['error'] and $result['offender']
145 return self
::error(9011, "Invalid credit card information. Please re-enter.");
147 case self
::AUTH_ERROR
:
148 return self
::error(9002, 'Could not initiate connection to payment gateway');
154 $params['trxn_id'] = $result['transid'];
155 $params['gross_amount'] = $tclink['amount'] / 100;
161 * Submit an Automated Recurring Billing subscription
163 * @param array $params assoc array of input parameters for this transaction
165 * @return array the result in a nice formatted array (or an error object)
168 function doRecurPayment(&$params) {
169 $payments = $this->_getParam('frequency_interval');
170 $cycle = $this->_getParam('frequency_unit');
172 /* Sort out our billing scheme */
187 return self
::error(9001, 'Payment interval not set! Unable to process payment.');
192 $params['authnow'] = 'y'; /* Process this payment `now' */
193 $params['cycle'] = $cycle; /* The billing cycle in years, months, weeks, or days. */
194 $params['payments'] = $payments;
197 $tclink = $this->_getTrustCommerceFields();
199 // Set up our call for hook_civicrm_paymentProcessor,
200 // since we now have our parameters as assigned for the AIM back end.
201 CRM_Utils_Hook
::alterPaymentProcessorParams($this,
206 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
207 if ($this->_checkDupe($tclink['ticket'])) {
208 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.');
211 $result = tclink_send($tclink);
213 $result = _getTrustCommereceResponse($result);
216 /* Transaction was sucessful */
217 $params['trxn_id'] = $result['transid']; /* Get our transaction ID */
218 $params['gross_amount'] = $tclink['amount']/100; /* Convert from cents to dollars */
221 /* Transaction was *not* successful */
226 /* Parses a response from TC via the tclink_send() command.
227 * @param $reply array The result of a call to tclink_send().
228 * @return mixed self::error() if transaction failed, otherwise returns 0.
230 function _getTrustCommerceResponse($reply) {
232 /* DUPLIATE CODE, please refactor. ~lisa */
234 return self
::error(9002, 'Could not initiate connection to payment gateway');
237 switch($result['status']) {
238 case self
::AUTH_APPROVED
:
241 case self
::AUTH_DECLINED
:
242 // TODO FIXME be more or less specific?
243 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
244 // See TC documentation for more info
245 return self
::error(9009, "Your transaction was declined: {$result['declinetype']}");
247 case self
::AUTH_BADDATA
:
248 // TODO FIXME do something with $result['error'] and $result['offender']
249 return self
::error(9011, "Invalid credit card information. Please re-enter.");
251 case self
::AUTH_ERROR
:
252 return self
::error(9002, 'Could not initiate connection to payment gateway');
258 function _getTrustCommerceFields() {
259 // Total amount is from the form contribution field
260 $amount = $this->_getParam('total_amount');
261 // CRM-9894 would this ever be the case??
262 if (empty($amount)) {
263 $amount = $this->_getParam('amount');
266 $fields['custid'] = $this->_getParam('user_name');
267 $fields['password'] = $this->_getParam('password');
268 $fields['action'] = 'sale';
270 // Enable address verification
271 $fields['avs'] = 'y';
273 $fields['address1'] = $this->_getParam('street_address');
274 $fields['zip'] = $this->_getParam('postal_code');
276 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
278 // This assumes currencies where the . is used as the decimal point, like USD
279 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
281 // We need to pass the amount to TrustCommerce in dollar cents
282 $fields['amount'] = $amount * 100;
285 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
288 $fields['cc'] = $this->_getParam('credit_card_number');
289 $fields['cvv'] = $this->_getParam('cvv2');
290 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT
);
291 $exp_year = substr($this->_getParam('year'),-2);
292 $fields['exp'] = "$exp_month$exp_year";
294 if ($this->_mode
!= 'live') {
295 $fields['demo'] = 'y';
301 * Checks to see if invoice_id already exists in db
303 * @param int $invoiceId The ID to check
305 * @return bool True if ID exists, else false
307 function _checkDupe($invoiceId) {
308 require_once 'CRM/Contribute/DAO/Contribution.php';
309 $contribution = new CRM_Contribute_DAO_Contribution();
310 $contribution->invoice_id
= $invoiceId;
311 return $contribution->find();
315 * Get the value of a field if set
317 * @param string $field the field
319 * @return mixed value of the field, or empty string if the field is
322 function _getParam($field) {
323 return CRM_Utils_Array
::value($field, $this->_params
, '');
326 function &error($errorCode = NULL, $errorMessage = NULL) {
327 $e = CRM_Core_Error
::singleton();
329 $e->push($errorCode, 0, NULL, $errorMessage);
332 $e->push(9001, 0, NULL, 'Unknown System Error.');
338 * Set a field to the specified value. Value must be a scalar (int,
339 * float, string, or boolean)
341 * @param string $field
342 * @param mixed $value
344 * @return bool false if value is not a scalar, true if successful
346 function _setParam($field, $value) {
347 if (!is_scalar($value)) {
351 $this->_params
[$field] = $value;
356 * This function checks to see if we have the right config values
358 * @return string the error message if any
361 function checkConfig() {
363 if (empty($this->_paymentProcessor
['user_name'])) {
364 $error[] = ts('Customer ID is not set for this payment processor');
367 if (empty($this->_paymentProcessor
['password'])) {
368 $error[] = ts('Password is not set for this payment processor');
371 if (!empty($error)) {
372 return implode('<p>', $error);
378 function cancelSubscriptionURL($entityID = NULL, $entity = NULL) {
379 if ($entityID && $entity == 'membership') {
380 require_once 'CRM/Contact/BAO/Contact/Utils.php';
381 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
382 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
384 return CRM_Utils_System
::url('civicrm/contribute/unsubscribe',
385 "reset=1&mid={$entityID}&cs={$checksumValue}", TRUE, NULL, FALSE, FALSE
389 return ($this->_mode
== 'test') ?
'https://test.authorize.net' : 'https://authorize.net';
392 function cancelSubscription() {
393 $template = CRM_Core_Smarty
::singleton();
395 $template->assign('subscriptionType', 'cancel');
397 $template->assign('apiLogin', $this->_getParam('apiLogin'));
398 $template->assign('paymentKey', $this->_getParam('paymentKey'));
399 $template->assign('subscriptionId', $this->_getParam('subscriptionId'));
401 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
403 // submit to authorize.net
404 $submit = curl_init($this->_paymentProcessor
['url_recur']);
406 return self
::error(9002, 'Could not initiate connection to payment gateway');
409 curl_setopt($submit, CURLOPT_RETURNTRANSFER
, 1);
410 curl_setopt($submit, CURLOPT_HTTPHEADER
, array("Content-Type: text/xml"));
411 curl_setopt($submit, CURLOPT_HEADER
, 1);
412 curl_setopt($submit, CURLOPT_POSTFIELDS
, $arbXML);
413 curl_setopt($submit, CURLOPT_POST
, 1);
414 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER
, 0);
416 $response = curl_exec($submit);
419 return self
::error(curl_errno($submit), curl_error($submit));
424 $responseFields = $this->_ParseArbReturn($response);
426 if ($responseFields['resultCode'] == 'Error') {
427 return self
::error($responseFields['code'], $responseFields['text']);
430 // carry on cancelation procedure
434 public function install() {
438 public function uninstall() {