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 the TC API
78 * @param array $params The params we will be sending to tclink_send()
79 * @return mixed An array of our results, or an error object if the transaction fails.
82 function doDirectPayment(&$params) {
83 if (!extension_loaded("tclink")) {
84 return self
::error(9001, 'TrustCommerce requires that the tclink module is loaded');
88 if (CRM_Utils_Array
::value('is_recur', $params) &&
89 $params['contributionRecurID']
91 CRM_Utils_Hook
::alterPaymentProcessorParams($this,
96 foreach ($newParams as $field => $value) {
97 $this->_setParam($field, $value);
100 if (CRM_Utils_Array
::value('is_recur', $params) &&
101 $params['contributionRecurID']
103 return $this->doRecurPayment($params);
106 $postFields = array();
107 $tclink = $this->_getTrustCommerceFields();
109 // Set up our call for hook_civicrm_paymentProcessor,
110 // since we now have our parameters as assigned for the AIM back end.
111 CRM_Utils_Hook
::alterPaymentProcessorParams($this,
116 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
117 if ($this->_checkDupe($tclink['ticket'])) {
118 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.');
121 $result = tclink_send($tclink);
124 return self
::error(9002, 'Could not initiate connection to payment gateway');
127 foreach ($result as $field => $value) {
128 error_log("result: $field => $value");
131 switch($result['status']) {
132 case self
::AUTH_APPROVED
:
135 case self
::AUTH_DECLINED
:
136 // TODO FIXME be more or less specific?
137 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
138 // See TC documentation for more info
139 return self
::error(9009, "Your transaction was declined: {$result['declinetype']}");
141 case self
::AUTH_BADDATA
:
142 // TODO FIXME do something with $result['error'] and $result['offender']
143 return self
::error(9011, "Invalid credit card information. Please re-enter.");
145 case self
::AUTH_ERROR
:
146 return self
::error(9002, 'Could not initiate connection to payment gateway');
152 $params['trxn_id'] = $result['transid'];
153 $params['gross_amount'] = $tclink['amount'] / 100;
159 * Submit an Automated Recurring Billing subscription
161 * @param array $params assoc array of input parameters for this transaction
163 * @return array the result in a nice formatted array (or an error object)
166 function doRecurPayment(&$params) {
167 $payments = $this->_getParam('frequency_interval');
168 $cycle = $this->_getParam('frequency_unit');
170 /* Sort out our billing scheme */
185 return self
::error(9001, 'Payment interval not set! Unable to process payment.');
190 $params['authnow'] = 'y'; /* Process this payment `now' */
191 $params['cycle'] = $cycle; /* The billing cycle in years, months, weeks, or days. */
192 $params['payments'] = $payments;
195 $tclink = $this->_getTrustCommerceFields();
197 // Set up our call for hook_civicrm_paymentProcessor,
198 // since we now have our parameters as assigned for the AIM back end.
199 CRM_Utils_Hook
::alterPaymentProcessorParams($this,
204 // TrustCommerce will not refuse duplicates, so we should check if the user already submitted this transaction
205 if ($this->_checkDupe($tclink['ticket'])) {
206 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.');
209 $result = tclink_send($tclink);
211 $result = _getTrustCommereceResponse($result);
214 /* Transaction was sucessful */
215 $params['trxn_id'] = $result['transid']; /* Get our transaction ID */
216 $params['gross_amount'] = $tclink['amount']/100; /* Convert from cents to dollars */
219 /* Transaction was *not* successful */
224 /* Parses a response from TC via the tclink_send() command.
225 * @param $reply array The result of a call to tclink_send().
226 * @return mixed self::error() if transaction failed, otherwise returns 0.
228 function _getTrustCommerceResponse($reply) {
230 /* DUPLIATE CODE, please refactor. ~lisa */
232 return self
::error(9002, 'Could not initiate connection to payment gateway');
235 switch($result['status']) {
236 case self
::AUTH_APPROVED
:
239 case self
::AUTH_DECLINED
:
240 // TODO FIXME be more or less specific?
241 // declinetype can be: decline, avs, cvv, call, expiredcard, carderror, authexpired, fraud, blacklist, velocity
242 // See TC documentation for more info
243 return self
::error(9009, "Your transaction was declined: {$result['declinetype']}");
245 case self
::AUTH_BADDATA
:
246 // TODO FIXME do something with $result['error'] and $result['offender']
247 return self
::error(9011, "Invalid credit card information. Please re-enter.");
249 case self
::AUTH_ERROR
:
250 return self
::error(9002, 'Could not initiate connection to payment gateway');
256 function _getTrustCommerceFields() {
257 // Total amount is from the form contribution field
258 $amount = $this->_getParam('total_amount');
259 // CRM-9894 would this ever be the case??
260 if (empty($amount)) {
261 $amount = $this->_getParam('amount');
264 $fields['custid'] = $this->_getParam('user_name');
265 $fields['password'] = $this->_getParam('password');
266 $fields['action'] = 'sale';
268 // Enable address verification
269 $fields['avs'] = 'y';
271 $fields['address1'] = $this->_getParam('street_address');
272 $fields['zip'] = $this->_getParam('postal_code');
274 $fields['name'] = $this->_getParam('billing_first_name') . ' ' . $this->_getParam('billing_last_name');
276 // This assumes currencies where the . is used as the decimal point, like USD
277 $amount = preg_replace("/([^0-9\\.])/i", "", $amount);
279 // We need to pass the amount to TrustCommerce in dollar cents
280 $fields['amount'] = $amount * 100;
283 $fields['ticket'] = substr($this->_getParam('invoiceID'), 0, 20);
286 $fields['cc'] = $this->_getParam('credit_card_number');
287 $fields['cvv'] = $this->_getParam('cvv2');
288 $exp_month = str_pad($this->_getParam('month'), 2, '0', STR_PAD_LEFT
);
289 $exp_year = substr($this->_getParam('year'),-2);
290 $fields['exp'] = "$exp_month$exp_year";
292 if ($this->_mode
!= 'live') {
293 $fields['demo'] = 'y';
299 * Checks to see if invoice_id already exists in db
301 * @param int $invoiceId The ID to check
303 * @return bool True if ID exists, else false
305 function _checkDupe($invoiceId) {
306 require_once 'CRM/Contribute/DAO/Contribution.php';
307 $contribution = new CRM_Contribute_DAO_Contribution();
308 $contribution->invoice_id
= $invoiceId;
309 return $contribution->find();
313 * Get the value of a field if set
315 * @param string $field the field
317 * @return mixed value of the field, or empty string if the field is
320 function _getParam($field) {
321 return CRM_Utils_Array
::value($field, $this->_params
, '');
324 function &error($errorCode = NULL, $errorMessage = NULL) {
325 $e = CRM_Core_Error
::singleton();
327 $e->push($errorCode, 0, NULL, $errorMessage);
330 $e->push(9001, 0, NULL, 'Unknown System Error.');
336 * Set a field to the specified value. Value must be a scalar (int,
337 * float, string, or boolean)
339 * @param string $field
340 * @param mixed $value
342 * @return bool false if value is not a scalar, true if successful
344 function _setParam($field, $value) {
345 if (!is_scalar($value)) {
349 $this->_params
[$field] = $value;
354 * This function checks to see if we have the right config values
356 * @return string the error message if any
359 function checkConfig() {
361 if (empty($this->_paymentProcessor
['user_name'])) {
362 $error[] = ts('Customer ID is not set for this payment processor');
365 if (empty($this->_paymentProcessor
['password'])) {
366 $error[] = ts('Password is not set for this payment processor');
369 if (!empty($error)) {
370 return implode('<p>', $error);
376 function cancelSubscriptionURL($entityID = NULL, $entity = NULL) {
377 if ($entityID && $entity == 'membership') {
378 require_once 'CRM/Contact/BAO/Contact/Utils.php';
379 $contactID = CRM_Core_DAO
::getFieldValue("CRM_Member_DAO_Membership", $entityID, "contact_id");
380 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID, NULL, 'inf');
382 return CRM_Utils_System
::url('civicrm/contribute/unsubscribe',
383 "reset=1&mid={$entityID}&cs={$checksumValue}", TRUE, NULL, FALSE, FALSE
387 return ($this->_mode
== 'test') ?
'https://test.authorize.net' : 'https://authorize.net';
390 function cancelSubscription() {
391 $template = CRM_Core_Smarty
::singleton();
393 $template->assign('subscriptionType', 'cancel');
395 $template->assign('apiLogin', $this->_getParam('apiLogin'));
396 $template->assign('paymentKey', $this->_getParam('paymentKey'));
397 $template->assign('subscriptionId', $this->_getParam('subscriptionId'));
399 $arbXML = $template->fetch('CRM/Contribute/Form/Contribution/AuthorizeNetARB.tpl');
401 // submit to authorize.net
402 $submit = curl_init($this->_paymentProcessor
['url_recur']);
404 return self
::error(9002, 'Could not initiate connection to payment gateway');
407 curl_setopt($submit, CURLOPT_RETURNTRANSFER
, 1);
408 curl_setopt($submit, CURLOPT_HTTPHEADER
, array("Content-Type: text/xml"));
409 curl_setopt($submit, CURLOPT_HEADER
, 1);
410 curl_setopt($submit, CURLOPT_POSTFIELDS
, $arbXML);
411 curl_setopt($submit, CURLOPT_POST
, 1);
412 curl_setopt($submit, CURLOPT_SSL_VERIFYPEER
, 0);
414 $response = curl_exec($submit);
417 return self
::error(curl_errno($submit), curl_error($submit));
422 $responseFields = $this->_ParseArbReturn($response);
424 if ($responseFields['resultCode'] == 'Error') {
425 return self
::error($responseFields['code'], $responseFields['text']);
428 // carry on cancelation procedure
432 public function install() {
436 public function uninstall() {